import React, { type Dispatch, type SetStateAction } from 'react';
import { useApolloClient } from '@apollo/client';
import { Button, Popover, useToast } from '@theorchard/suite-components';
import { GlyphIcon } from '@theorchard/suite-icons';
import { useDeleteMappedSigningEntity } from 'src/apollo/mutations/reference-sap-profit-center';
import {
    failedToDeleteSigningEntity,
    signingEntityDeletedSuccess,
} from 'src/apollo/type-constants/reference-sap-profit-center';
import { useSidecarActivity } from 'src/components/reference-sap-profit-center-edit/sidecar-activity-context';

export interface ConfirmDeletePopoverIconPropTypes {
    id: string;
    legalName: string;
    onDeleteSuccess?: () => void;
    setError: Dispatch<SetStateAction<string | null>>;
}

export const ConfirmDeletePopoverIcon: React.FC<
    ConfirmDeletePopoverIconPropTypes
> = ({ id, legalName, onDeleteSuccess, setError }) => {
    const addToast = useToast();
    const { isDeletingEntity, setIsDeletingEntity } = useSidecarActivity();
    const [showContent, setShowContent] = React.useState(false);
    const [isDeleting, setIsDeleting] = React.useState(false);
    const client = useApolloClient();

    const deleteMappedSigningEntity = useDeleteMappedSigningEntity();

    const handleDelete = () => {
        setError('');
        setIsDeleting(true);
        setIsDeletingEntity(true);
        deleteMappedSigningEntity({
            variables: { signingEntitySapProfitCenterId: id },
        })
            .then(() => {
                addToast(signingEntityDeletedSuccess(legalName));
                setShowContent(false);

                client.cache.evict({
                    id: 'ROOT_QUERY',
                    fieldName: 'abacusReferenceSapProfitCenterList',
                });

                client.cache.evict({
                    id: 'ROOT_QUERY',
                    fieldName: 'abacusSigningEntitiesBySapProfitCenter',
                });

                onDeleteSuccess?.();
            })
            .catch(() => {
                setError(`Error: ${failedToDeleteSigningEntity(legalName)}`);
            })
            .finally(() => {
                setIsDeleting(false);
                setIsDeletingEntity(false);
            });
    };

    const renderPopoverContent = () => (
        <div className="py-2">
            <p>Are you sure you want to delete this item?</p>
            <div className="d-flex justify-content-between mt-3">
                <Button
                    disabled={isDeleting}
                    size="sm"
                    variant="secondary"
                    onClick={() => setShowContent(false)}
                >
                    Cancel
                </Button>
                <Button
                    disabled={isDeleting}
                    size="sm"
                    variant="danger"
                    onClick={handleDelete}
                >
                    {isDeleting ? 'Deleting...' : 'Confirm'}
                </Button>
            </div>
        </div>
    );

    return (
        <Popover
            id="MyPopoverConfirmation"
            content={renderPopoverContent()}
            show={showContent}
        >
            <div
                className={`d-inline-block${isDeletingEntity ? ' disabled' : ''}`}
                role="button"
                tabIndex={0}
                onClick={() => !isDeletingEntity && setShowContent(true)}
            >
                <GlyphIcon name="trash" size={16} />
            </div>
        </Popover>
    );
};

export default ConfirmDeletePopoverIcon;
