import _ from 'lodash';
import {
    CircleX,
    DownloadCloud,
    Edit3,
    MoreHorizontalIcon,
    Trash2,
} from 'lucide-react';

import {
    CollectionRelationType,
    StructureType,
} from '@/api/types';
import AnyDropdownMenu, { MenuData } from '@/components/AnyDropdownMenu';
import { ServerIcon } from '@/components/ServerIcon';
import { Button } from '@/components/ui/button';
import { ButtonGroup } from '@/components/ui/button-group';
import { MobileFab } from '@/components/ui/mobile';
import {
    Lang,
    LLRender,
} from '@/lang/Lang';
import useAppConfigStore from '@/stores/appConfig';
import { canAccess } from '@/utils/accessUtils';

export type SelectedRowButtonFunctionsProps = {
    onClearSelected: () => void;
    onEditFields: (item: StructureType) => void;
    onDoAction: (item: StructureType) => void;
    onDeleteSelected: (row_id?: string) => void;
    onExportSelected: () => void;
    onOpenRelationTable: (item: CollectionRelationType) => void;
}

type SelectedRowButtonProps = SelectedRowButtonFunctionsProps & {
    selectedRows: string[];
    structure: StructureType | null;
    relations: CollectionRelationType[];

}


type FastMenuProps = {
    structure: StructureType | null;
    relations: CollectionRelationType[];
    onEditFields: (item: StructureType) => void;
    onDoAction: (item: StructureType) => void;
    onDeleteSelected: () => void;
    onExportSelected: () => void;
    forOneRow?: boolean;
    onOpenRelationTable: (item: CollectionRelationType) => void;
    onClearSelected: () => void;
}

export const getFastMenu = ({ structure, relations, onClearSelected, onOpenRelationTable, onEditFields, onDoAction, onDeleteSelected, onExportSelected, forOneRow }: FastMenuProps): MenuData[] => {

    const canDeleteSelected = canAccess(structure).canDelete();
    const canUpdateSelected = canAccess(structure).canUpdate();

    const menu: MenuData[] = [];


    if (canUpdateSelected) {
        menu.push({
            label: forOneRow ? Lang.key("edit_field") : Lang.key("edit_fields"),
            htmlIcon: <Edit3 className='size-5' />,
            submenu: _.map(structure?.items, (item) => {

                if (!item.inAdmin) return null;
                if (item.hide) return null;
                if (!item.editable) return null;

                //  if (item.cond || item.localCond) return null;

                if (item.type == "array" || item.type == "structure") return null;

                return {
                    label: LLRender(item.title ?? item.key ?? ''),
                    click: () => {
                        onEditFields(item);
                    }
                }
            }).filter((item) => item !== null)
        });
    }


    if (relations.length > 0) {
        menu.push({
            label: Lang.key("relations_collection"),
            htmlIcon: <MoreHorizontalIcon />,
            submenu: relations.map((item) => {
                return {
                    htmlIcon: <ServerIcon icon={item.icon} />,
                    label: LLRender(item.title ?? item.key ?? ''),
                    subtitle: item.subtitle,
                    click: () => {

                        onOpenRelationTable(item);


                    }
                }
            })
        });
    }

    if (!forOneRow) {
        menu.push({
            label: Lang.key("export_selected"),
            htmlIcon: <DownloadCloud />,
            click: () => {
                onExportSelected()
            }
        });
        menu.push({
            label: Lang.key("clear_selected"),
            htmlIcon: <CircleX />,
            click: () => {
                onClearSelected()
            }
        });
    }

    if (canDeleteSelected) {
        menu.push({
            label: forOneRow ? Lang.key("delete") : Lang.key("delete_selected"),
            htmlIcon: <Trash2 />,
            click: () => {
                onDeleteSelected();
            }
        });
    }




    return menu;

}



const SelectedRowButton = ({ selectedRows, structure, relations, onClearSelected, onOpenRelationTable, onEditFields, onDoAction, onDeleteSelected, onExportSelected }: SelectedRowButtonProps) => {

    const { isMobile } = useAppConfigStore();

    if (selectedRows.length === 0) {
        return null;
    }



    const getMenu = (): MenuData[] => {



        return getFastMenu({ structure, relations, onClearSelected, onEditFields, onDoAction, onDeleteSelected, onExportSelected, onOpenRelationTable });



    }

    if (isMobile) {
        return <AnyDropdownMenu
            className="fixed right-3 bottom-1/2 bottom-safe-14 transform -translate-y-1/2 z-20"
            menu={getMenu()}
        >
            <MobileFab

                icon={<Edit3 className='size-5' />}
                text={<span className='text-base px-2'>{selectedRows.length}</span>}
                textPosition="after"
            />
        </AnyDropdownMenu>
    }


    return <ButtonGroup>
        <Button variant="outline">{Lang.key("selected")} {selectedRows.length}</Button>
        <AnyDropdownMenu
            menu={getMenu()}
        >
            <Button
                variant="outline"
                size="icon"
                tooltip={Lang.key('more_options')}
                aria-label={Lang.key('more_options')}
            >
                <MoreHorizontalIcon />
            </Button>

        </AnyDropdownMenu>

    </ButtonGroup>

}

export default SelectedRowButton;