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 {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/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 TCompanyDialogRefType = {
    open: () => void;
    close: () => void;
}

export const tCompanyDialogRef = createRef<TCompanyDialogRefType>();

export const TCompanyDialog = forwardRef<TCompanyDialogRefType, {}>((_, 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?.tCompanyData ?? {};
                setCompanyStatus(profile?.tCompanyData?.status ?? null);


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

    const onSaveChanges = () => {

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

                type: valuesRef.current?.type,
                ipResident: valuesRef.current?.ipResident,
                ulResident: valuesRef.current?.ulResident,

            }).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.tCompanySend().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?.tCompanyStructure) {
        return null;
    }



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

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



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

                    key={companyStatus}

                    onlyShow={companyStatus != "draft"}
                    structure={profile?.tCompanyStructure}
                    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 (<>
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh] overflow-hidden" >

                <DialogHeader
                >
                    <DialogTitle>
                        {Lang.key('company_data')}
                    </DialogTitle>
                </DialogHeader>



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

                    key={companyStatus}

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




                {companyStatus == "draft" && <DialogFooter>
                    <Button

                        variant="outline"

                        onClick={() => {
                            onSaveChanges()
                        }}>
                        {Lang.key('save')}
                    </Button>
                    <Button


                        onClick={() => {
                            onSendToProcessing()
                        }}>
                        {Lang.key('send_to_processing')}
                    </Button>
                </DialogFooter>}
            </DialogContent>
        </Dialog>


    </>


    )
});