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

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

import { StructureType } from '@/api/types';
import { toast } from '@/components/ToastRoot';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import CollectionFields from './CollectionFields/CollectionFields';
import { requiredValidation } from './CollectionView/utils';
import { Button } from './ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
} from './ui/dialog';
import {
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from './ui/mobile';

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 } = useAppConfig();
    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 (
        <Dialog open={isOpen} onOpenChange={setIsOpen}>
            <DialogContent showCloseButton={!isMobile}>

                <CollectionFields noPaddingBottom structure={structure} valuesRef={valuesRef} />
                <DialogFooter>
                    <Button onClick={handleSave}>{Lang.key("save")}</Button>
                </DialogFooter>
            </DialogContent>

        </Dialog>
    );
});

CollectionFieldsDialog.displayName = 'CollectionFieldsDialog';

export default CollectionFieldsDialog;