import {
    useEffect,
    useRef,
    useState,
} from 'react';

import {
    ArrowLeftIcon,
    ArrowRightIcon,
    PlusIcon,
    Trash2,
} from 'lucide-react';

import { rpc } from '@/api/request';
import { DisplayValueDLOTType } from '@/api/types';
import TablePagination
    from '@/components/CollectionTable/components/TablePagination';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import {
    Item,
    ItemContent,
    ItemMedia,
    ItemTitle,
} from '@/components/ui/item';
import {
    MobileFab,
    MobileList,
    MobileListItem,
    MobileSearchbar,
    MobileToolbar,
} from '@/components/ui/mobile';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Lang } from '@/lang/Lang';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

type IDsSelectBlockProps = {
    collection: string;
    onLeftClick?: (ids: string[]) => void;
    onRightClick?: (ids: string[]) => void;
    ignoreIds?: string[];
    includeIds?: string[];
    onClear?: () => void;
}

const IDsSelectBlock = ({ collection, ignoreIds, includeIds, onLeftClick, onRightClick, onClear }: IDsSelectBlockProps) => {

    const { isMobile } = useAppConfigStore();

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

    const timeout = useRef<any>(null);



    const [data, setData] = useState<DisplayValueDLOTType | null>(null);


    const handleSearch = () => {
        clearTimeout(timeout.current);


        timeout.current = setTimeout(() => {
            getDate();
        }, 1000);
    };
    const [loading, setLoading] = useState<boolean>(false);


    const [selectedIds, setSelectedIds] = useState<string[]>([]);

    const [offset, setOffset] = useState<number>(0);

    useEffect(() => {
        getDate();
    }, [collection, ignoreIds, includeIds, offset]);

    const getDate = () => {


        setLoading(true);

        setSelectedIds([]);


        rpc.displayValues({
            collection: collection,
            offset: offset,

            filter: {
                _id: {
                    nin: ignoreIds ?? [],
                    in: includeIds ?? [],
                }
            },
            search: !!search.trim() ? search.trim() : undefined,
        }).then((json) => {
            if (json?.result) {
                setData(json.result ?? null);
                setLoading(false);
            }
        }).finally(() => {
            setLoading(false);
        });

    };

    useEffect(() => {
        handleSearch();
    }, [search]);

    const onSelect = (id: string) => {
        setSelectedIds((prev) => {
            if (prev.includes(id)) {
                return prev.filter((id) => id !== id);
            } else {
                return [...prev, id];
            }
        });
    }

    if (isMobile) {
        return <>



            <div className='flex  mx-4  sticky top-0 z-10'>


                <MobileSearchbar

                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={Lang.key('search_placeholder')}
                />

            </div>


            <MobileList

                outline
                style={{
                    marginBottom: window.innerHeight * 0.5,
                    opacity: loading ? 0.5 : 1,
                    pointerEvents: loading ? 'none' : 'auto',
                }}>
                {data?.data?.map((item) => (
                    <MobileListItem
                        dividers
                        onClick={() => {
                            onSelect(item._id!);
                        }}
                        media={<Checkbox
                            onCheckedChange={(checked) => {
                                alert(1);
                                //  onSelect(item._id!);
                            }}
                            checked={!!item._id && selectedIds.includes(item._id)}

                        />}

                        title={item.displayValue}

                    >
                    </MobileListItem>


                ))}

            </MobileList>


            {!!onLeftClick && <MobileFab

                style={{
                    opacity: !selectedIds.length ? 0.5 : 1,
                }}

                className="fixed left-1/2 bottom-safe-20 transform -translate-x-1/2 z-20"
                text={<div className=' text-center '>{Lang.key('remove_selected')}</div>}
                textPosition="after"

                icon={<Trash2 />}

                onClick={() => {
                    if (!selectedIds.length) return;
                    onLeftClick(selectedIds);
                }}
            >

            </MobileFab>}
            {!!onRightClick && <MobileFab
                style={{
                    opacity: !selectedIds.length ? 0.5 : 1,
                }}
                onClick={() => {
                    if (!selectedIds.length) return;
                    onRightClick(selectedIds);
                }}

                className="fixed left-1/2 bottom-safe-20 transform -translate-x-1/2 z-20 "
                text={<div className=' text-center '>{Lang.key('add_selected')}</div>}
                textPosition="after"
                icon={<PlusIcon />}
            >
            </MobileFab>}

            <MobileToolbar className={`left-0 fixed bottom-0 w-full mt-auto`}>
                <TablePagination
                    onChangeLimit={(limit) => {
                        //    setLimit(limit);
                    }}
                    mini={true}
                    total={data?.total ?? 0}
                    limit={data?.limit ?? 0}
                    offset={data?.offset ?? 0}
                    onChangeOffset={(offset) => {
                        setOffset(offset);
                    }}
                />
            </MobileToolbar>

        </>
    }

    return <div>

        <div className='flex flex-row gap-0'>
            {!!onLeftClick ? <Button
                size="icon"
                disabled={!selectedIds.length}
                className='mr-1'
                onClick={() => {
                    onLeftClick(selectedIds);
                }}
                variant="secondary">
                <ArrowLeftIcon />
            </Button> : <div
                className=' flex items-center justify-center mx-2'

                onClick={() => {

                    if (data?.data?.length === selectedIds.length) {
                        setSelectedIds([]);
                    } else {
                        setSelectedIds(data?.data?.map((item) => item._id!) ?? []);
                    }


                }}
            >
                <Checkbox checked={data?.data?.length === selectedIds.length} />
            </div>}
            <div className='flex-1'>
                <Input
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    placeholder={Lang.key('search_placeholder')}
                />
            </div>

            {!!onRightClick ? <Button
                disabled={!selectedIds.length}
                onClick={() => {
                    onRightClick(selectedIds);
                }}
                size="icon"
                className='ml-1'
                variant="secondary">
                <ArrowRightIcon />
            </Button>
                : <Button
                    onClick={() => {
                        setSelectedIds([]);
                        onClear?.();
                    }}
                    size="icon"
                    className='ml-1'
                    variant="secondary">
                    <Trash2 />
                </Button>}
        </div>

        <ScrollArea
            className='pt-1'
            style={{
                height: window.innerHeight * 0.5,
                opacity: loading ? 0.5 : 1,
                pointerEvents: loading ? 'none' : 'auto',
            }}>
            {data?.data?.map((item) => (
                <Item
                    onClick={() => {

                        setSelectedIds((prev) => {

                            if (!item._id) {
                                return prev;

                            }
                            if (selectedIds.includes(item._id)) {
                                return prev.filter((id) => id !== item._id);
                            } else {
                                return [...prev, item._id];
                            }


                        });
                    }}
                    variant="outline">
                    <ItemMedia>
                        <Checkbox
                            checked={!!item._id && selectedIds.includes(item._id)}

                        />
                    </ItemMedia>
                    <ItemContent>
                        <ItemTitle>{item.displayValue}</ItemTitle>

                    </ItemContent>

                </Item>


            ))}

        </ScrollArea>
        <TablePagination
            mini={true}
            onChangeLimit={(limit) => {
                //    setLimit(limit);
            }}
            total={data?.total ?? 0}
            limit={data?.limit ?? 0}
            offset={data?.offset ?? 0}
            onChangeOffset={(offset) => {
                setOffset(offset);
            }}
        />
    </div>


}

export default IDsSelectBlock;