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

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

import {
    Dialog,
    DialogContent,
} from '../ui/dialog';
import {
    Grid,
    GridCol,
} from '../ui/grid';
import IDSelectOneBlock from './components/IDSelectOneBlock';

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 } = useAppConfig();

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

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


    return <Dialog



        open={open} onOpenChange={setOpen}>



        <DialogContent className="sm:max-w-[500px] sm:h-[80vh]" >

            <Grid
                className=' h-full w-full'
            >
                <GridCol>



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



            </Grid>




        </DialogContent>
    </Dialog>





});
