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

import {
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';

import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
    Grid,
    GridCol,
} from '@/components/ui/grid';
import IDSelectOneBlock from './components/IDSelectOneBlock';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

export const idSearchCommandRef = React.createRef<IDSearchCommandRefProps>();


type OpenParamsType = {
    collection: string;
    onSelect: (item: any) => void;
}

type IDSearchCommandRefProps = {
    open: (params: OpenParamsType) => void;
    close: () => void;
}

export const IDSearchCommand = forwardRef<IDSearchCommandRefProps, {}>((_, ref) => {


    const [open, setOpen] = useState(false);

    const [search, setSearch] = useState<string>('');

    const timeout = useRef<any>(null);

    const [collection, setCollection] = useState<string>('');




    const onSelectRef = useRef<((item: any) => void) | null>(null);
    useImperativeHandle(ref, () => ({
        open: (params: OpenParamsType) => {

            setCollection(params.collection);
            onSelectRef.current = params.onSelect;
            setOpen(true);
        },
        close: () => {
            setOpen(false);
        }
    }));


    const { isMobile } = useAppConfigStore();

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

                <IDSelectOneBlock
                    onClose={() => setOpen(false)}
                    collection={collection} onSelect={(id) => {
                        onSelectRef.current?.(id);
                        setOpen(false);
                    }} />
            </MobilePage>
        </MobilePopup>
    }


    return (
        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            width={500}
            height="80vh"
        >
            <Grid className='h-full w-full'>
                <GridCol>
                    <IDSelectOneBlock collection={collection} onSelect={(id) => {
                        onSelectRef.current?.(id);
                        setOpen(false);
                    }} />
                </GridCol>
            </Grid>
        </SystemWindowDialog>
    )





});
