import React, {
    createRef,
    forwardRef,
    useImperativeHandle,
    useRef,
    useState,
} from 'react';

import {
    Save,
    Send,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import { StatusADPREnum } from '@/api/types';
import CollectionFields from '@/components/CollectionFields/CollectionFields';
import SkeletonList from '@/components/SkeletonList';
import { Button } from '@/components/ui/button';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { useMainPage } from '@/stores/mainPage';

import { confirmAlertRef } from './ConfirmAlert';
import { toast } from './ToastRoot';

type TCompanyBankDialogRefType = {
    open: () => void;
    close: () => void;
}

export const tCompanyBankDialogRef = createRef<TCompanyBankDialogRefType>();

export const TCompanyBankDialog = forwardRef<TCompanyBankDialogRefType, {}>((_, ref) => {
    const [open, setOpen] = useState(false);


    const [companyStatus, setCompanyStatus] = useState<StatusADPREnum | null>(null);

    const { isMobile } = useAppConfigStore();
    const { profile, loadProfile } = useMainPage();

    const valuesRef = useRef<any>({});

    const [loading, setLoading] = useState(false);

    useImperativeHandle(ref, () => ({
        open: () => {

            setLoading(true);
            setOpen(true);


            loadProfile().then(() => {

                valuesRef.current = profile?.tCompanyBankData ?? {};
                setCompanyStatus(profile?.tCompanyBankData?.status ?? null);


            }).finally(() => {
                setLoading(false);
            });
        },
        close: () => setOpen(false),
    }));

    const onSaveChanges = () => {

        return new Promise((resolve, reject) => {
            rpc.tCompanyBankUpdate({

                bik: valuesRef.current?.bik,
                kpp: valuesRef.current?.kpp,
                inn: valuesRef.current?.inn,
                name: valuesRef.current?.name,
                bankName: valuesRef.current?.bankName,
                accountNumber: valuesRef.current?.accountNumber,
                corrAccountNumber: valuesRef.current?.corrAccountNumber,

            }).then(() => {
                toast.success(Lang.key('changes_saved_successfully'));
            }).finally(() => {
                resolve(true);
            });
        });

    }


    const onSendToProcessing = () => {

        confirmAlertRef.current?.open({
            title: Lang.key('send_to_processing_confirm'),
            description: Lang.key('send_to_processing_confirm_description'),
            buttons: [
                {
                    label: Lang.key('send'), onClick: () => {

                        setLoading(true);
                        onSaveChanges().then(() => {
                            rpc.tCompanyBankSend().then((data) => {
                                toast.success(Lang.key('changes_saved_successfully'));
                                valuesRef.current = data?.result ?? {};
                                setCompanyStatus(data?.result?.status ?? null);
                            }).finally(() => {
                                setLoading(false);
                            });
                        })



                    }
                },
                { label: Lang.key('cancel'), onClick: () => { } },
            ]
        });

    }

    if (!profile?.tCompanyBankStructure) {
        return null;
    }





    if (isMobile) {
        return <MobilePopup
            opened={open}
            onBackdropClick={() => setOpen(false)}
        >
            <MobilePage className="flex flex-col">
                <MobileNavbar

                    title={Lang.key('company_bank_data')}
                    right={<MobileLink onClick={() => setOpen(false)}><XIcon /></MobileLink>}
                />



                {loading ? <SkeletonList count={20} /> : <> {open && <CollectionFields

                    key={companyStatus}

                    onlyShow={companyStatus != "draft"}
                    structure={profile?.tCompanyBankStructure}
                    valuesRef={valuesRef}
                />}</>}


                {companyStatus == "draft" && <MobileFab
                    disabled={companyStatus != "draft"}
                    className="fixed left-safe-4 bottom-safe-4 z-20 "
                    onClick={() => {


                        onSaveChanges()
                    }}
                    icon={<Save />}

                />}

                {companyStatus == "draft" && <MobileFab
                    disabled={companyStatus != "draft"}
                    className="fixed right-safe-4 bottom-safe-4 z-20"
                    icon={<Send />}
                    textPosition="after"

                    onClick={() => {
                        onSendToProcessing()
                    }}
                />}


            </MobilePage>
        </MobilePopup>
    }



    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={Lang.key('company_bank_data')}
            width="80vw"
            height="80vh"
            allowFullscreen
            footer={companyStatus == "draft" ? (
                <>
                    <Button variant="outline" onClick={onSaveChanges}>
                        {Lang.key('save')}
                    </Button>
                    <Button onClick={onSendToProcessing}>
                        {Lang.key('send_to_processing')}
                    </Button>
                </>
            ) : undefined}
        >
            {loading ? (
                <SkeletonList count={20} />
            ) : (
                open && (
                    <CollectionFields
                        key={companyStatus}
                        onlyShow={companyStatus != "draft"}
                        structure={profile?.tCompanyBankStructure}
                        valuesRef={valuesRef}
                    />
                )
            )}
        </SystemWindowDialog>


    )
});