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

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

import { StructureType } from '@/api/types';
import CollectionFields from '@/components/CollectionFields/CollectionFields';
import { requiredValidation } from '@/components/CollectionView/utils';
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 { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

type OpenParams = {
    structure: StructureType;
    initialValues?: any;
    onSave: (values: any) => void;
}

type CollectionFieldsDialogRef = {
    open: (options: OpenParams) => void;
    close: () => void;
}

export const collectionFieldsDialogRef = React.createRef<CollectionFieldsDialogRef>();

const CollectionFieldsDialog = forwardRef<CollectionFieldsDialogRef, {}>((_, ref) => {
    const { isMobile } = useAppConfigStore();
    const [isOpen, setIsOpen] = useState(false);
    const [structure, setStructure] = useState<StructureType | null>(null);
    const valuesRef = useRef<any>({});
    const paramsRef = useRef<OpenParams | null>(null);

    useImperativeHandle(ref, () => ({
        open: (options: OpenParams) => {
            paramsRef.current = options;
            setStructure(options.structure);
            valuesRef.current = options.initialValues ? { ...options.initialValues } : {};
            setIsOpen(true);
        },
        close: () => {
            setIsOpen(false);
        }
    }));

    const handleSave = () => {
        if (paramsRef.current && structure) {

            let valid = requiredValidation(valuesRef.current, structure, valuesRef.current, []);
            if (valid.length > 0) {
                toast.error(`${valid[0]} ${Lang.key('is_required')}`);
                return;
            }

            paramsRef.current.onSave(valuesRef.current);
            setIsOpen(false);
        }
    };

    const handleClose = () => {
        setIsOpen(false);
    };

    if (!isOpen) return null;


    if (isMobile) {
        return <MobilePopup opened={isOpen} onBackdropClick={handleClose}>
            <MobilePage>
                <MobileNavbar
                    title={Lang.key('edit_fields')}
                    subtitle={structure?.title ?? ''}
                    right={
                        <MobileLink onClick={handleClose}>
                            <XIcon />
                        </MobileLink>
                    }
                />
                <CollectionFields noPaddingBottom structure={structure} valuesRef={valuesRef} />
                <MobileFab
                    className='fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20'
                    icon={<Save />}
                    onClick={handleSave}
                    text={Lang.key("save")}
                />
            </MobilePage>
        </MobilePopup>
    }


    return (
        <SystemWindowDialog
            open={isOpen}
            onOpenChange={setIsOpen}
            title={Lang.key('edit_fields')}
            width="80vw"
            height="80vh"
            allowFullscreen
            footer={<Button onClick={handleSave}>{Lang.key("save")}</Button>}
        >
            <CollectionFields noPaddingBottom structure={structure} valuesRef={valuesRef} />
        </SystemWindowDialog>
    );
});

CollectionFieldsDialog.displayName = 'CollectionFieldsDialog';

export default CollectionFieldsDialog;