// ============================================================
// EpisodeSelector — 集数下拉选择器
//
// 列出 selectedProject/shots/ 下的子文件夹作为可选集数。
// 右击菜单项定义见 menus/episode-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 { getEpisodeMenuItems } from '../../controllers/menus';

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) {
                logger.warn('canvas', '加载镜头列表失败', err instanceof Error ? err : new Error(String(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) {
                logger.warn('canvas', '创建集数失败', err instanceof Error ? err : undefined);
            message.error(`创建失败: ${(err as Error).message}`);
            }
        },
        [workspaceRoot, selectedProject, getDataSource, setEpisodes, handleSelect, message],
    );

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

    const menuItems = getEpisodeMenuItems({
        canCreate: !!selectedProject,
        canOpenFolder: !!selectedProject && !!selectedEpisode && !!workspaceRoot,
        onCreate: () => setCreateOpen(true),
        onStats: () => message.info('统计集数功能待实现'),
        onOpenFolder: () => {
            if (workspaceRoot && selectedProject && selectedEpisode) {
                const path = `${workspaceRoot}\\${selectedProject}\\shots\\${selectedEpisode}`;
                window.fileStorage?.showItemInFolder(path);
            }
        },
    });

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

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

    return (
        <>
            <ContextMenu items={menuItems}>
                <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)}
            />
        </>
    );
}
