import { useState, useCallback } from 'react';

import type { DialogProps } from '@/components/Dialog';

import { createModel } from '../utils/model/createModel';

interface DialogItem extends Omit<DialogProps, 'open' | 'id' | 'zIndex'> {
    id: string;
    zIndex: number;
    closeOnOverlayClick?: boolean;
}

interface DialogState {
    dialogs: DialogItem[];
    nextZIndex: number;
}

interface DialogModel extends DialogState {
    /** 打开弹窗
     * @param props 弹窗配置，字段说明：
     *   - title: 弹窗标题（React.ReactNode）
     *   - content: 弹窗主体内容（React.ReactNode）
     *   - icon: 可选，标题前图标（string 或 IconifyIcon）
     *   - buttons: 可选，底部按钮列表，每项为 { label, onClick?(event, dialogId), variant?: 'primary'|'secondary' }
     *   - maskClosable: 可选，点击遮罩是否关闭，默认 true
     *   - closeable: 可选，是否显示关闭按钮，默认 false
     * @returns 该弹窗的唯一 id，用于 closeDialog
     */
    openDialog: (props: Omit<DialogProps, 'open' | 'id' | 'zIndex'>) => string;
    /** 关闭指定弹窗
     * @param id openDialog 返回的弹窗 id
     * @returns void
     */
    closeDialog: (id: string) => void;
}

const BASE_Z_INDEX = 500;

const useDialogModel = (): DialogModel => {
    const [state, setState] = useState<DialogState>({
        dialogs: [],
        nextZIndex: BASE_Z_INDEX,
    });

    const openDialog = useCallback((props: Omit<DialogProps, 'open' | 'id' | 'zIndex'>): string => {
        const id = `dialog-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        setState((prev) => {
            const zIndex = prev.nextZIndex;
            const newDialog: DialogItem = {
                ...props,
                id,
                zIndex,
            };
            return {
                ...prev,
                dialogs: [...prev.dialogs, newDialog],
                nextZIndex: zIndex + 1,
            };
        });
        return id;
    }, []);

    const closeDialog = useCallback((id: string) => {
        setState((prev) => ({
            ...prev,
            dialogs: prev.dialogs.filter((dialog) => dialog.id !== id),
        }));
    }, []);

    return {
        ...state,
        openDialog,
        closeDialog,
    };
};

export const dialogModel = createModel(useDialogModel, 'dialog');
