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

import {
  CollectionRelationType,
  StructureType,
} from '@/api/types';
import AnyDropdownMenu, { MenuData } from '@/components/AnyDropdownMenu';
import SvgIcon from '@/components/SvgIcon';
import { Button } from '@/components/ui/button';
import { ButtonGroup } from '@/components/ui/button-group';
import { MobileFab } from '@/components/ui/mobile';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';
import { canAccess } from '@/utils/accessUtils';

export type SelectedRowButtonFunctionsProps = {
    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;
}

export const getFastMenu = ({ structure, relations, 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;


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


    let actions: StructureType[] = [];
    _.map(structure?.items, (item) => {
        if (item.type == "action" && item.actionPosition != "table") {
            actions.push(item);
        }
    });

    if (actions.length > 0) {
        menu.push({
            label: Lang.key("do_action"),
            htmlIcon: <MoreHorizontalIcon />,
            submenu: actions?.map((item) => {
                return {
                    htmlIcon: <SvgIcon icon={item.assets?.icon} />,
                    label: item.title ?? item.key,
                    click: () => {
                        onDoAction(item);
                    }
                }
            })
        });
    }

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

                        onOpenRelationTable(item);


                    }
                }
            })
        });
    }

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

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




    return menu;

}



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

    const { isMobile } = useAppConfig();

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



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


        return getFastMenu({ structure, relations, 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" aria-label="More Options">
                <MoreHorizontalIcon />
            </Button>

        </AnyDropdownMenu>

    </ButtonGroup>

}

export default SelectedRowButton;