// ============================================================
// MediaCardContextMenu — 右键菜单
//
// 功能：
//   - 打开文件所在位置（showItemInFolder）
//   - 复制文件路径
//   - 切换审核状态
//   - 删除文件及其 sidecar
// ============================================================

import { Dropdown, type MenuProps, message, Modal } from 'antd';
import {
    FolderOpenOutlined,
    CopyOutlined,
    CheckCircleOutlined,
    CloseCircleOutlined,
    DeleteOutlined,
} from '@ant-design/icons';
import { useCallback } from 'react';
import { useCanvasStore } from '../store/useCanvasStore';
import { useSidecarSync } from '../hooks/useSidecarSync';
import { safeIpcInvoke } from '@/utils/bus';
import { BIDIRECTIONAL } from '@shared/constants/ipc-channels';
import { ITEM_W, ITEM_H } from '../utils/constants';
import type { AuditStatus } from '../store/useCanvasStore';

interface MediaCardContextMenuProps {
    itemId: number;
    children: React.ReactNode;
    /** 画布中的绝对定位（传递给 Dropdown 外层容器，确保右键区域尺寸正确） */
    x: number;
    y: number;
}

export function MediaCardContextMenu({ itemId, children, x, y }: MediaCardContextMenuProps) {
    const item = useCanvasStore((s) => s.items.find((i) => i.id === itemId));
    const getDataSource = useCanvasStore((s) => s.getDataSource);
    const { commitMetadata } = useSidecarSync();

    const handleShowInFolder = useCallback(async () => {
        if (!item) return;
        await safeIpcInvoke(BIDIRECTIONAL.SHOW_ITEM_IN_FOLDER, {
            filePath: item.path,
        });
    }, [item]);

    const handleCopyPath = useCallback(async () => {
        if (!item) return;
        try {
            await navigator.clipboard.writeText(item.path);
            void message.success('已复制文件路径');
        } catch {
            void message.error('复制失败');
        }
    }, [item]);

    const handleSetAudit = useCallback(
        (status: AuditStatus) => {
            if (!item) return;
            // commitMetadata 同时更新 Store 内存 + 写入磁盘 .json 侧加载文件
            commitMetadata(itemId, item.path, { audit_status: status });
            void message.success(`审核状态已更新为：${status}`);
        },
        [item, itemId, commitMetadata],
    );

    const handleDelete = useCallback(() => {
        if (!item) return;
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除「${item.fileName}」及其元数据吗？`,
            okText: '删除',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const dataSource = getDataSource();
                    await dataSource.deleteFile(item.path);
                    void message.success('已删除');
                } catch {
                    void message.error('删除失败');
                }
            },
        });
    }, [item, getDataSource]);

    if (!item) return <>{children}</>;

    const isAuditable = ['Storyboard', 'Keyframe', 'Video'].includes(item.stage);

    const menuItems: MenuProps['items'] = [
        {
            key: 'show',
            label: '在文件管理器中显示',
            icon: <FolderOpenOutlined />,
            onClick: () => void handleShowInFolder(),
        },
        {
            key: 'copy',
            label: '复制文件路径',
            icon: <CopyOutlined />,
            onClick: () => void handleCopyPath(),
        },
        ...(isAuditable
            ? [
                  { type: 'divider' as const },
                  {
                      key: 'audit-header',
                      label: '审核状态',
                      disabled: true,
                  },
                  {
                      key: 'audit-pending',
                      label: '⏳ 待审核',
                      icon: <CheckCircleOutlined style={{ color: '#FAAD14' }} />,
                      onClick: () => handleSetAudit('pending'),
                  },
                  {
                      key: 'audit-approved',
                      label: '✅ 已通过',
                      icon: <CheckCircleOutlined style={{ color: '#52C41A' }} />,
                      onClick: () => handleSetAudit('approved'),
                  },
                  {
                      key: 'audit-rework',
                      label: '🔄 需返工',
                      icon: <CloseCircleOutlined style={{ color: '#FF4D4F' }} />,
                      onClick: () => handleSetAudit('rework'),
                  },
                  {
                      key: 'audit-deprecated',
                      label: '🗑️ 已废弃',
                      icon: <CloseCircleOutlined style={{ color: '#8C8C8C' }} />,
                      onClick: () => handleSetAudit('deprecated'),
                  },
              ]
            : []),
        { type: 'divider' as const },
        {
            key: 'delete',
            label: '删除文件',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDelete(),
        },
    ];

    return (
        <div
            style={{
                position: 'absolute',
                left: x,
                top: y,
                width: ITEM_W,
                height: ITEM_H,
            }}
        >
            <Dropdown menu={{ items: menuItems }} trigger={['contextMenu']}>
                {children}
            </Dropdown>
        </div>
    );
}
