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 { Lang } from '@/lang/Lang';
import { LL } from '@/lang/LL';

import { confirmAlertRef } from '@/componentsRoot/ConfirmAlert';
import { Button } from '@/components/ui/button';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
    MobileBadge,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
    MobileSegmented,
    MobileSegmentedButton,
} from '@/components/ui/mobile';
import IDsSelectBlock from './components/IDsSelectBlock';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

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

    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={<LL value={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 (




        <SystemWindowDialog
            open={open}
            onOpenChange={setOpen}
            title={<LL value={structure?.title} />}
            width={800}
            height="80vh"
            allowFullscreen
            bodyClassName="flex min-h-0 flex-col overflow-hidden"
            footer={
                <div className='flex flex-row gap-2 justify-end w-full'>
                    <Button variant="secondary" onClick={() => setOpen(false)}>
                        {Lang.key('cancel')}
                    </Button>
                    <Button variant="default" onClick={onSave}>
                        <Save /> {Lang.key('save')}
                    </Button>
                </div>
            }
        >
            <div className="flex min-h-0 flex-1 flex-col gap-2">
                <div className="grid min-h-0 flex-1 grid-cols-2 grid-rows-1 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>
                <p className="shrink-0 border-t pt-2 text-xs leading-relaxed text-muted-foreground">
                    {Lang.key('ids_search_desktop_help')}
                </p>
            </div>
        </SystemWindowDialog>

    )
});
