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

import _ from 'lodash';
import {
    ChevronDownIcon,
    Download,
    FilterIcon,
    MenuIcon,
    MoreHorizontal,
    MoveIcon,
    Plus,
    XIcon,
} from 'lucide-react';

import {
    CollectionRelationType,
    FilterPresetFKTType,
    StructureType,
} from '@/api/types';
import AnyDropdownMenu from '@/components/AnyDropdownMenu';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ButtonGroup } from '@/components/ui/button-group';
import { GridRow } from '@/components/ui/grid';
import { Input } from '@/components/ui/input';
import {
    MobileBadge,
    MobileLink,
    MobileList,
    MobileListItem,
    MobileNavbar,
    MobilePopover,
    MobileSearchbar,
} from '@/components/ui/mobile';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
import { openMobileMenu } from '@/pages/MainPage.tsx/components/AppSidebar';

import SelectedRowButton, {
    SelectedRowButtonFunctionsProps,
} from './SelectedRowButton';

type TableNavabarProps = SelectedRowButtonFunctionsProps & {
    structure: StructureType | null;
    filterPreset: FilterPresetFKTType | null;
    setFilterPreset: (filterPreset: FilterPresetFKTType | null) => void;
    search: string | null;
    setSearch: (search: string) => void;
    onCreate: () => void;
    selectedRows: string[];
    sortable: boolean;
    setSortable: (sortable: boolean) => void;
    onExport: () => void;
    onOpenFilter: () => void;
    relations: CollectionRelationType[];
    onOpenRelationTable: (item: CollectionRelationType) => void;
    onCloseTableDialog: () => void;
    filterCount: number;
    dialog?: boolean;

}

const TableNavabar = ({ structure, filterPreset, setFilterPreset, onCloseTableDialog, onOpenRelationTable, relations, filterCount, search, onOpenFilter, setSearch, onCreate, onExport, selectedRows, sortable, setSortable, onEditFields, onDoAction, onDeleteSelected, onExportSelected, dialog = false }: TableNavabarProps) => {

    const { isMobile } = useAppConfig();



    if (isMobile) {

        const menuElementRef = useRef<HTMLDivElement>(null);

        const stageElementRef = useRef<HTMLDivElement>(null);


        const [popoverOpened, setPopoverOpened] = useState(false);
        const [stagePopoverOpened, setStagePopoverOpened] = useState(false);
        return <>
            <MobileNavbar
                left={dialog ? undefined : <MobileLink

                    onClick={() => {
                        openMobileMenu();
                    }}
                ><MenuIcon /></MobileLink>}
                title={structure?.title}

                subtitle={filterPreset ? <div
                    ref={stageElementRef}

                    onClick={() => {
                        setStagePopoverOpened(true);
                        //  setStage(undefined);
                    }}
                    className='flex items-center gap-2'>{filterPreset?.title ?? ''} <ChevronDownIcon /></div> : undefined}

                subnavbar={<MobileSearchbar
                    onClear={() => {
                        setSearch("");
                    }}
                    placeholder={Lang.key("searchPlaceholder")} value={search ?? ""} onChange={(event) => {
                        setSearch(event.target.value);
                    }} />}

                right={<>{sortable ? <MobileLink

                    onClick={() => {

                        setSortable(!sortable);
                    }}>
                    <MoveIcon className='text-red-500 animate-pulse' />


                </MobileLink> :
                    <div ref={menuElementRef}>
                        <MobileLink
                            onClick={() => {
                                setPopoverOpened(true);
                            }}

                        >
                            <MoreHorizontal />

                            {filterCount > 0 && <MobileBadge>{filterCount}</MobileBadge>}
                        </MobileLink>

                    </div>

                }


                    {dialog && <MobileLink
                        onClick={() => {

                            onCloseTableDialog();
                        }}
                    >
                        <XIcon />
                    </MobileLink>}

                </>}
            />
            <SelectedRowButton
                onOpenRelationTable={onOpenRelationTable}
                relations={relations}
                onExportSelected={onExportSelected}
                onEditFields={onEditFields}
                onDoAction={onDoAction}
                onDeleteSelected={onDeleteSelected}
                selectedRows={selectedRows} structure={structure} />

            <MobilePopover opened={popoverOpened}

                target={menuElementRef.current}
                onBackdropClick={() => {
                    setPopoverOpened(false);
                }}
            >
                <MobileList nested>
                    <MobileListItem
                        title={Lang.key("create")}
                        media={<Plus />}
                        onClick={() => {
                            setPopoverOpened(false);
                            onCreate();
                        }}
                    />
                    <MobileListItem
                        title={Lang.key("export")}
                        media={<Download />}
                        onClick={() => {
                            setPopoverOpened(false);
                            onExport();
                        }}
                    />
                    <MobileListItem
                        title={Lang.key("filter")}
                        after={filterCount > 0 ? <MobileBadge>{filterCount}</MobileBadge> : undefined}
                        media={<FilterIcon />}
                        onClick={() => {
                            onOpenFilter();
                            setPopoverOpened(false);
                        }}
                    />


                    {structure?.manualSort && <MobileListItem
                        title={sortable ? Lang.key("disableManualSort") : Lang.key("manualSort")}
                        media={<MoveIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            setSortable(!sortable);
                        }}
                    />}
                </MobileList>
            </MobilePopover>

            <MobilePopover opened={stagePopoverOpened}
                target={stageElementRef.current}
                onBackdropClick={() => {
                    setStagePopoverOpened(false);
                }}
            >
                <MobileList nested>
                    {structure?.filterPresets?.map((item) => <MobileListItem key={item.key} title={item.title} onClick={() => {
                        setFilterPreset(item);
                        setStagePopoverOpened(false);
                    }} />)}
                </MobileList>
            </MobilePopover>





        </>
    }
    return <><GridRow autoSize className='flex flex-col p-4'>


        <div className="flex items-center  gap-2 justify-between">





            <div className='flex items-center'>



                <div className='text-lg font-medium mr-2'>{structure?.title}</div>
                {!!structure?.filterPresets && <AnyDropdownMenu menu={_.map(structure?.filterPresets, (item) => ({
                    label: item.title,
                    click: () => {
                        setFilterPreset(item);
                    }
                }))} >
                    <Button variant="outline"> {filterPreset?.title ?? ''} <ChevronDownIcon /></Button>
                </AnyDropdownMenu>}

            </div>

            <SelectedRowButton
                onOpenRelationTable={onOpenRelationTable}
                relations={relations}
                onExportSelected={onExportSelected}
                onEditFields={onEditFields}
                onDoAction={onDoAction}
                onDeleteSelected={onDeleteSelected}
                selectedRows={selectedRows} structure={structure} />

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


                <Input
                    placeholder={Lang.key("searchPlaceholder")}
                    value={search ?? ""}

                    onChange={(event) => {
                        setSearch(event.target.value);
                    }}

                    className='w-full'

                />

                <ButtonGroup>

                    <Button
                        onClick={() => {
                            onExport();
                        }}
                        variant="outline">
                        <Download />
                    </Button>
                    <Button
                        variant="outline"
                        onClick={() => {
                            onOpenFilter();
                        }}
                    >
                        <FilterIcon /> {filterCount > 0 && <Badge>{filterCount}</Badge>}
                    </Button>
                    {structure?.manualSort && <Button
                        variant={!sortable ? "outline" : "default"}
                        onClick={() => {
                            setSortable(!sortable);
                        }}
                    >
                        <MoveIcon />
                    </Button>}
                    {structure?.canCreate && <Button

                        variant="outline"
                        onClick={() => {
                            onCreate();
                        }}
                    >
                        <Plus />
                    </Button>}

                </ButtonGroup>
            </div>


        </div>

    </GridRow>

    </>
}

export default TableNavabar;