import React, { useState } from 'react';
import { ABACUS_ACTION_STATUSES } from '@theorchard/accounting-apps-shared';
import {
    Alert,
    ExpandableContent,
    SkeletonLoader,
    useToast,
} from '@theorchard/suite-components';
import { useIdentity } from '@theorchard/suite-frontend';
import { useUpdateAbacusState } from 'src/apollo/mutations/abacus-state';
import { useDeleteAccountPayeeTaxFormInfo } from 'src/apollo/mutations/account-payee';
import { getAccountFullDetail } from 'src/apollo/queries/account';
import { useCanPerformAction } from 'src/apollo/queries/can-perform';
import { PERMISSIONS_ACTIONS, PERMISSIONS_RESOURCE_TYPES } from 'src/constants';
import type { AlertProps } from '@theorchard/suite-components/dist/esm/src/components/alert/alert';
import type { GetAccountFullDetailQuery } from 'src/apollo/queries/account/__generated__/get-account-full-detail';

type ActionStates = NonNullable<
    NonNullable<GetAccountFullDetailQuery['abacusAccount']>['accountPayee']
>['actionStates'][0];

export interface SubsectionDataType {
    title: string;
    subtitle: string | React.ReactNode;
    notes?: ActionStates['message'];
    variant: AlertProps['variant'];
}

export interface TaxFormInfoSubsectionPropTypes {
    accountId: string;
    accountPayeeId?: string;
    isTaxFormInfoEmpty: boolean;
    subsection: SubsectionDataType;
    taxEligibilityStateId?: string;
    isNonSpanishTaxResident?: boolean;
}

const CLASS_NAME = 'TaxFormInfoSubsection';

export const REQUEST_NEW_FORM_TOAST_MSG = {
    SUCESS: 'An updated form has been requested successfully',
    ERROR: 'An error occurred. Please try again later.',
};

export const REQUEST_NEW_FORM_BTN_TEXT = 'I’ve received a new tax form';

export const TaxFormInfoSubsection: React.FC<
    TaxFormInfoSubsectionPropTypes
> = ({
    accountId,
    accountPayeeId,
    subsection,
    isTaxFormInfoEmpty,
    taxEligibilityStateId,
    isNonSpanishTaxResident = false,
}) => {
    const identity = useIdentity();
    const [error, setError] = useState();
    const toast = useToast();
    const { title, subtitle, notes, variant } = subsection;
    const { data: canEditTaxInfo, loading: canPerformActionQueryLoading } =
        useCanPerformAction(
            identity.id,
            PERMISSIONS_ACTIONS.EDIT,
            PERMISSIONS_RESOURCE_TYPES.TAX_INFO
        );
    const { updateAbacusState, loading: updateAbacusStateLoading } =
        useUpdateAbacusState([
            {
                query: getAccountFullDetail,
                variables: { accountId: accountId },
            },
        ]);

    if (!accountPayeeId)
        return (
            <Alert
                text="Error: accountPayeeId is not defined"
                variant="error"
            />
        );

    const { deleteTaxFormInfo, loading: deleteTaxFormInfoLoading } =
        useDeleteAccountPayeeTaxFormInfo(accountId, {
            accountPayeeId: accountPayeeId,
        });

    const loading =
        updateAbacusStateLoading ||
        deleteTaxFormInfoLoading ||
        canPerformActionQueryLoading;

    if (loading) {
        return <SkeletonLoader numberOfItems={4} vertical />;
    }

    const handleAlertBtnClick = async () => {
        if (!isTaxFormInfoEmpty && accountPayeeId) {
            const deleteTaxFormInfoVariables = {
                accountPayeeId: accountPayeeId,
            };
            return await deleteTaxFormInfo({
                variables: deleteTaxFormInfoVariables,
            })
                .then(() => {
                    toast(REQUEST_NEW_FORM_TOAST_MSG.SUCESS);
                })
                .catch(error => {
                    toast(REQUEST_NEW_FORM_TOAST_MSG.ERROR);
                    setError(error?.message || JSON.stringify(error));
                });
        }
        if (taxEligibilityStateId) {
            const updateStateVariables = {
                abacusStateId: taxEligibilityStateId,
                actionStatus: ABACUS_ACTION_STATUSES.RUNNING,
            };
            updateAbacusState({ variables: updateStateVariables })
                .then(() => {
                    toast(REQUEST_NEW_FORM_TOAST_MSG.SUCESS);
                })
                .catch(err => {
                    toast(REQUEST_NEW_FORM_TOAST_MSG.ERROR);
                    setError(err[0].message || JSON.stringify(err));
                });
        }
    };
    const buttonConfig =
        canEditTaxInfo && !isNonSpanishTaxResident
            ? {
                  text: REQUEST_NEW_FORM_BTN_TEXT,
                  onClick: () => {
                      handleAlertBtnClick();
                  },
              }
            : undefined;

    return (
        <div className={CLASS_NAME}>
            <div className={`${CLASS_NAME}-inner`}>
                {error && <Alert text={error} variant="error" />}
                <Alert
                    title={title}
                    text={
                        <div>
                            <div> {subtitle} </div>
                            {notes && (
                                <ExpandableContent
                                    className={`${CLASS_NAME}Notes`}
                                    expandLabel="See notes"
                                    collapseLabel="Hide notes"
                                >
                                    {notes}
                                </ExpandableContent>
                            )}
                        </div>
                    }
                    variant={variant}
                    button={buttonConfig}
                />
            </div>
        </div>
    );
};

export default TaxFormInfoSubsection;
