import { useState } from 'react';

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

import { rpc } from '@/api/request';
import {
  AdminActionMenuItemType,
  CollectionAccessType,
  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 } from '@/lang/Lang';
import { LL } from '@/lang/LL';
import useAppConfigStore from '@/stores/appConfig';

export type SelectedRowButtonFunctionsProps = {
    onClearSelected: () => void;
    onEditFields: (item: StructureType) => void;
    onDoAction: (item: AdminActionMenuItemType) => 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: AdminActionMenuItemType) => void;
    onDeleteSelected: () => void;
    onExportSelected: () => void;
    forOneRow?: boolean;
    onOpenRelationTable: (item: CollectionRelationType) => void;
    onClearSelected: () => void;
    collectionAccess: CollectionAccessType | null;
    actions: AdminActionMenuItemType[];
}

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

    const canDeleteSelected = collectionAccess?.canDelete ?? false;
    const canUpdateSelected = collectionAccess?.canUpdate ?? false;

    const menu: MenuData[] = [];

    if (collectionAccess?.buttons?.showActionButton && actions.length) {
        menu.push({
            label: Lang.key("actions"),
            htmlIcon: <Zap />,
            submenu: actions.map((item) => ({
                htmlIcon: <ServerIcon icon={item.icon} />,
                label: item.title ? <LL value={item.title} /> : item.key,
                click: () => {
                    onDoAction(item);
                }
            }))
        });
    }


    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: <LL value={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: <LL value={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();

    const [collectionAccess, setCollectionAccess] = useState<CollectionAccessType | null>(null);
    const [actions, setActions] = useState<AdminActionMenuItemType[]>([]);
    const [loading, setLoading] = useState(false);

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

    const onOpen = () => {
        if (!structure?.collection) return;
        setCollectionAccess(null);
        setActions([]);
        setLoading(true);

        const collection = structure.collection;

        Promise.all([
            rpc.collectionAccess({ collection, ids: selectedRows }),
            rpc.allActions({ collection, _ids: selectedRows }),
        ]).then(([accessData, actionsData]) => {
            setCollectionAccess(accessData?.result ?? null);
            setActions(actionsData?.result ?? []);
        }).catch(() => {
            setCollectionAccess(null);
            setActions([]);
        }).finally(() => {
            setLoading(false);
        });
    };

    const getMenu = (): MenuData[] => {
        return getFastMenu({ structure, relations, onClearSelected, onEditFields, onDoAction, onDeleteSelected, onExportSelected, onOpenRelationTable, collectionAccess, actions });
    }

    if (isMobile) {
        return <AnyDropdownMenu
            className="fixed right-3 bottom-1/2 bottom-safe-14 transform -translate-y-1/2 z-20"
            menu={getMenu()}
            onOpen={onOpen}
            loading={loading}
        >
            <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()}
            onOpen={onOpen}
            loading={loading}
        >
            <Button
                variant="outline"
                size="icon"
                tooltip={Lang.key('more_options')}
                aria-label={Lang.key('more_options')}
            >
                <MoreHorizontalIcon />
            </Button>

        </AnyDropdownMenu>

    </ButtonGroup>

}

export default SelectedRowButton;
