// ============================================================
// CanvasPage — 无限画布页面（AntD Layout 双栏布局）
//
//   ┌──────────────┬─────────────────────────────────────────┐
//   │  CanvasSidebar│  CanvasToolbar                         │
//   │  ├ 项目选择    │  ├ StageTabs + 无限画布                 │
//   │  ├ 集数选择    │  ├ CategoryTabs + FilterBar            │
//   │  ├ 镜头搜索    │  ├────────────────────────────────────┤
//   │  ├ 镜头列表    │  │ CanvasViewport（或 Placeholder）     │
//   │  └ 刷新按钮    │  │                                     │
//   └──────────────┴─────────────────────────────────────────┘
//                        └── 底部状态栏 ─────────────────────────┘
// ============================================================

import { useState, useCallback } from 'react';
import { Layout } from 'antd';
import { useTheme } from '@/app/providers/ThemeProvider';
import { useCanvasStore } from '../stores/useCanvasStore';
import { useDirectoryScan } from '../hooks/useDirectoryScan';
import { CanvasToolbar } from './toolbar/CanvasToolbar';
import { CanvasViewport } from './core/CanvasViewport';
import { MediaPreview } from './core/MediaPreview';
import { CanvasSidebar } from './navigation/CanvasSidebar';

const { Sider, Content } = Layout;

/** 中心区域占位提示 */
function Placeholder({
    icon,
    title,
    hint,
    isDark,
}: {
    icon: string;
    title: string;
    hint: string;
    isDark: boolean;
}) {
    return (
        <div
            style={{
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
            }}
        >
            <div style={{ fontSize: 48, marginBottom: 16 }}>{icon}</div>
            <div style={{ fontSize: 14, color: isDark ? '#A5A3C0' : '#6B7280' }}>{title}</div>
            <div
                style={{
                    fontSize: 13,
                    marginTop: 8,
                    color: isDark ? '#6E6B90' : '#9CA3AF',
                }}
            >
                {hint}
            </div>
        </div>
    );
}

export function CanvasPage() {
    const { isDark } = useTheme();
    const workspaceRoot = useCanvasStore((s) => s.workspaceRoot);
    const selectedProject = useCanvasStore((s) => s.selectedProject);
    const selectedEpisode = useCanvasStore((s) => s.selectedEpisode);
    const selectedShot = useCanvasStore((s) => s.selectedShot);
    const items = useCanvasStore((s) => s.items);
    const isScanning = useCanvasStore((s) => s.isScanning);
    const currentStage = useCanvasStore((s) => s.currentStage);

    // 启动目录扫描监听
    useDirectoryScan();

    // ── 全屏预览状态 ──
    const [previewItemId, setPreviewItemId] = useState<number | null>(null);

    const handlePreviewOpen = useCallback((itemId: number) => {
        setPreviewItemId(itemId);
    }, []);

    const handlePreviewClose = useCallback(() => {
        setPreviewItemId(null);
    }, []);

    const isAssets = currentStage === 'Assets';

    /** 根据当前选中状态决定主视图内容 */
    const renderMainContent = () => {
        if (!workspaceRoot) {
            return (
                <Placeholder
                    icon="📂"
                    title="请先选择一个工作区目录"
                    hint="从左侧边栏打开或切换工作区"
                    isDark={isDark}
                />
            );
        }

        if (!selectedProject) {
            return (
                <Placeholder
                    icon="📁"
                    title="请先选择一个项目"
                    hint="从左侧边栏的项目下拉列表中选择"
                    isDark={isDark}
                />
            );
        }

        if (isScanning) {
            return (
                <div
                    style={{
                        flex: 1,
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                    }}
                >
                    <div style={{ fontSize: 32, marginBottom: 12 }}>🔍</div>
                    <div style={{ fontSize: 14 }}>正在扫描文件…</div>
                </div>
            );
        }

        if (!isAssets && !selectedEpisode) {
            return (
                <Placeholder
                    icon="🎬"
                    title="请先选择集数"
                    hint="从左侧边栏的集数下拉列表中选择"
                    isDark={isDark}
                />
            );
        }

        if (!isAssets && !selectedShot) {
            return (
                <Placeholder
                    icon="🎞️"
                    title="请先选择镜头"
                    hint="从左侧边栏的镜头列表中点击选择"
                    isDark={isDark}
                />
            );
        }

        if (items.length === 0) {
            return (
                <Placeholder
                    icon="📭"
                    title={`当前阶段「${currentStage}」没有匹配的文件`}
                    hint="请确认目录结构，或切换阶段标签"
                    isDark={isDark}
                />
            );
        }

        return <CanvasViewport onPreviewOpen={handlePreviewOpen} previewActive={previewItemId !== null} />;
    };

    const borderColor = isDark ? '#2E2A5A' : '#E5E7EB';

    return (
        <Layout
            style={{
                width: '100vw',
                height: '100vh',
                overflow: 'hidden',
            }}
            hasSider
        >
            {/* ── 左侧导航边栏 ── */}
            <Sider
                width={220}
                style={{
                    background: isDark ? '#0F0D21' : '#F5F3FF',
                    borderRight: `1px solid ${borderColor}`,
                    overflow: 'hidden',
                }}
                trigger={null}
            >
                <CanvasSidebar />
            </Sider>

            {/* ── 右侧主内容区 ── */}
            <Layout
                style={{
                    background: isDark ? '#0F0D1E' : '#F5F3FF',
                }}
            >
                <Content
                    style={{
                        display: 'flex',
                        flexDirection: 'column',
                        overflow: 'hidden',
                    }}
                >
                    {/* 顶部工具栏（两行：阶段标签 + 分类标签/筛选） */}
                    <CanvasToolbar />

                    {/* 主画布区域 */}
                    <div
                        style={{
                            flex: 1,
                            display: 'flex',
                            overflow: 'hidden',
                        }}
                    >
                        {renderMainContent()}
                    </div>

                    {/* 底部状态栏 */}
                    <div
                        style={{
                            height: 28,
                            flexShrink: 0,
                            display: 'flex',
                            alignItems: 'center',
                            padding: '0 12px',
                            borderTop: `1px solid ${borderColor}`,
                            background: isDark ? '#15132E' : '#EEF2FF',
                            fontSize: 12,
                            color: isDark ? '#6E6B90' : '#9CA3AF',
                        }}
                    >
                        <span>离线模式 · 本地文件系统</span>
                        <span style={{ margin: '0 8px' }}>|</span>
                        <span>
                            {isScanning
                                ? '扫描中…'
                                : workspaceRoot
                                    ? `项目：${selectedProject || '(未选)'} · 阶段：${currentStage} · ${items.length} 个文件`
                                    : '准备就绪'}
                        </span>
                        {selectedEpisode && (
                            <>
                                <span style={{ margin: '0 4px' }}>|</span>
                                <span>集数：{selectedEpisode}</span>
                            </>
                        )}
                        {selectedShot && (
                            <>
                                <span style={{ margin: '0 4px' }}>|</span>
                                <span>镜头：{selectedShot}</span>
                            </>
                        )}
                        <span style={{ flex: 1 }} />
                        <span>Phase 1</span>
                    </div>
                </Content>
            </Layout>

            {/* 全屏预览（页面级别渲染，与画布 DOM 解耦） */}
            <MediaPreview itemId={previewItemId} onClose={handlePreviewClose} />
        </Layout>
    );
}
