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

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

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

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;
    onViz?: () => void;
    vizMode: boolean;

}

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

    const { isMobile } = useAppConfigStore();



    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={<ShortViewText text={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}
                onClearSelected={onClearSelected}
                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();
                        }}
                    />
                    {!!onViz && <>{!vizMode ? <MobileListItem
                        title={Lang.key("viz_analytics")}
                        media={<ChartBarIcon />}
                        onClick={() => {
                            setPopoverOpened(false);
                            onViz();
                        }}
                    />
                        : <MobileListItem
                            title={Lang.key("table_view")}
                            media={<Table2Icon />}
                            onClick={() => {
                                setPopoverOpened(false);
                                onViz();
                            }}
                        />}</>}
                    <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
                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>
                    {onViz && <>{!vizMode ? <Button
                        tooltip={Lang.key("viz_analytics")}
                        variant="outline"
                        onClick={() => {
                            onViz();
                        }}
                    >
                        <ChartBarIcon />
                    </Button>
                        : <Button
                            tooltip={Lang.key("table_view")}
                            variant="outline"
                            onClick={() => {
                                onViz();
                            }}
                        >
                            <Table2Icon />
                        </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>}
                    {structure?.canCreate && <Button
                        tooltip={Lang.key("create")}
                        variant="outline"
                        onClick={() => {
                            onCreate();
                        }}
                    >
                        <Plus />
                    </Button>}

                </ButtonGroup>
            </div>


        </div>

    </GridRow>

    </>
}

export default TableNavabar;