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 { 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';

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 (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={Lang.key('profile')}
            width="80vw"
            height="80vh"
            allowFullscreen
            footer={<Button onClick={onSave}>{Lang.key("save")}</Button>}
        >
            {profile?.structure && (
                <CollectionFields
                    structure={profile?.structure}
                    valuesRef={valuesRef}
                />
            )}
        </SystemWindowDialog>
    )
});