// ============================================================
// ProjectSelector — 项目下拉选择器
//
// 列出 workspaceRoot 下的子文件夹作为可选项目。
// 右击菜单项定义见 menus/project-menu.ts
// ============================================================

import { useState, useCallback } from 'react';
import { logger } from '@/shared/utils/bus';
import { Select, App } from 'antd';
import { useCanvasStore } from '../../stores/useCanvasStore';
import { ContextMenu } from '@/shared/components/ContextMenu';
import { DirectoryCreateModal } from './DirectoryCreateModal';
import { getProjectMenuItems } from '../../controllers/menus';

export function ProjectSelector() {
    const { message } = App.useApp();
    const workspaceRoot = useCanvasStore((s) => s.workspaceRoot);
    const projects = useCanvasStore((s) => s.projects);
    const selectedProject = useCanvasStore((s) => s.selectedProject);
    const selectProject = useCanvasStore((s) => s.selectProject);
    const setEpisodes = useCanvasStore((s) => s.setEpisodes);
    const setProjects = useCanvasStore((s) => s.setProjects);
    const getDataSource = useCanvasStore((s) => s.getDataSource);

    const [createOpen, setCreateOpen] = useState(false);

    const handleSelect = useCallback(
        async (name: string) => {
            selectProject(name);
            try {
                const dataSource = getDataSource();
                const epPath = `${workspaceRoot}\\${name}\\shots`;
                const episodes = await dataSource.listSubdirs(epPath);
                setEpisodes(episodes);
            } catch (err) {
                logger.warn('canvas', '加载集数列表失败', err instanceof Error ? err : new Error(String(err)));
            }
        },
        [workspaceRoot, selectProject, setEpisodes, getDataSource],
    );

    const handleCreate = useCallback(
        async (dirName: string) => {
            if (!workspaceRoot) return;
            try {
                const dataSource = getDataSource();
                await dataSource.createDirectory(workspaceRoot, dirName);
                const updated = await dataSource.listSubdirs(workspaceRoot);
                setProjects(updated);
                await handleSelect(dirName);
                message.success(`项目 "${dirName}" 已创建`);
            } catch (err) {
                logger.warn('canvas', '创建项目失败', err instanceof Error ? err : undefined);
            message.error(`创建失败: ${(err as Error).message}`);
            }
        },
        [workspaceRoot, getDataSource, setProjects, handleSelect, message],
    );

    // ── 右键菜单定义 ──

    const menuItems = getProjectMenuItems({
        canCreate: !!workspaceRoot,
        canOpenFolder: !!selectedProject && !!workspaceRoot,
        onCreate: () => setCreateOpen(true),
        onStats: () => message.info('统计项目功能待实现'),
        onBatchShots: () => message.info('批量创建镜头功能待实现'),
        onOpenFolder: () => {
            if (workspaceRoot && selectedProject) {
                const path = `${workspaceRoot}\\${selectedProject}`;
                window.fileStorage?.showItemInFolder(path);
            }
        },
    });

    const options = projects.map((p) => ({ value: p, label: p }));

    return (
        <>
            <ContextMenu items={menuItems}>
                <Select
                    value={selectedProject}
                    onChange={handleSelect}
                    placeholder="选择项目"
                    size="small"
                    style={{ width: '100%' }}
                    options={options}
                    disabled={!workspaceRoot}
                    showSearch
                    filterOption={(input, option) =>
                        (option?.label as string)?.toLowerCase().includes(input.toLowerCase())
                    }
                />
            </ContextMenu>
            <DirectoryCreateModal
                open={createOpen}
                title="新建项目"
                onOk={handleCreate}
                onCancel={() => setCreateOpen(false)}
            />
        </>
    );
}
