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

import {
    Trash2,
    XIcon,
} from 'lucide-react';

import { rpc } from '@/api/request';
import { DisplayValueDLOTType } from '@/api/types';
import FabTablePagination
    from '@/components/CollectionTable/components/FabTablePagination';
import TablePagination
    from '@/components/CollectionTable/components/TablePagination';
import { Button } from '@/components/ui/button';
import { GridRow } from '@/components/ui/grid';
import { Input } from '@/components/ui/input';
import {
    Item,
    ItemContent,
    ItemTitle,
} from '@/components/ui/item';
import {
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobileSearchbar,
} from '@/components/ui/mobile';
import { Lang } from '@/lang/Lang';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

type IDsSelectBlockProps = {
    collection: string;
    onSelect?: (id: string | null) => void;
    onClose?: () => void;
}

const IDSelectOneBlock = ({ collection, onSelect, onClose }: IDsSelectBlockProps) => {

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

    const timeout = useRef<any>(null);


    const { isMobile } = useAppConfigStore();

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


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


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



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

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

    const getDate = () => {


        setLoading(true);




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


            search: !!search.trim() ? search.trim() : undefined,
        }).then((json) => {
            if (json?.result) {
                setData(json.result ?? null);
                setLoading(false);
            }
        }).finally(() => {
            setLoading(false);
        });

    };

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

    if (isMobile) {
        return <div className="flex flex-col h-full min-h-0 overflow-hidden">

            <MobileNavbar
                title={""}
                right={
                    <MobileLink iconOnly onClick={() => onClose?.()}>
                        <XIcon />
                    </MobileLink>
                }
                subnavbar={
                    <MobileSearchbar
                        value={search}
                        onClear={() => setSearch('')}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder={Lang.key('search_placeholder')}
                    />
                }
            />


            <MobileList outline dividers className="flex-1 min-h-0 overflow-auto">
                {data?.data?.map((item) => (
                    <MobileListItem
                        title={item.displayValue}
                        dividers
                        key={item._id} onClick={() => {
                            onSelect?.(item._id ?? null);
                        }}>
                    </MobileListItem>
                ))}
            </MobileList>


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


    return <>
        <GridRow className='flex flex-row gap-0' autoSize>

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

            <Button
                onClick={() => {
                    onSelect?.(null);
                }}
                size="icon"
                className='ml-1'
                variant="secondary">
                <Trash2 />
            </Button>

        </GridRow>
        <GridRow className='flex flex-col pt-2'>

            {data?.data?.map((item) => (
                <Item
                    onClick={() => {

                        onSelect?.(item._id ?? null);

                    }}
                    variant="outline">

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

                    </ItemContent>

                </Item>


            ))}
        </GridRow>
        <GridRow autoSize className='flex flex-row'>
            <TablePagination
                mini={true}
                onChangeLimit={(limit) => {
                    //    setLimit(limit);
                }}
                total={data?.total ?? 0}
                limit={data?.limit ?? 0}
                offset={data?.offset ?? 0}
                onChangeOffset={(offset) => {
                    setOffset(offset);
                }}
            />
        </GridRow>
    </>



}

export default IDSelectOneBlock;