// ============================================================
// ProjectSelector — 项目下拉选择器
//
// 列出 workspaceRoot 下的子文件夹作为可选项目。
// 右击可新建项目。
// ============================================================

import { useState, useCallback } from 'react';
import { Select, App } from 'antd';
import { useCanvasStore } from '../store/useCanvasStore';
import { ContextMenu } from './ContextMenu';
import { DirectoryCreateModal } from './DirectoryCreateModal';

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) {
                console.error('[ProjectSelector] 加载集数列表失败:', 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) {
                message.error(`创建失败: ${(err as Error).message}`);
            }
        },
        [workspaceRoot, getDataSource, setProjects, handleSelect, message],
    );

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

    return (
        <>
            <ContextMenu
                items={[
                    {
                        label: '新建项目',
                        onClick: () => setCreateOpen(true),
                        disabled: !workspaceRoot,
                    },
                ]}
            >
                <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)}
            />
        </>
    );
}
