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

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

import { rpc } from '@/api/request';
import { StructureType } from '@/api/types';
import { IS_DEV } from '@/config';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import { confirmAlertRef } from '../ConfirmAlert';
import { Button } from '../ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '../ui/dialog';
import {
    MobileBadge,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
    MobileSegmented,
    MobileSegmentedButton,
} from '../ui/mobile';
import IDsSelectBlock from './components/IDsSelectBlock';

export const idsSearchCommandRef = React.createRef<IDsSearchCommandRefProps>();


type OpenParamsType = {
    collection: string;
    values: string[];
    onSelect: (item: string[]) => void;
}
type IDsSearchCommandRefProps = {

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

export const IDsSearchCommand = forwardRef<IDsSearchCommandRefProps, {}>((_, ref) => {


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



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


    const [structure, setStructure] = useState<StructureType | null>(null);

    const onSelectRef = useRef<((item: any) => void) | null>(null);

    const [selectedValues, setSelectedValues] = useState<string[]>([]);

    const { isMobile } = useAppConfig();

    useImperativeHandle(ref, () => ({
        open: (params: OpenParamsType) => {


            if (IS_DEV) {
                console.log("DEV: Open IDsSearchCommand", params);
            }

            setCollection(params.collection);
            setSelectedValues(params.values);
            onSelectRef.current = params.onSelect;
            setOpen(true);



        },
        close: () => {
            setOpen(false);
        }
    }));

    const onSave = () => {
        setOpen(false);


        if (selectedValues.length === 0) {
            onSelectRef.current?.([]);
            return;
        } else {
            onSelectRef.current?.(selectedValues);

        }


    }


    useEffect(() => {
        if (collection) {
            rpc.collection({ collection: collection }).then((json) => {
                setStructure(json?.result?.structure ?? null);
            });
        }
    }, [collection]);

    if (isMobile) {

        const [activeTab, setActiveTab] = useState<'all' | 'selected'>('all');

        return <MobilePopup opened={open} onBackdropClick={() => setOpen(false)} >
            <MobilePage className="flex flex-col">
                <MobileNavbar
                    title={structure?.title}
                    right={<MobileLink onClick={() => {

                        confirmAlertRef.current?.open({
                            title: Lang.key('confirm_ids_selection'),
                            description: Lang.key('confirm_ids_selection_description'),
                            buttons: [
                                {
                                    label: Lang.key('cancel'), onClick: () => {


                                        setOpen(false);

                                    }
                                },
                                {
                                    label: Lang.key('save'), onClick: () => {


                                        onSave();
                                    }
                                },
                            ]
                        })




                    }}><XIcon /></MobileLink>}
                    subnavbar={<MobileSegmented >
                        <MobileSegmentedButton
                            active={activeTab === 'all'}
                            onClick={() => setActiveTab('all')}
                            value="all">
                            {Lang.key('all')}
                        </MobileSegmentedButton>
                        <MobileSegmentedButton

                            active={activeTab === 'selected'}
                            onClick={() => setActiveTab('selected')}
                            value="selected">
                            {Lang.key('selected')} <MobileBadge className='ml-2'>{selectedValues.length}</MobileBadge>
                        </MobileSegmentedButton>
                    </MobileSegmented>}
                />

                {activeTab === 'all' && !!structure && <IDsSelectBlock
                    ignoreIds={selectedValues}
                    onRightClick={(ids) => {

                        setSelectedValues((prev) => {
                            return uniq([...prev, ...ids]);
                        });


                    }}
                    collection={collection} />}
                {activeTab === 'selected' && !!structure && <IDsSelectBlock
                    onClear={() => {
                        setSelectedValues([]);
                    }}
                    includeIds={selectedValues.length ? selectedValues : ['none']}
                    onLeftClick={(ids) => {

                        setSelectedValues((prev) => {
                            return prev.filter((id) => !ids.includes(id));
                        });

                    }}
                    collection={collection} />}

            </MobilePage>
        </MobilePopup>

    }


    return (




        <Dialog


            open={open} onOpenChange={setOpen}>

            <DialogContent className="sm:max-w-[800px] " >

                <DialogHeader>
                    <DialogTitle>{structure?.title}</DialogTitle>
                </DialogHeader>


                <div className='grid grid-cols-2 gap-2'>
                    {!!structure && <IDsSelectBlock
                        ignoreIds={selectedValues}
                        onRightClick={(ids) => {

                            setSelectedValues((prev) => {
                                return uniq([...prev, ...ids]);
                            });


                        }}
                        collection={collection} />}
                    {!!structure && <IDsSelectBlock
                        onClear={() => {
                            setSelectedValues([]);
                        }}
                        includeIds={selectedValues.length ? selectedValues : ['none']}
                        onLeftClick={(ids) => {

                            setSelectedValues((prev) => {
                                return prev.filter((id) => !ids.includes(id));
                            });

                        }}
                        collection={collection} />}
                </div>

                <DialogFooter>
                    <div className='flex flex-row gap-2 justify-end'>
                        <Button variant="secondary" onClick={() => {
                            setOpen(false);
                        }}>
                            {Lang.key('cancel')}
                        </Button>
                        <Button variant="default" onClick={() => {
                            onSave();
                        }}>
                            <Save /> {Lang.key('save')}
                        </Button>
                    </div>
                </DialogFooter>
            </DialogContent>


        </Dialog>

    )
});
