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

import _ from 'lodash';
import {
    Check,
    FunnelPlus,
    FunnelX,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import { StructureType } from '@/api/types';
import AnyDropdownMenu, { MenuData } from '@/components/AnyDropdownMenu';
import CollectionFields from '@/components/CollectionFields/CollectionFields';
import { toast } from '@/components/ToastRoot';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
} from '@/components/ui/dialog';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    MobileFab,
    MobileLink,
    MobileNavbar,
    MobilePage,
    MobilePopup,
} from '@/components/ui/mobile';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import {
    flatFilterStructure,
    menuByFilterStructure,
} from '../utils';

export type TableFilterDialogRef = {
    open: () => void;
    close: () => void;
}

type TableFilterDialogProps = {
    structure?: StructureType | null;
    onApply: (filterStructureData: StructureType[], values: any) => void;
    initialFilter?: any;
}


const TableFilterDialog = forwardRef<TableFilterDialogRef, TableFilterDialogProps>(({ structure, onApply, initialFilter }, ref) => {
    const { isMobile } = useAppConfig();
    const [isOpen, setIsOpen] = useState(false);
    const [filterStructure, setFilterStructure] = useState<StructureType | null>(null);
    const [filterStructureData, setFilterStructureData] = useState<StructureType[]>([]);
    const valuesRef = useRef<any>({});
    const structureRef = useRef<StructureType | null>(structure ?? null);

    useImperativeHandle(ref, () => ({
        open: () => {
            structureRef.current = structure ?? null;
            setIsOpen(true);
        },
        close: () => {
            setIsOpen(false);
        }
    }));

    useEffect(() => {
        structureRef.current = structure ?? null;
    }, [structure]);

    const currentStructure = structureRef.current;


    const recoverFilterStructure = (structure: StructureType) => {

        if (initialFilter) {

            let flatFilters = flatFilterStructure({
                structure: structure,
            })
            let _filterStructureData: StructureType[] = [];
            _.map(flatFilters, (filter) => {
                if (initialFilter[filter.key ?? '']) {
                    _filterStructureData.push(filter);
                }
            })
            setFilterStructureData(_filterStructureData);
            valuesRef.current = initialFilter;
        }

    }

    useEffect(() => {
        if (currentStructure?.collection) {
            rpc.filter({ collection: currentStructure.collection! }).then((data) => {
                if (data?.result) {
                    setFilterStructure(data.result ?? null);

                    recoverFilterStructure(data.result ?? null);


                }
            });
        }
    }, [currentStructure?.collection]);


    const ClearFilterButton = () => {
        if (isMobile) {
            return <MobileFab
                className="fixed left-safe-4 bottom-safe-4 z-20 k-color-brand-green"
                onClick={() => {


                    setFilterStructureData([]);
                    valuesRef.current = {};

                    onApply([], {});
                    handleClose();
                }}
                icon={<FunnelX />}

            />
        }
        return <Button
            disabled={filterStructureData.length === 0}
            variant="outline" onClick={() => {
                setFilterStructureData([]);
                valuesRef.current = {};

                onApply([], {});
                handleClose();
            }}><FunnelX /> {Lang.key('clearFilter')}</Button>
    }

    const ApplyFilterButton = () => {

        if (isMobile) {
            return <MobileFab
                className="fixed right-safe-4 bottom-safe-4 z-20"
                icon={<Check />}
                textPosition="after"

                onClick={() => {
                    if (filterStructureData.length === 0) {
                        toast.error(Lang.key('please_add_filter'));
                        return;
                    }

                    onApply(filterStructureData, valuesRef.current);
                    handleClose();
                }}
            />
        }


        return <Button

            onClick={() => {


                onApply(filterStructureData, valuesRef.current);
                handleClose();
            }}

            disabled={filterStructureData.length === 0}
            variant="default" ><Check /> {Lang.key('apply')}</Button>
    }

    const AddFilterButton = () => {

        let menu: MenuData[] = menuByFilterStructure({
            onSelect: (val) => {

                setFilterStructureData((prev) => {
                    return [...prev, val];
                });

            }, structure: filterStructure, selectBefore: []
        });


        if (isMobile) {
            return <AnyDropdownMenu menu={menu}><MobileFab
                className="fixed left-1/2 bottom-safe-4 transform -translate-x-1/2 z-20"


                icon={<FunnelPlus />}
                text={Lang.key('add')}
                textPosition="after"
            />
            </AnyDropdownMenu>
        }


        return <AnyDropdownMenu menu={menu}>

            <Button

                variant={'outline'}
            ><FunnelPlus /> {Lang.key('add_filter')}</Button>
        </AnyDropdownMenu>
    }

    const removeFilter = (index: number, item: StructureType) => {

        if (item.key) {
            delete valuesRef.current[item.key];
        }

        setFilterStructureData((prev) => {
            return [...prev.slice(0, index), ...prev.slice(index + 1)];
        });
    }

    const FilterElements = () => {



        if (filterStructureData.length === 0) {
            return <Empty>
                <EmptyHeader>
                    <EmptyMedia variant="icon">
                        <FunnelX />
                    </EmptyMedia>
                    <EmptyTitle>{Lang.key('no_filters_title')}</EmptyTitle>
                    <EmptyDescription>
                        {Lang.key('no_filters_description')}
                    </EmptyDescription>
                </EmptyHeader>
            </Empty>
        }



        return <>



            {filterStructureData.map((filterStructureItem, index) => {
                return <div className='flex items-center'>
                    <div className='flex-1'>
                        <CollectionFields
                            inline
                            noPaddingBottom structure={filterStructureItem} valuesRef={valuesRef} />
                    </div>
                    {isMobile ? <MobileLink
                        className='px-2'
                        onClick={() => {
                            removeFilter(index, filterStructureItem);



                        }}>

                        <XIcon />

                    </MobileLink> : <Button variant="ghost"
                        className='mt-3'
                        size="icon-sm" onClick={() => {
                            removeFilter(index, filterStructureItem);
                        }}>
                        <XIcon />
                    </Button>}
                </div>
            })}




        </>
    }

    const handleClose = () => {
        setIsOpen(false);
    };

    if (!isOpen) return null;

    if (!currentStructure || !currentStructure.items) return null;

    if (isMobile) {
        return <MobilePopup opened={isOpen} onBackdropClick={handleClose}>
            <MobilePage>
                <MobileNavbar
                    title={Lang.key('filter')}
                    right={<MobileLink onClick={handleClose}><XIcon /></MobileLink>}
                />
                <div className='px-2'>
                    <FilterElements />
                </div>


                <AddFilterButton />

                <ClearFilterButton />

                <ApplyFilterButton />





            </MobilePage>
        </MobilePopup>
    }

    return (<>


        <Dialog open={isOpen} onOpenChange={(val) => {
            if (!val) {
                handleClose();
            }
        }}>
            <DialogContent className='sm:!max-w-[80vw]'>
                <div className='min-h-[20vh] overflow-y-auto'>
                    <FilterElements />
                </div>

                <DialogFooter>
                    <div className='flex justify-between w-full'>
                        <div className='flex items-center gap-2'>
                            <AddFilterButton />
                            <ClearFilterButton />
                        </div>

                        <div className='flex items-center gap-2'>
                            <ApplyFilterButton />

                            <Button variant="outline" onClick={handleClose}>{Lang.key('close')}</Button>
                        </div>
                    </div>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    </>
    );
});

TableFilterDialog.displayName = 'TableFilterDialog';

export default TableFilterDialog;