// ============================================================
// CategoryTabs — 内容分类标签栏（阶段感知 + 数量徽标）
//
// Assets 阶段 → 资产分类：
//   全部 | 角色(chr) | 道具(prp) | 场景(set) | 收藏
//   → 映射到 store.assetTypeFilter + favoriteOnly
//
// 其他阶段 → 审核分类：
//   所有[阶段名] | 收藏 | 待审核 | 通过 | 返修 | 已弃用
//   → 映射到 store.auditFilter + favoriteOnly
//
// 每个标签显示对应数据的数量徽标（基于当前已加载 items 计算）。
// "收藏"标签额外显示媒体类型细分（视频/图片/音频）。
// ============================================================

import { useMemo } from 'react';
import { useTheme } from '@/app/providers/ThemeProvider';
import { useCanvasStore, type AssetTypeFilter, type AuditStatus } from '../../stores/useCanvasStore';

interface CategoryTab {
    key: string;
    label: string;
}

// ── 工具：根据扩展名判断媒体类型 ──

type MediaType = 'video' | 'image' | 'audio' | 'other';

const VIDEO_EXTS = new Set(['mp4', 'mov', 'avi', 'mkv', 'webm', 'm4v', 'wmv']);
const AUDIO_EXTS = new Set(['mp3', 'wav', 'aac', 'flac', 'ogg', 'wma', 'm4a']);
const IMAGE_EXTS = new Set([
    'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'tiff', 'tga', 'exr', 'psd',
]);

function getMediaType(ext: string): MediaType {
    const lower = ext.toLowerCase();
    if (VIDEO_EXTS.has(lower)) return 'video';
    if (IMAGE_EXTS.has(lower)) return 'image';
    if (AUDIO_EXTS.has(lower)) return 'audio';
    return 'other';
}

// ── 工具：根据目录路径推断资产类型 ──

function inferAssetType(path: string): AssetTypeFilter {
    const lower = path.toLowerCase();
    // 路径中包含 \chr\ → 角色，\prp\ → 道具，\set\ → 场景
    if (lower.includes('\\chr\\') || lower.includes('/chr/')) return '角色';
    if (lower.includes('\\prp\\') || lower.includes('/prp/')) return '道具';
    if (lower.includes('\\set\\') || lower.includes('/set/')) return '场景';
    return '全部';
}

export function CategoryTabs() {
    const { isDark } = useTheme();
    const currentStage = useCanvasStore((s) => s.currentStage);
    const assetTypeFilter = useCanvasStore((s) => s.assetTypeFilter);
    const auditFilter = useCanvasStore((s) => s.auditFilter);
    const favoriteOnly = useCanvasStore((s) => s.favoriteOnly);
    const items = useCanvasStore((s) => s.items);
    const setFilters = useCanvasStore((s) => s.setFilters);

    const isAssets = currentStage === 'Assets';

    // 阶段中文名映射
    const stageLabel: Record<string, string> = {
        Assets: '资产',
        Storyboard: '分镜',
        Keyframe: '关键帧',
        Video: '视频',
        Audio: '音频',
        LipSync: '口型',
    };

    // ── 分类数量统计 ──

    const categoryCounts = useMemo(() => {
        const counts: Record<string, number> = {};
        let favoriteMediaCounts: Record<MediaType, number> = { video: 0, image: 0, audio: 0, other: 0 };

        if (isAssets) {
            // Assets 阶段：按 assetType (chr/prp/set) 分类统计
            counts['全部'] = items.length;
            counts['角色'] = 0;
            counts['道具'] = 0;
            counts['场景'] = 0;
            counts['收藏'] = 0;
            for (const item of items) {
                const at = inferAssetType(item.path);
                if (at === '角色') counts['角色']++;
                else if (at === '道具') counts['道具']++;
                else if (at === '场景') counts['场景']++;
                if (item.metadata?.favorite) {
                    counts['收藏']++;
                    favoriteMediaCounts[getMediaType(item.ext)]++;
                }
            }
        } else {
            // 非 Assets 阶段：按审核状态 + 收藏统计
            counts['all'] = items.length;
            counts['pending'] = 0;
            counts['approved'] = 0;
            counts['rework'] = 0;
            counts['deprecated'] = 0;
            counts['收藏'] = 0;
            for (const item of items) {
                const status = item.metadata?.audit_status;
                if (status) counts[status] = (counts[status] || 0) + 1;
                if (item.metadata?.favorite) {
                    counts['收藏']++;
                    favoriteMediaCounts[getMediaType(item.ext)]++;
                }
            }
        }

        return { counts, favoriteMediaCounts };
    }, [items, isAssets]);

    // ── 根据阶段决定标签组 ──

    const tabs: CategoryTab[] = useMemo(() => {
        if (isAssets) {
            return [
                { key: '全部', label: '全部' },
                { key: '角色', label: '角色' },
                { key: '道具', label: '道具' },
                { key: '场景', label: '场景' },
                { key: '收藏', label: '⭐ 收藏' },
            ];
        }
        const label = stageLabel[currentStage] || currentStage;
        return [
            { key: 'all', label: `所有${label}` },
            { key: '收藏', label: '⭐ 收藏' },
            { key: 'pending', label: '待审核' },
            { key: 'approved', label: '通过' },
            { key: 'rework', label: '返修' },
            { key: 'deprecated', label: '已弃用' },
        ];
    }, [isAssets, currentStage]);

    // ── 点击处理 ──

    const handleTabClick = (key: string) => {
        if (isAssets) {
            if (key === '收藏') {
                setFilters({ favoriteOnly: !favoriteOnly, assetTypeFilter: '全部' });
            } else {
                setFilters({ assetTypeFilter: key as AssetTypeFilter, favoriteOnly: false });
            }
        } else {
            if (key === '收藏') {
                setFilters({ favoriteOnly: !favoriteOnly, auditFilter: 'all' });
            } else {
                setFilters({ auditFilter: key as AuditStatus | 'all', favoriteOnly: false });
            }
        }
    };

    // ── 判断标签是否激活 ──

    const isTabActive = (tab: CategoryTab): boolean => {
        if (tab.key === '收藏') return favoriteOnly;
        if (isAssets) return !favoriteOnly && tab.key === assetTypeFilter;
        return !favoriteOnly && tab.key === auditFilter;
    };

    // ── 收藏媒体细分提示 ──

    const buildFavoriteTooltip = () => {
        const { favoriteMediaCounts } = categoryCounts;
        const parts: string[] = [];
        if (favoriteMediaCounts.video > 0) parts.push(`视频:${favoriteMediaCounts.video}`);
        if (favoriteMediaCounts.image > 0) parts.push(`图片:${favoriteMediaCounts.image}`);
        if (favoriteMediaCounts.audio > 0) parts.push(`音频:${favoriteMediaCounts.audio}`);
        if (favoriteMediaCounts.other > 0) parts.push(`其他:${favoriteMediaCounts.other}`);
        return parts.length > 0 ? ` ${parts.join(' / ')}` : '';
    };

    const activeBg = isDark ? '#3E3A6A' : '#E0E7FF';
    const activeColor = isDark ? '#C4B5FD' : '#4338CA';
    const inactiveColor = isDark ? '#6E6B90' : '#9CA3AF';
    const badgeBg = isDark ? 'rgba(110, 107, 144, 0.5)' : 'rgba(156, 163, 175, 0.3)';

    return (
        <div
            style={{
                display: 'flex',
                alignItems: 'center',
                gap: 0,
                padding: '2px 4px',
                borderRadius: 6,
                background: isDark ? 'rgba(21, 19, 46, 0.8)' : 'rgba(245, 243, 255, 0.8)',
                border: `1px solid ${isDark ? '#2E2A5A' : '#E5E7EB'}`,
                overflowX: 'auto',
                scrollbarWidth: 'none' as const,
            }}
        >
            {tabs.map((tab) => {
                const isActive = isTabActive(tab);
                const count = categoryCounts.counts[tab.key] ?? 0;
                const tooltip = tab.key === '收藏' ? `${count} 个收藏${buildFavoriteTooltip()}` : undefined;

                return (
                    <button
                        key={tab.key}
                        type="button"
                        onClick={() => handleTabClick(tab.key)}
                        title={tooltip ?? undefined}
                        style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 3,
                            padding: '3px 10px',
                            border: 'none',
                            borderRadius: 4,
                            cursor: 'pointer',
                            fontSize: 13,
                            fontWeight: isActive ? 600 : 400,
                            background: isActive ? activeBg : 'transparent',
                            color: isActive ? activeColor : inactiveColor,
                            transition: 'all 0.15s',
                            whiteSpace: 'nowrap',
                            flexShrink: 0,
                        }}
                    >
                        {tab.label}
                        {count > 0 && (
                            <span
                                style={{
                                    display: 'inline-flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    minWidth: 18,
                                    height: 17,
                                    padding: '0 4px',
                                    borderRadius: 8,
                                    fontSize: 10,
                                    fontWeight: 600,
                                    background: badgeBg,
                                    color: isActive ? activeColor : inactiveColor,
                                    lineHeight: 1,
                                }}
                            >
                                {count}
                            </span>
                        )}
                    </button>
                );
            })}
        </div>
    );
}
