// ============================================================
// EpisodeSelector — 集数下拉选择器
//
// 列出 selectedProject/shots/ 下的子文件夹作为可选集数。
// 右击可新建集数。Assets 阶段隐藏。
// ============================================================

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 EpisodeSelector() {
    const { message } = App.useApp();
    const workspaceRoot = useCanvasStore((s) => s.workspaceRoot);
    const selectedProject = useCanvasStore((s) => s.selectedProject);
    const episodes = useCanvasStore((s) => s.episodes);
    const selectedEpisode = useCanvasStore((s) => s.selectedEpisode);
    const selectEpisode = useCanvasStore((s) => s.selectEpisode);
    const setShots = useCanvasStore((s) => s.setShots);
    const setEpisodes = useCanvasStore((s) => s.setEpisodes);
    const currentStage = useCanvasStore((s) => s.currentStage);
    const getDataSource = useCanvasStore((s) => s.getDataSource);

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

    const handleSelect = useCallback(
        async (name: string) => {
            selectEpisode(name);
            // 异步加载该集数下的镜头列表
            try {
                if (!workspaceRoot || !selectedProject) return;
                const dataSource = getDataSource();
                const shotsPath = `${workspaceRoot}\\${selectedProject}\\shots\\${name}`;
                const shots = await dataSource.listSubdirs(shotsPath);
                setShots(shots);
            } catch (err) {
                console.error('[EpisodeSelector] 加载镜头列表失败:', err);
            }
        },
        [workspaceRoot, selectedProject, selectEpisode, setShots, getDataSource],
    );

    const handleCreate = useCallback(
        async (dirName: string) => {
            if (!workspaceRoot || !selectedProject) return;
            try {
                const dataSource = getDataSource();
                const parentPath = `${workspaceRoot}\\${selectedProject}\\shots`;
                await dataSource.createDirectory(parentPath, dirName);
                // 刷新集数列表
                const updated = await dataSource.listSubdirs(parentPath);
                setEpisodes(updated);
                // 自动选中新集数
                await handleSelect(dirName);
                message.success(`集数 "${dirName}" 已创建`);
            } catch (err) {
                message.error(`创建失败: ${(err as Error).message}`);
            }
        },
        [workspaceRoot, selectedProject, getDataSource, setEpisodes, handleSelect, message],
    );

    // Assets 阶段隐藏集数选择器
    if (currentStage === 'Assets') return null;

    const options = episodes.map((ep) => ({ value: ep, label: ep }));

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