import type { FC } from 'react';
import React, { useState } from 'react';
import { Button } from '@theorchard/suite-components';
import { useUpdateStatementPeriodPaymentEntity } from 'src/apollo/mutations/statement-periods';
import { STATEMENT_PERIOD_STATUSES } from 'src/constants';
import { PopupModal } from '../shared/popup-modal';
import type { GetStatementPeriodQuery } from 'src/apollo/queries/statement-periods/__generated__/statement-period';
import { useMoneyhubDbtRefresh } from 'src/apollo/mutations/moneyhubDbtRefresh';
import { AccountingDBTModel } from 'src/apollo/definitions/globalTypes';

type AbacusStatementPeriod = NonNullable<
    GetStatementPeriodQuery['abacusStatementPeriod']
>;
type AbacusStatementPaymentEntity = NonNullable<
    AbacusStatementPeriod['paymentEntities'][0]
>;

export const TERM_SHOW_IN_ACCOUNTING = 'Show to customer';
const TERM_SHOW_IN_ACCOUNTING_MODAL_TITLE = 'Warning';
const TERM_SHOW_IN_ACCOUNTING_MODAL_SUBTITLE = 'Are you sure?';
const TERM_SHOW_IN_ACCOUNTING_MODAL_TEXT =
    'You will be showing all activity for this statement period for the accounts paid by the selected entity, ie. the period will be live.';
const TERM_SHOW_IN_ACCOUNTING_MODAL_TEXT_WARNING =
    'You cannot undo this action!';
export const TERM_LIVE_IN_ACCOUNTING =
    'The statement is available to customers in the Accounting app.';
const TERM_SHOW_IN_ACCOUNTING_MODAL_CONFIRM = 'Yes, Show';
const TERM_SHOW_IN_ACCOUNTING_MODAL_CANCEL = 'Cancel';

const CLASS_NAME = 'ShowCustomerAccounting';
const TEST_ID_SHOW_TO_ACCOUNTING_MODAL = 'ShowCustomerAccountingModalTestid';
const MODELS_TO_REFRESH = Object.freeze([
    AccountingDBTModel.CONTRACTS,
    AccountingDBTModel.STATEMENTS,
    AccountingDBTModel.LEDGER,
    AccountingDBTModel.EXPENSES,
    AccountingDBTModel.ADVANCES,
    AccountingDBTModel.ADJUSTMENTS,
    AccountingDBTModel.PAYMENTS,
]);

interface Props {
    statementPeriod: AbacusStatementPeriod;
    paymentEntity: AbacusStatementPaymentEntity;
}

export const ShowInCustomerAccountingButton: FC<Props> = ({
    statementPeriod,
    paymentEntity,
}) => {
    const paymentEntityId =
        paymentEntity.referencePaymentEntity.referencePaymentEntityId;

    const isVisibleToCustomer = paymentEntity.isVisibleToCustomer;

    const setPaymentEntityToVisible = useUpdateStatementPeriodPaymentEntity();

    const triggerDbtRefresh = useMoneyhubDbtRefresh(
        true,
        MODELS_TO_REFRESH as AccountingDBTModel[]
    );

    const [isModalOpen, setIsModalOpen] = useState(false);

    const toggleModal = () => {
        setIsModalOpen(!isModalOpen);
    };

    const handleConfirm = async () => {
        const variables = {
            statementPeriodId: statementPeriod.statementPeriodId,
            paymentEntityId: paymentEntityId?.toString() || '',
        };

        try {
            await setPaymentEntityToVisible({ variables });
            await triggerDbtRefresh();
            toggleModal();
        } catch (e) {
            console.error(e);
        }
    };

    const modalContent = (
        <div
            className={`${CLASS_NAME}-modal`}
            data-testid={TEST_ID_SHOW_TO_ACCOUNTING_MODAL}
        >
            <p>{TERM_SHOW_IN_ACCOUNTING_MODAL_SUBTITLE}</p>
            <p>{TERM_SHOW_IN_ACCOUNTING_MODAL_TEXT}</p>
            <p className="bold">{TERM_SHOW_IN_ACCOUNTING_MODAL_TEXT_WARNING}</p>
        </div>
    );

    const renderButton = () => {
        return isVisibleToCustomer ? (
            <div className="text">{TERM_LIVE_IN_ACCOUNTING}</div>
        ) : (
            <div className="ShowInCustomerAccounting">
                <Button
                    variant="secondary"
                    disabled={
                        statementPeriod.statementPeriodStatus ===
                        STATEMENT_PERIOD_STATUSES.CLOSED
                    }
                    onClick={toggleModal}
                >
                    {TERM_SHOW_IN_ACCOUNTING}
                </Button>
            </div>
        );
    };

    return (
        <div>
            {renderButton()}
            {isModalOpen && (
                <PopupModal
                    className={`${CLASS_NAME}-popup`}
                    closeHandler={toggleModal}
                    closeButtonText={TERM_SHOW_IN_ACCOUNTING_MODAL_CANCEL}
                    saveHandler={handleConfirm}
                    saveButtonText={TERM_SHOW_IN_ACCOUNTING_MODAL_CONFIRM}
                    modalContent={modalContent}
                    isOpen={isModalOpen}
                    headerLabel={TERM_SHOW_IN_ACCOUNTING_MODAL_TITLE}
                />
            )}
        </div>
    );
};
