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

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

import CollectionFields from '@/components/CollectionFields/CollectionFields';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
} 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';

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

export const profileDialogRef = createRef<ProfileDialogRefType>();

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


    const { profile, saveProfile } = useMainPage();

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

            valuesRef.current = profile?.data;


            setOpen(true);
        },
        close: () => setOpen(false),
    }));

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

    const onSave = () => {
        saveProfile(valuesRef.current).then(() => {
            setOpen(false);
        });
    }









    const { isMobile } = useAppConfigStore();

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

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




                {profile?.structure && <CollectionFields
                    structure={profile?.structure}
                    valuesRef={valuesRef}
                />}

                <MobileFab
                    className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"
                    icon={<Save />}
                    text={Lang.key("save")}
                    onClick={onSave}
                    textPosition="after"
                />





            </MobilePage>
        </MobilePopup>
    }

    return (<>
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="!w-[80vw] !max-w-[80vw] sm:!max-w-[80vw] h-[80vh]  " >


                {profile?.structure && <CollectionFields
                    structure={profile?.structure}
                    valuesRef={valuesRef}
                />}



                <DialogFooter>
                    <Button onClick={onSave}>{Lang.key("save")}</Button>
                </DialogFooter>



            </DialogContent>
        </Dialog>


    </>


    )
});