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

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

import {
    CollectionAccessType,
    CollectionRelationType,
    FilterPresetFKTType,
    StructureType,
} from '@/api/types';
import AnyDropdownMenu from '@/components/AnyDropdownMenu';
import ShortViewLL from '@/components/ShortViewLL';
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 { Lang } from '@/lang/Lang';
import { LL } from '@/lang/LL';
import { openMobileMenu } from '@/pages/MainPage.tsx/components/AppSidebar';
import useAppConfigStore from '@/stores/appConfig';

import { CollectionTableMode } from '../CollectionTable';
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[];
    onClearSelected: () => void;
    sortable: boolean;
    setSortable: (sortable: boolean) => void;
    onExport: () => void;
    onOpenFilter: () => void;
    relations: CollectionRelationType[];

    onOpenRelationTable: (item: CollectionRelationType) => void;
    onCloseTableDialog: () => void;
    filterCount: number;
    dialog?: boolean;
    setMode: (mode: CollectionTableMode) => void;
    mode: CollectionTableMode;
    showVizMode: boolean;
    showBoardMode: boolean;
    collectionAccess: CollectionAccessType | null;
}

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

    const { isMobile } = useAppConfigStore();

    const haveAnyAdditionalModes = !!showVizMode || !!showBoardMode;

    const filterPresets = useMemo(() => {
        let _filterPresets = structure?.filterPresets;



        return _filterPresets;

    }, [structure]);

    console.log("filterPresets", filterPresets);

    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={<ShortViewLL value={structure?.title ?? ''} />}

                subtitle={mode !== "board" && 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}
                onClearSelected={onClearSelected}
                onDoAction={onDoAction}
                onDeleteSelected={onDeleteSelected}
                selectedRows={selectedRows} structure={structure} />

            <MobilePopover opened={popoverOpened}

                target={menuElementRef.current}
                onBackdropClick={() => {
                    setPopoverOpened(false);
                }}
            >
                <MobileList nested>
                    {collectionAccess?.canCreate && <MobileListItem
                        title={Lang.key("create")}
                        media={<Plus />}
                        onClick={() => {
                            setPopoverOpened(false);
                            onCreate();
                        }}
                    />}


                    {!!showVizMode && <MobileListItem
                        title={Lang.key("viz_analytics")}
                        media={<FileChartPieIcon />}

                        after={mode === "viz" ? <MobileBadge>{Lang.key("active")}</MobileBadge> : undefined}


                        onClick={() => {
                            setPopoverOpened(false);
                            setMode("viz");
                        }}
                    />}


                    {!!haveAnyAdditionalModes && <MobileListItem
                        title={Lang.key("table_view")}
                        media={<Table2Icon />}
                        after={mode === "table" ? <MobileBadge>{Lang.key("active")}</MobileBadge> : undefined}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMode("table");
                        }}
                    />}

                    {!!showBoardMode && <MobileListItem
                        title={Lang.key("board_view")}
                        media={<LayoutDashboard />}
                        after={mode === "board" ? <MobileBadge>{Lang.key("active")}</MobileBadge> : undefined}
                        onClick={() => {
                            setPopoverOpened(false);
                            setMode("board");
                        }}
                    />}
                    <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>
                    {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'><LL value={structure?.title} /></div>
                {mode !== "board" && !!filterPresets && <AnyDropdownMenu menu={_.map(filterPresets, (item) => ({
                    label: item.title,
                    click: () => {
                        setFilterPreset(item);
                    }
                }))} >
                    <Button variant="outline"> {filterPresets?.find((item) => item.key === filterPreset?.key)?.title ?? filterPreset?.title ?? ''} <ChevronDownIcon /></Button>
                </AnyDropdownMenu>}

            </div>

            <SelectedRowButton
                onClearSelected={onClearSelected}
                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
                        tooltip={Lang.key("export")}
                        onClick={() => {
                            onExport();
                        }}
                        variant="outline">
                        <Download />
                    </Button>

                    {showVizMode && <Button
                        tooltip={Lang.key("viz_analytics")}
                        variant={mode === "viz" ? "default" : "outline"}
                        onClick={() => {
                            setMode("viz");
                        }}
                    >
                        <FileChartPieIcon />
                    </Button>}

                    {!!haveAnyAdditionalModes && <Button
                        tooltip={Lang.key("table_view")}
                        variant={mode === "table" ? "default" : "outline"}
                        onClick={() => {
                            setMode("table");
                        }}
                    >
                        <Table2Icon />
                    </Button>}

                    {showBoardMode && <Button
                        tooltip={Lang.key("board_view")}
                        variant={mode === "board" ? "default" : "outline"}
                        onClick={() => {
                            setMode("board");
                        }}
                    >
                        <LayoutDashboard />
                    </Button>}

                    <Button
                        tooltip={Lang.key("filter")}
                        variant="outline"
                        onClick={() => {
                            onOpenFilter();
                        }}
                    >
                        <FilterIcon /> {filterCount > 0 && <Badge>{filterCount}</Badge>}
                    </Button>
                    {structure?.manualSort && <Button
                        tooltip={Lang.key("manualSort")}
                        variant={!sortable ? "outline" : "default"}
                        onClick={() => {
                            setSortable(!sortable);
                        }}
                    >
                        <MoveIcon />
                    </Button>}
                    {collectionAccess?.canCreate && <Button
                        tooltip={Lang.key("create")}
                        variant="outline"
                        onClick={() => {
                            onCreate();
                        }}
                    >
                        <Plus />
                    </Button>}

                </ButtonGroup>
            </div>


        </div>

    </GridRow>

    </>
}

export default TableNavabar;