/**
 * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). All Rights Reserved.
 *
 * This software is the property of WSO2 LLC. and its suppliers, if any.
 * Dissemination of any information or reproduction of any material contained
 * herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
 * You may not alter or remove any copyright or other notice from copies of this content.
 */

import { IdentifiableComponentInterface, SBACInterface } from "@wso2is/core/models";
import {
    ConfirmationModal,
    ContentLoader, EmphasizedSegment,
    EmptyPlaceholder,
    Heading,
    ListLayout
} from "@wso2is/react-components";
import { getEmptyPlaceholderIllustrations } from "apps/console/src/features/core";
import React, { FunctionComponent, ReactElement, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Input } from "semantic-ui-react";
import { PermissionListAPIResource } from "./permission-list-api-resource";
import { ExtendedFeatureConfigInterface } from "../../../../configs/models";
import { APIResourcePanesCommonPropsInterface, APIResourcePermissionInterface } from "../../models";

/**
 * Prop-types for the API resources page component.
 */
type PermissionAPIResourceInterface = SBACInterface<ExtendedFeatureConfigInterface> &
    IdentifiableComponentInterface & APIResourcePanesCommonPropsInterface;

/**
 * API Resources listing page.
 *
 * @param props - Props injected to the component.
 * @returns API Resources Page component
 */
export const PermissionAPIResource: FunctionComponent<PermissionAPIResourceInterface> = (
    props: PermissionAPIResourceInterface
): ReactElement => {

    const {
        apiResourceData,
        isAPIResourceDataLoading,
        isSubmitting,
        isReadOnly,
        isManagedByChoreo,
        handleUpdateAPIResource,
        ["data-componentid"]: componentId
    } = props;

    const { t } = useTranslation();

    const [ permissionList, setPermissionList ] = useState<APIResourcePermissionInterface[]>([]);
    const [ serachedPermissionList,  setSearchedPermissionList ] = useState<APIResourcePermissionInterface[]>([]);
    const [ deletingAPIResourcePermission, setDeletingAPIResourcePermission ]
        = useState<APIResourcePermissionInterface>(undefined);
    const [ permissionSearchQuery, setPermissionSearchQuery ] = useState<string>("");

    /**
     * Set the permission list.
     */
    useEffect(() => {
        if (apiResourceData) {
            setPermissionList(apiResourceData.permissions);
            setSearchedPermissionList(apiResourceData.permissions);
        }
    }, [ apiResourceData ]);

    /**
     * Handles the search query change.
     * 
     * @param event - Change event
     */
    const searchPermission = (event: React.ChangeEvent<HTMLInputElement>) => {
        const changeValue: string = event.target.value;

        setPermissionSearchQuery(changeValue);
        if (changeValue.length > 0) {
            // Filter the permission list using the `displayName`
            setSearchedPermissionList(
                permissionList.filter(
                    (permission: APIResourcePermissionInterface) => {
                        const displayName: string = permission.displayName;
                        
                        return displayName.toLowerCase().includes(changeValue.toLowerCase());
                    }  
                )
            );
        } else {
            setSearchedPermissionList(permissionList);
        }
    };

    /**
     * Handles the search query clear.
     */
    const clearSearchPermission = () => {
        setPermissionSearchQuery("");
        setSearchedPermissionList(permissionList);
    };

    /**
     * Handles the API resource permission delete action.
     */
    const deletePermission = (): void => {
        handleUpdateAPIResource(
            {
                deletedPermissions: [ deletingAPIResourcePermission.id ]
            },
            (): void => setDeletingAPIResourcePermission(undefined)
        );
    };

    return (
        !isAPIResourceDataLoading
            ? (
                <>
                    {
                        <EmphasizedSegment className="padded">
                            <Heading as="h4" compact>
                                { t("extensions:develop.apiResource.tabs.permissions.title") }
                            </Heading>
                            <Heading as="h6" color="grey" subHeading className="mb-5">
                                { t("extensions:develop.apiResource.tabs.permissions.subTitle") }
                            </Heading>
                            <ListLayout
                                showTopActionPanel={ !isAPIResourceDataLoading && permissionList?.length > 0 }
                                listItemLimit={ 10 }
                                showPagination={ false }
                                onPageChange={ () => null }
                                totalPages={ 10 }
                                data-testid={ `${componentId}-list-layout` }
                                totalListSize={ permissionList?.length }
                                leftActionPanel={
                                    (<div className="advanced-search-wrapper aligned-left fill-default">
                                        <Input
                                            className="advanced-search with-add-on"
                                            data-testid={ `${componentId}-list-search-input` }
                                            icon="search"
                                            iconPosition="left"
                                            onChange={ searchPermission }
                                            placeholder={ t("extensions:develop.apiResource.tabs.permissions.search") }
                                            floated="right"
                                            size="small"
                                            value={ permissionSearchQuery }
                                        />
                                    </div>)
                                }
                            >
                                {
                                    !permissionList
                                        ? (
                                            <EmptyPlaceholder
                                                subtitle={ [ t("extensions:develop.apiResource.apiResourceError." +
                                                    "subtitles.0"),
                                                t("extensions:develop.apiResource.apiResourceError.subtitles.1") ] }
                                                title={ t("extensions:develop.apiResource.apiResourceError.title") }
                                                image={ getEmptyPlaceholderIllustrations().genericError }
                                                imageSize="tiny"
                                            />
                                        )
                                        : (
                                            <PermissionListAPIResource
                                                isAPIResourceDataLoading={ isAPIResourceDataLoading }
                                                isReadOnly={ isReadOnly }
                                                isManagedByChoreo={ isManagedByChoreo }
                                                permissionList={ permissionList }
                                                serachedPermissionList={ serachedPermissionList }
                                                isSubmitting={ isSubmitting }
                                                clearSearchPermission={ clearSearchPermission }
                                                setRemovePermission={ setDeletingAPIResourcePermission }
                                            />
                                        )
                                }
                            </ListLayout>
                        </EmphasizedSegment>
                    }

                    {
                        deletingAPIResourcePermission && (
                            <ConfirmationModal
                                primaryActionLoading={ isSubmitting }
                                onClose={ (): void => setDeletingAPIResourcePermission(undefined) }
                                type="negative"
                                assertionHint={ t("extensions:develop.apiResource.confirmations." +
                                    "deleteAPIResourcePermission.assertionHint") }
                                assertionType="checkbox"
                                primaryAction={ t("common:confirm") }
                                secondaryAction={ t("common:cancel") }
                                onSecondaryActionClick={ (): void => setDeletingAPIResourcePermission(undefined) }
                                onPrimaryActionClick={ (): void => deletePermission() }
                                data-testid={ `${componentId}-delete-confirmation-modal` }
                                closeOnDimmerClick={ false }
                            >
                                <ConfirmationModal.Header
                                    data-testid={ `${componentId}-delete-confirmation-modal-header` }
                                >
                                    { t("extensions:develop.apiResource.confirmations.deleteAPIResourcePermission." + 
                                        "header") }
                                </ConfirmationModal.Header>
                                <ConfirmationModal.Message
                                    attached
                                    negative
                                    data-testid={ `${componentId}-delete-confirmation-modal-message` }
                                >
                                    { t("extensions:develop.apiResource.confirmations.deleteAPIResourcePermission." + 
                                        "message") }
                                </ConfirmationModal.Message>
                                <ConfirmationModal.Content
                                    data-testid={ `${componentId}-delete-confirmation-modal-content` }
                                >
                                    { t("extensions:develop.apiResource.confirmations.deleteAPIResourcePermission." + 
                                        "content") }
                                </ConfirmationModal.Content>
                            </ConfirmationModal>
                        )
                    }
                </>
            )
            : <ContentLoader dimmer />
    );
};

/**
 * Default props for the component.
 */
PermissionAPIResource.defaultProps = {
    "data-componentid": "permission-api-resource"
};
