import React, { useEffect, useState, useCallback, useMemo, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft, FolderOpen, Upload, FileVideo, FileAudio, FileImage, HardDrive, Brain, Loader2, Link, Layers, Calendar, MapPin, Users, CheckCircle, Filter, Shuffle, Download, Trash2, Square, CheckSquare, MinusSquare } from 'lucide-react';
import { invoke } from '@tauri-apps/api/core';
import { useProjectStore } from '../store/projectStore';
import { useMaterialStore } from '../store/materialStore';
import { useVideoClassificationStore } from '../store/videoClassificationStore';
import { Project } from '../types/project';
import { Material, MaterialImportResult, BatchDeleteResult } from '../types/material';
import { ProjectBatchClassificationRequest, ProjectBatchClassificationResponse } from '../types/videoClassification';
import { LoadingSpinner } from '../components/LoadingSpinner';
import { ErrorMessage } from '../components/ErrorMessage';
import { MaterialImportDialog } from '../components/MaterialImportDialog';
import { MaterialCard } from '../components/MaterialCard';
import { MaterialEditDialog } from '../components/MaterialEditDialog';
import { VideoClassificationProgress } from '../components/VideoClassificationProgress';
import { AiAnalysisLogViewer } from '../components/AiAnalysisLogViewer';
import MaterialCardSkeleton from '../components/MaterialCardSkeleton';
import ExportRecordManager from '../components/ExportRecordManager';
import { ProjectTemplateBindingList } from '../components/ProjectTemplateBindingList';
import { ProjectTemplateBindingForm } from '../components/ProjectTemplateBindingForm';
import { MaterialMatchingResultDialog } from '../components/MaterialMatchingResultDialog';
import { useProjectTemplateBindingStore } from '../stores/projectTemplateBindingStore';
import { useTemplateStore } from '../stores/templateStore';
import {
  ProjectTemplateBindingDetail,
  CreateProjectTemplateBindingRequest,
  UpdateProjectTemplateBindingRequest
} from '../types/projectTemplateBinding';
import { MaterialMatchingService } from '../services/materialMatchingService';
import { MaterialMatchingResult, MaterialMatchingRequest } from '../types/materialMatching';
import { MaterialSegmentView } from '../components/MaterialSegmentView';
import { BatchMatchingService } from '../services/batchMatchingService';
import { BatchMatchingRequest, BatchMatchingResult, BatchMatchingProgress, BatchMatchingProgressStatus } from '../types/batchMatching';
import { BatchMatchingResultDialog } from '../components/BatchMatchingResultDialog';
import { BatchMatchingProgressDialog } from '../components/BatchMatchingProgressDialog';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { MaterialSegmentStats } from '../components/MaterialSegmentStats';
import { MaterialSegmentViewMode } from '../types/materialSegmentView';
import { TemplateMatchingResultManager } from '../components/TemplateMatchingResultManager';
import { useNotifications } from '../components/NotificationSystem';
import { ProjectMaterialUsageOverviewComponent } from '../components/ProjectMaterialUsageOverview';
import { useMaterialUsage } from '../hooks/useMaterialUsage';
import { useBatchSelection, calculateSelectionState } from '../hooks/useBatchSelection';
import { BatchDeleteConfirmDialog } from '../components/BatchDeleteConfirmDialog';

// 格式化时间
const formatTime = (dateString: string) => {
  try {
    const date = new Date(dateString);
    return formatDistanceToNow(date, {
      addSuffix: true,
      locale: zhCN
    });
  } catch {
    return '未知时间';
  }
};

// 获取项目目录名
const getDirectoryName = (path: string) => {
  const parts = path.split(/[/\\]/);
  return parts[parts.length - 1] || path;
};

/**
 * 项目详情页面组件
 * 遵循 Tauri 开发规范的页面组件设计模式
 */
export const ProjectDetails: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { projects, isLoading, error, loadProjects } = useProjectStore();
  const {
    materials,
    stats,
    loadMaterials,
    loadMaterialStats,
    deleteMaterial,
    batchDeleteMaterials,
    processMaterials,
    isLoading: materialsLoading,
    isBatchDeleting
  } = useMaterialStore();
  const {
    startProjectBatchClassification,
    isLoading: classificationLoading,
    error: _classificationError,
    queueStats,
    getProjectQueueStatus
  } = useVideoClassificationStore();
  const { success: addNotification } = useNotifications();
  const {
    usageOverview,
    loadUsageOverview,
    resetProjectUsage,
    isLoading: usageLoading,
    error: usageError
  } = useMaterialUsage();

  // 模板绑定状态管理
  const {
    bindingDetails,
    loading: bindingLoading,
    error: bindingError,
    selectedBindingIds,
    filters: bindingFilters,
    actions: bindingActions
  } = useProjectTemplateBindingStore();

  // 获取过滤后的绑定详情
  const filteredBindingDetails = React.useMemo(() => {
    if (!bindingDetails.length) return [];

    const filteredBindings = bindingActions.getFilteredBindings();
    return bindingDetails.filter(detail =>
      filteredBindings.some(binding => binding.id === detail.binding.id)
    );
  }, [bindingDetails, bindingFilters, bindingActions.getFilteredBindings]);

  // 模板状态管理
  const { templates, fetchTemplates } = useTemplateStore();

  const [project, setProject] = useState<Project | null>(null);
  const [showImportDialog, setShowImportDialog] = useState(false);
  const [showBindingForm, setShowBindingForm] = useState(false);
  const [editingBinding, setEditingBinding] = useState<ProjectTemplateBindingDetail | null>(null);
  const [showMaterialEditDialog, setShowMaterialEditDialog] = useState(false);
  const [editingMaterial, setEditingMaterial] = useState<Material | null>(null);
  const [activeTab, setActiveTab] = useState<'overview' | 'materials' | 'segments' | 'templates' | 'matching-results' | 'export-records' | 'usage-stats' | 'ai-logs' | 'outfit-match'>('overview');
  const [_batchClassificationResult, setBatchClassificationResult] = useState<ProjectBatchClassificationResponse | null>(null);

  // 素材匹配状态
  const [showMatchingResultDialog, setShowMatchingResultDialog] = useState(false);
  const [matchingResult, setMatchingResult] = useState<MaterialMatchingResult | null>(null);
  const [matchingLoading, setMatchingLoading] = useState(false);
  const [segmentStats, setSegmentStats] = useState<any>(null);
  const [currentMatchingBinding, setCurrentMatchingBinding] = useState<ProjectTemplateBindingDetail | null>(null);

  // 一键匹配状态
  const [showBatchMatchingResultDialog, setShowBatchMatchingResultDialog] = useState(false);
  const [batchMatchingResult, setBatchMatchingResult] = useState<BatchMatchingResult | null>(null);
  const [batchMatchingLoading, setBatchMatchingLoading] = useState(false);
  const [showBatchMatchingProgressDialog, setShowBatchMatchingProgressDialog] = useState(false);
  const [batchMatchingProgress, setBatchMatchingProgress] = useState<BatchMatchingProgress | null>(null);

  // 素材筛选状态
  const [materialClassificationFilter, setMaterialClassificationFilter] = useState<string>('全部');
  const [materialModelFilter, setMaterialModelFilter] = useState<string>('全部');
  const [materialUsageFilter, setMaterialUsageFilter] = useState<string>('全部');
  const [materialClassificationRecords, setMaterialClassificationRecords] = useState<{ [materialId: string]: any[] }>({});
  const [modelsMap, setModelsMap] = useState<{ [modelId: string]: any }>({});

  // 批量删除状态
  const [showBatchDeleteDialog, setShowBatchDeleteDialog] = useState(false);
  const [batchDeleteResult, setBatchDeleteResult] = useState<BatchDeleteResult | null>(null);

  // 批量选择Hook
  const batchSelection = useBatchSelection({
    enabled: true,
    maxSelection: 50 // 限制最多选择50个素材
  });

  // 用于跟踪分类统计是否已加载的ref
  const classificationStatsLoadedRef = useRef<string | null>(null);

  // 加载片段统计数据
  const loadSegmentStats = useCallback(async (projectId: string) => {
    try {
      const segmentView = await invoke('get_project_segment_view', { projectId }) as any;
      setSegmentStats(segmentView.stats);
    } catch (error) {
      console.error('Failed to load segment stats:', error);
      // 设置默认统计数据
      setSegmentStats({
        total_segments: 0,
        total_duration: 0,
        classified_segments: 0,
        unclassified_segments: 0,
        classification_coverage: 0,
        classification_counts: {},
        model_counts: {}
      });
    }
  }, []);

  // 加载所有模特信息
  const loadAllModels = useCallback(async () => {
    try {
      const models = await invoke('get_all_models') as any[];
      const modelMap: { [modelId: string]: any } = {};
      models.forEach(model => {
        modelMap[model.id] = model;
      });
      setModelsMap(modelMap);
    } catch (error) {
      console.error('Failed to load models:', error);
      setModelsMap({});
    }
  }, []);

  // 加载项目分类统计信息
  const loadProjectClassificationStats = useCallback(async (_projectId: string, materialList?: any[]) => {
    try {
      // 使用传入的素材列表或当前的素材列表
      const materialsToProcess = materialList || materials;

      // 获取每个素材的分类记录
      const classificationRecords: { [materialId: string]: any[] } = {};
      for (const material of materialsToProcess) {
        try {
          const records = await invoke('get_material_classification_records', { materialId: material.id }) as any[];
          classificationRecords[material.id] = records;
        } catch (error) {
          console.warn(`Failed to load classification records for material ${material.id}:`, error);
          classificationRecords[material.id] = [];
        }
      }

      setMaterialClassificationRecords(classificationRecords);
    } catch (error) {
      console.error('Failed to load project classification stats:', error);
      setMaterialClassificationRecords({});
    }
  }, []);

  // 加载项目详情
  useEffect(() => {
    if (!projects.length) {
      loadProjects();
    }
  }, [projects.length, loadProjects]);

  // 根据ID查找项目
  useEffect(() => {
    if (id && projects.length > 0) {
      const foundProject = projects.find(p => p.id === id);
      setProject(foundProject || null);

      // 加载项目素材
      if (foundProject) {
        // 重置分类统计加载状态
        classificationStatsLoadedRef.current = null;

        loadMaterials(foundProject.id);
        loadMaterialStats(foundProject.id);
        // 加载项目的模板绑定
        bindingActions.fetchTemplatesByProject(foundProject.id);
        // 加载片段统计数据
        loadSegmentStats(foundProject.id);
        // 加载素材使用状态概览
        loadUsageOverview(foundProject.id);
        // 加载所有模特信息
        loadAllModels();
        // 加载项目分类统计信息将在素材加载完成后执行
      }
    }
  }, [id, projects, loadMaterials, loadMaterialStats, bindingActions.fetchTemplatesByProject, loadSegmentStats, loadUsageOverview, loadAllModels, loadProjectClassificationStats]);

  // 当素材加载完成后，加载分类统计信息
  useEffect(() => {
    if (project && materials.length > 0 && classificationStatsLoadedRef.current !== project.id) {
      classificationStatsLoadedRef.current = project.id;
      loadProjectClassificationStats(project.id, materials);
    }
  }, [project?.id, materials.length, loadProjectClassificationStats]);

  // 加载模板列表
  useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  // 监控AI分类队列状态
  useEffect(() => {
    if (!project) return;

    // 初始加载队列状态
    getProjectQueueStatus(project.id);

    // 设置定时刷新
    const interval = setInterval(() => {
      getProjectQueueStatus(project.id);
    }, 3000); // 每3秒刷新一次

    return () => clearInterval(interval);
  }, [project, getProjectQueueStatus]);

  // 返回项目列表
  const handleBack = () => {
    navigate('/');
  };

  // 打开项目文件夹
  const handleOpenFolder = async () => {
    if (project) {
      try {
        const { openPath } = await import('@tauri-apps/plugin-opener');

        // 处理 Windows 路径格式，移除 \\?\ 前缀
        let normalizedPath = project.path;
        if (normalizedPath.startsWith('\\\\?\\')) {
          normalizedPath = normalizedPath.substring(4);
        }

        console.log('尝试打开路径:', normalizedPath);
        await openPath(normalizedPath);
      } catch (error) {
        console.error('打开文件夹失败:', error);

        // 如果 openPath 失败，尝试使用 revealItemInDir
        try {
          const { revealItemInDir } = await import('@tauri-apps/plugin-opener');
          let normalizedPath = project.path;
          if (normalizedPath.startsWith('\\\\?\\')) {
            normalizedPath = normalizedPath.substring(4);
          }
          console.log('尝试使用 revealItemInDir 打开:', normalizedPath);
          await revealItemInDir(normalizedPath);
        } catch (fallbackError) {
          console.error('备用方法也失败:', fallbackError);
          // 可以在这里显示用户友好的错误提示
          alert('无法打开文件夹，请检查路径是否存在');
        }
      }
    }
  };

  // 素材导入处理
  const handleMaterialImport = () => {
    setShowImportDialog(true);
  };

  // 导入完成处理
  const handleImportComplete = (result: MaterialImportResult) => {
    setShowImportDialog(false);
    console.log('导入完成:', result);
    // 重新加载素材列表
    if (project) {
      // 重置分类统计加载状态，以便重新加载
      classificationStatsLoadedRef.current = null;
      loadMaterials(project.id);
      loadMaterialStats(project.id);
    }
  };
  const { success, warning } = useNotifications()
  // 一键AI分类处理
  const handleBatchClassification = async () => {
    if (!project) return;

    try {
      const request: ProjectBatchClassificationRequest = {
        project_id: project.id,
        overwrite_existing: false, // 默认不覆盖已有分类
        material_types: undefined, // 使用默认值（只处理视频）
        priority: undefined, // 使用默认优先级
      };

      const response = await startProjectBatchClassification(request);
      setBatchClassificationResult(response);

      // 显示结果提示
      const message = `一键分类启动成功！\n` +
        `项目总素材数: ${response.total_materials}\n` +
        `符合条件的素材数: ${response.eligible_materials}\n` +
        `创建的任务数: ${response.created_tasks}\n` +
        `跳过的素材数: ${response.skipped_materials.length}`;

      success(message);

      // 刷新队列状态
      if (project) {
        getProjectQueueStatus(project.id);
      }
    } catch (error) {
      console.error('一键分类失败:', error);
      warning(`一键分类失败: ${error}`);
    }
  };

  // 模板绑定处理函数
  const handleAddBinding = () => {
    setEditingBinding(null);
    setShowBindingForm(true);
  };

  const handleEditBinding = (detail: ProjectTemplateBindingDetail) => {
    setEditingBinding(detail);
    setShowBindingForm(true);
  };

  const handleDeleteBinding = async (id: string) => {
    try {
      await bindingActions.deleteBinding(id);
      if (project) {
        bindingActions.fetchTemplatesByProject(project.id);
      }
    } catch (error) {
      console.error('删除绑定失败:', error);
    }
  };

  const handleToggleBindingStatus = async (id: string) => {
    try {
      await bindingActions.toggleBindingStatus(id);
      if (project) {
        bindingActions.fetchTemplatesByProject(project.id);
      }
    } catch (error) {
      console.error('切换绑定状态失败:', error);
    }
  };

  const handleSetPrimaryTemplate = async (projectId: string, templateId: string) => {
    try {
      await bindingActions.setPrimaryTemplate(projectId, templateId);
    } catch (error) {
      console.error('设置主要模板失败:', error);
    }
  };

  const handleBindingFormSubmit = async (data: CreateProjectTemplateBindingRequest | UpdateProjectTemplateBindingRequest) => {
    try {
      if (editingBinding) {
        await bindingActions.updateBinding(editingBinding.binding.id, data as UpdateProjectTemplateBindingRequest);
      } else {
        await bindingActions.createBinding(data as CreateProjectTemplateBindingRequest);
      }
      if (project) {
        bindingActions.fetchTemplatesByProject(project.id);
      }
      setShowBindingForm(false);
      setEditingBinding(null);
    } catch (error) {
      console.error('保存绑定失败:', error);
      throw error;
    }
  };
  // 素材匹配处理函数
  const handleMatchMaterials = async (binding: ProjectTemplateBindingDetail) => {
    if (!project) return;

    try {
      setCurrentMatchingBinding(binding);
      setMatchingLoading(true);
      setShowMatchingResultDialog(true);

      const request: MaterialMatchingRequest = {
        project_id: project.id,
        template_id: binding.binding.template_id,
        binding_id: binding.binding.id,
        overwrite_existing: false,
      };

      const result = await MaterialMatchingService.executeMatching(request);
      console.log({ result })
      setMatchingResult(result);
    } catch (error) {
      console.error('素材匹配失败:', error);
      warning(`素材匹配失败: ${error}`);
      setShowMatchingResultDialog(false);
    } finally {
      setMatchingLoading(false);
    }
  };

  const handleApplyMatchingResult = async (result: MaterialMatchingResult) => {
    try {
      if (!currentMatchingBinding) {
        throw new Error('没有找到当前匹配绑定信息');
      }

      // 生成结果名称
      const resultName = `匹配结果_${new Date().toLocaleString('zh-CN')}`;
      const description = `模板 ${currentMatchingBinding.template_name} 的匹配结果，成功匹配 ${result.statistics.matched_segments} 个片段`;

      // 调用后端API保存匹配结果
      const savedResult = await invoke('save_matching_result', {
        serviceResult: {
          project_id: project?.id,
          template_id: currentMatchingBinding.binding.template_id,
          binding_id: currentMatchingBinding.binding.id,
          matches: result.matches,
          failed_segments: result.failed_segments,
          statistics: result.statistics,
          matching_duration_ms: 0 // MaterialMatchingResult 没有这个字段，使用默认值
        },
        resultName,
        description,
        matchingDurationMs: 0 // 使用默认值
      });

      console.log({ savedResult })
      // 创建素材使用记录
      if (savedResult && typeof savedResult === 'object' && 'id' in savedResult) {
        try {
          await invoke('create_usage_records_from_matching_result', {
            projectId: project?.id,
            templateId: currentMatchingBinding.binding.template_id,
            bindingId: currentMatchingBinding.binding.id,
            templateMatchingResultId: (savedResult as any).id,
            matches: result.matches
          });
          console.log('素材使用记录创建成功');
        } catch (usageError) {
          console.warn('创建素材使用记录失败，但匹配结果已保存:', usageError);
          // 不阻断主流程，只记录警告
        }
      }

      // 关闭对话框
      setShowMatchingResultDialog(false);
      setMatchingResult(null);
      setCurrentMatchingBinding(null);

      // 显示成功提示
      addNotification('匹配结果已保存', `已成功保存匹配结果"${resultName}"，可在匹配记录页面查看。`);

      // 如果当前在匹配记录选项卡，刷新数据
      if (activeTab === 'matching-results') {
        // 触发匹配记录列表刷新
        window.location.reload();
      }
    } catch (error) {
      console.error('应用匹配结果失败:', error);
      addNotification('保存匹配结果失败', `保存匹配结果时发生错误: ${error}`);
    }
  };

  const handleRetryMatching = () => {
    if (currentMatchingBinding) {
      handleMatchMaterials(currentMatchingBinding);
    }
  };

  const handleCloseMatchingDialog = () => {
    setShowMatchingResultDialog(false);
    setMatchingResult(null);
    setCurrentMatchingBinding(null);
    setMatchingLoading(false);
  };

  // 一键匹配处理函数
  const handleBatchMatching = async () => {
    if (!project) return;

    try {
      setBatchMatchingLoading(true);
      setShowBatchMatchingProgressDialog(true);

      // 设置进度回调
      await BatchMatchingService.setProgressCallback((progress: BatchMatchingProgress) => {
        setBatchMatchingProgress(progress);

        // 当匹配完成时，显示结果对话框
        if (progress.status === BatchMatchingProgressStatus.Completed) {
          setTimeout(() => {
            setShowBatchMatchingProgressDialog(false);
            setShowBatchMatchingResultDialog(true);
          }, 1000); // 延迟1秒显示结果
        } else if (progress.status === BatchMatchingProgressStatus.Failed) {
          setTimeout(() => {
            setShowBatchMatchingProgressDialog(false);
          }, 2000); // 延迟2秒关闭进度对话框
        }
      });

      const request: BatchMatchingRequest = {
        project_id: project.id,
        overwrite_existing: false,
        result_name_prefix: '一键匹配',
      };

      const result = await BatchMatchingService.executeBatchMatching(request);
      setBatchMatchingResult(result);

      // 显示结果提示
      const overallStatus = BatchMatchingService.getOverallStatus(result);
      if (overallStatus === 'success') {
        addNotification(
          '循环匹配成功',
          `完成 ${result.total_rounds} 轮匹配，成功匹配 ${result.successful_matches} 个模板，耗时 ${(result.total_duration_ms / 1000).toFixed(1)} 秒。${result.termination_reason}`
        );
      } else if (overallStatus === 'partial') {
        addNotification(
          '循环匹配部分成功',
          `完成 ${result.total_rounds} 轮匹配，成功 ${result.successful_matches} 个，失败 ${result.failed_matches} 个。${result.termination_reason}`
        );
      } else {
        addNotification(
          '循环匹配失败',
          `完成 ${result.total_rounds} 轮匹配，所有模板匹配均失败。${result.termination_reason}`
        );
      }

      // 如果当前在匹配记录选项卡，刷新数据
      if (activeTab === 'matching-results') {
        window.location.reload();
      }
    } catch (error) {
      console.error('一键匹配失败:', error);
      addNotification('一键匹配失败', `执行一键匹配时发生错误: ${error}`);
      setShowBatchMatchingProgressDialog(false);
    } finally {
      setBatchMatchingLoading(false);
      BatchMatchingService.clearProgressCallback();
    }
  };

  const handleCloseBatchMatchingDialog = () => {
    setShowBatchMatchingResultDialog(false);
    setBatchMatchingResult(null);
  };

  const handleCloseBatchMatchingProgressDialog = () => {
    setShowBatchMatchingProgressDialog(false);
    setBatchMatchingProgress(null);
  };

  const handleCancelBatchMatching = () => {
    // 取消匹配逻辑（如果需要的话）
    BatchMatchingService.clearProgressCallback();
    setShowBatchMatchingProgressDialog(false);
    setBatchMatchingLoading(false);
    setBatchMatchingProgress(null);
    addNotification('一键匹配已取消', '用户取消了一键匹配操作');
  };

  // 素材编辑处理函数
  const handleEditMaterial = (material: Material) => {
    setEditingMaterial(material);
    setShowMaterialEditDialog(true);
  };

  const handleMaterialSave = async (materialId: string, updates: Partial<Material>) => {
    try {
      // 调用后端API更新素材
      await invoke('update_material', { id: materialId, updates });

      // 重新加载素材列表
      if (project) {
        loadMaterials(project.id);
      }

      setShowMaterialEditDialog(false);
      setEditingMaterial(null);
    } catch (error) {
      console.error('更新素材失败:', error);
      throw error;
    }
  };

  // 素材删除处理函数
  const handleDeleteMaterial = async (materialId: string, _materialName: string) => {
    try {
      await deleteMaterial(materialId);

      // 重新加载素材列表
      if (project) {
        loadMaterials(project.id);
      }
    } catch (error) {
      console.error('删除素材失败:', error);
      throw error;
    }
  };

  // 批量删除处理函数
  const handleBatchDelete = async () => {
    if (batchSelection.selectedIds.length === 0) {
      addNotification('请先选择要删除的素材', 'warning');
      return;
    }

    setShowBatchDeleteDialog(true);
  };

  // 确认批量删除
  const handleConfirmBatchDelete = async () => {
    try {
      const result = await batchDeleteMaterials(batchSelection.selectedIds);
      setBatchDeleteResult(result);

      // 清空选择
      batchSelection.clearSelection();

      // 重新加载素材列表
      if (project) {
        loadMaterials(project.id);
      }

      // 显示通知
      if (result.failed_count === 0) {
        addNotification(`成功删除 ${result.success_count} 个素材`, 'success');
      } else {
        addNotification(
          `删除完成：成功 ${result.success_count} 个，失败 ${result.failed_count} 个`,
          'warning'
        );
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      addNotification('批量删除失败', 'error');
    }
  };

  // 关闭批量删除对话框
  const handleCloseBatchDeleteDialog = () => {
    setShowBatchDeleteDialog(false);
    setBatchDeleteResult(null);
  };

  // 素材重新处理函数
  const handleReprocessMaterial = async (materialId: string) => {
    try {
      await processMaterials([materialId]);

      // 重新加载素材列表
      if (project) {
        loadMaterials(project.id);
      }
    } catch (error) {
      console.error('重新处理素材失败:', error);
      throw error;
    }
  };

  // 重置项目使用状态函数
  const handleResetProjectUsage = async () => {
    if (!project) return;

    try {
      await resetProjectUsage(project.id);
      addNotification('项目素材使用状态已重置', 'success');

      // 重新加载使用状态数据
      loadUsageOverview(project.id);
    } catch (error) {
      console.error('重置项目使用状态失败:', error);
      addNotification('重置项目使用状态失败', 'error');
    }
  };

  // 素材筛选选项
  const materialClassificationOptions = useMemo(() => {
    const options = [{ label: '全部', value: '全部', count: materials.length }];

    // 统计分类信息
    const categoryCount: { [category: string]: number } = {};

    // 遍历所有素材的分类记录
    Object.values(materialClassificationRecords).forEach(records => {
      records.forEach(record => {
        if (record.category) {
          categoryCount[record.category] = (categoryCount[record.category] || 0) + 1;
        }
      });
    });

    // 添加分类选项
    Object.entries(categoryCount).forEach(([category, count]) => {
      options.push({
        label: category,
        value: category,
        count
      });
    });

    return options;
  }, [materials.length, materialClassificationRecords]);

  const materialModelOptions = useMemo(() => {
    const options = [{ label: '全部', value: '全部', count: materials.length }];

    // 统计模特信息
    const modelCounts: { [key: string]: number } = {};
    materials.forEach(material => {
      if (material.model_id) {
        const modelKey = material.model_id;
        modelCounts[modelKey] = (modelCounts[modelKey] || 0) + 1;
      } else {
        modelCounts['未指定'] = (modelCounts['未指定'] || 0) + 1;
      }
    });

    Object.entries(modelCounts).forEach(([modelKey, count]) => {
      let label = '未指定';
      if (modelKey !== '未指定') {
        // 从modelsMap中获取模特的真实名称
        const model = modelsMap[modelKey];
        if (model) {
          label = model.stage_name || model.name;
        } else {
          label = `模特-${modelKey}`;
        }
      }

      options.push({
        label,
        value: modelKey,
        count
      });
    });

    return options;
  }, [materials, modelsMap]);

  const materialUsageOptions = useMemo(() => {
    // 计算使用状态统计
    let usedCount = 0;
    let unusedCount = 0;

    materials.forEach(material => {
      const hasUsedSegments = material.segments.some(segment => segment.is_used);
      if (hasUsedSegments) {
        usedCount++;
      } else {
        unusedCount++;
      }
    });

    return [
      { label: '全部', value: '全部', count: materials.length },
      { label: '已使用', value: '已使用', count: usedCount },
      { label: '未使用', value: '未使用', count: unusedCount }
    ];
  }, [materials]);

  // 过滤后的素材列表
  const filteredMaterials = useMemo(() => {
    return materials.filter(material => {
      // AI分类过滤
      if (materialClassificationFilter !== '全部') {
        const materialRecords = materialClassificationRecords[material.id] || [];
        const hasMatchingClassification = materialRecords.some(record =>
          record.category === materialClassificationFilter
        );
        if (!hasMatchingClassification) return false;
      }

      // 模特过滤
      if (materialModelFilter !== '全部') {
        if (materialModelFilter === '未指定') {
          if (material.model_id) return false;
        } else {
          // 检查model_id是否匹配
          if (material.model_id !== materialModelFilter) return false;
        }
      }

      // 使用状态过滤
      if (materialUsageFilter !== '全部') {
        const hasUsedSegments = material.segments.some(segment => segment.is_used);
        if (materialUsageFilter === '已使用' && !hasUsedSegments) return false;
        if (materialUsageFilter === '未使用' && hasUsedSegments) return false;
      }

      return true;
    });
  }, [materials, materialClassificationFilter, materialModelFilter, materialUsageFilter, materialClassificationRecords]);

  // 计算选择状态
  const selectionState = useMemo(() => {
    const allIds = filteredMaterials.map(m => m.id);
    return calculateSelectionState(batchSelection.selectedIds, allIds);
  }, [batchSelection.selectedIds, filteredMaterials]);

  // 获取选中的素材列表
  const selectedMaterials = useMemo(() => {
    return filteredMaterials.filter(material => batchSelection.selectedIds.includes(material.id));
  }, [filteredMaterials, batchSelection.selectedIds]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <LoadingSpinner />
      </div>
    );
  }

  if (error) {
    return <ErrorMessage message={error} />;
  }

  if (!project) {
    return (
      <div className="text-center py-12">
        <h2 className="text-2xl font-bold text-gray-900 mb-4">项目未找到</h2>
        <p className="text-gray-600 mb-6">请检查项目ID是否正确</p>
        <button
          onClick={handleBack}
          className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          返回项目列表
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto">
      {/* 美观的页面头部 */}
      <div className="mb-6">
        {/* 面包屑导航 */}
        <div className="mb-4">
          <button
            onClick={handleBack}
            className="inline-flex items-center text-gray-500 hover:text-primary-600 transition-all duration-200 hover:scale-105"
          >
            <ArrowLeft className="w-4 h-4 mr-1.5" />
            <span className="text-sm font-medium">返回项目列表</span>
          </button>
        </div>

        {/* 项目标题和操作区 */}
        <div className="bg-gradient-to-r from-white via-primary-50/30 to-white rounded-2xl border border-gray-200/50 p-6 shadow-sm hover:shadow-md transition-all duration-300 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-primary-100/50 to-primary-200/50 rounded-full -translate-y-16 translate-x-16 opacity-50"></div>

          <div className="relative z-10">
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
              <div className="flex-1 min-w-0">
                <h1 className="text-2xl lg:text-3xl font-bold text-gray-900 mb-2 truncate">
                  {project.name}
                </h1>
                {project.description && (
                  <p className="text-gray-600 text-sm lg:text-base mb-3 line-clamp-2">
                    {project.description}
                  </p>
                )}
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <div className="flex items-center gap-1.5">
                    <Calendar className="w-4 h-4" />
                    <span>更新于 {formatTime(project.updated_at)}</span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <MapPin className="w-4 h-4" />
                    <span className="truncate max-w-xs" title={project.path}>
                      {getDirectoryName(project.path)}
                    </span>
                  </div>
                </div>
              </div>

              <div className="flex flex-wrap items-center gap-2">
                <button
                  onClick={handleOpenFolder}
                  className="inline-flex items-center px-4 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-all duration-200 hover:scale-105 text-sm font-medium"
                >
                  <FolderOpen className="w-4 h-4 mr-2" />
                  打开文件夹
                </button>

                <button
                  onClick={handleMaterialImport}
                  className="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-primary-600 to-primary-700 hover:from-primary-700 hover:to-primary-800 text-white rounded-lg transition-all duration-200 hover:scale-105 shadow-sm hover:shadow-md text-sm font-medium"
                >
                  <Upload className="w-4 h-4 mr-2" />
                  导入素材
                </button>

                <button
                  onClick={handleBatchClassification}
                  disabled={classificationLoading}
                  className="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-all duration-200 hover:scale-105 shadow-sm hover:shadow-md text-sm font-medium"
                >
                  {classificationLoading ? (
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  ) : (
                    <Brain className="w-4 h-4 mr-2" />
                  )}
                  {classificationLoading ? '分类中...' : '一键AI分类'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>



      {/* 主要内容区域 */}
      <div className="space-y-6">
        {/* 美观的选项卡导航 */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-200/50 overflow-hidden">
          <div className="border-b border-gray-100">
            <nav className="flex space-x-1 px-4 md:px-6 overflow-x-auto" aria-label="Tabs">
              <button
                onClick={() => setActiveTab('overview')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'overview'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <Brain className="w-4 h-4" />
                  <span className="hidden sm:inline">项目概述</span>
                  <span className="sm:hidden">概述</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('materials')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'materials'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <FolderOpen className="w-4 h-4" />
                  <span className="hidden sm:inline">素材管理</span>
                  <span className="sm:hidden">素材</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('segments')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'segments'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <Layers className="w-4 h-4" />
                  <span className="hidden sm:inline">片段管理</span>
                  <span className="sm:hidden">片段</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('templates')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'templates'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <Link className="w-4 h-4" />
                  <span className="hidden sm:inline">模板绑定</span>
                  <span className="sm:hidden">模板</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('matching-results')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'matching-results'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <Brain className="w-4 h-4" />
                  <span className="hidden sm:inline">匹配记录</span>
                  <span className="sm:hidden">匹配</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('export-records')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'export-records'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <Download className="w-4 h-4" />
                  <span className="hidden sm:inline">导出记录</span>
                  <span className="sm:hidden">导出</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('usage-stats')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'usage-stats'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span className="hidden sm:inline">使用状态</span>
                  <span className="sm:hidden">使用</span>
                </div>
              </button>
              <button
                onClick={() => setActiveTab('ai-logs')}
                className={`py-3 px-4 font-medium text-sm transition-all duration-200 whitespace-nowrap rounded-t-lg relative ${activeTab === 'ai-logs'
                    ? 'text-primary-600 border-b-2 border-primary-500'
                    : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center space-x-2">
                  <HardDrive className="w-4 h-4" />
                  <span className="hidden sm:inline">AI分析日志</span>
                  <span className="sm:hidden">AI日志</span>
                </div>
              </button>
            </nav>
          </div>

          {/* 选项卡内容 */}
          <div className="h-[calc(100vh-16rem)] overflow-y-auto custom-scrollbar">
            {/* 项目概述选项卡 */}
            {activeTab === 'overview' && (
              <div className="p-4 md:p-6 space-y-6">
                {/* 项目统计概览 */}
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-4">项目统计</h3>
                  <div className="grid grid-cols-2 md:grid-cols-5 gap-3 md:gap-4">
                    {/* 总素材数 */}
                    <div className="bg-gradient-to-br from-white to-primary-50/30 rounded-xl shadow-sm border border-gray-200/50 p-4 md:p-5 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-primary-100/50 to-primary-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
                      <div className="flex items-center justify-between relative z-10">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs md:text-sm font-medium text-gray-600 truncate">总素材数</p>
                          <p className="text-xl md:text-2xl font-bold text-gray-900">{stats?.total_materials || 0}</p>
                        </div>
                        <div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-primary-100 to-primary-200 rounded-xl flex items-center justify-center ml-2 shadow-sm">
                          <FolderOpen className="w-5 h-5 md:w-6 md:h-6 text-primary-600" />
                        </div>
                      </div>
                    </div>

                    {/* 视频文件 */}
                    <div className="bg-gradient-to-br from-white to-green-50/30 rounded-xl shadow-sm border border-gray-200/50 p-4 md:p-5 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-green-100/50 to-green-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
                      <div className="flex items-center justify-between relative z-10">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs md:text-sm font-medium text-gray-600 truncate">视频文件</p>
                          <p className="text-xl md:text-2xl font-bold text-gray-900">{stats?.video_count || 0}</p>
                        </div>
                        <div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-green-100 to-green-200 rounded-xl flex items-center justify-center ml-2 shadow-sm">
                          <FileVideo className="w-5 h-5 md:w-6 md:h-6 text-green-600" />
                        </div>
                      </div>
                    </div>

                    {/* 音频文件 */}
                    <div className="bg-gradient-to-br from-white to-purple-50/30 rounded-xl shadow-sm border border-gray-200/50 p-4 md:p-5 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-purple-100/50 to-purple-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
                      <div className="flex items-center justify-between relative z-10">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs md:text-sm font-medium text-gray-600 truncate">音频文件</p>
                          <p className="text-xl md:text-2xl font-bold text-gray-900">{stats?.audio_count || 0}</p>
                        </div>
                        <div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-purple-100 to-purple-200 rounded-xl flex items-center justify-center ml-2 shadow-sm">
                          <FileAudio className="w-5 h-5 md:w-6 md:h-6 text-purple-600" />
                        </div>
                      </div>
                    </div>

                    {/* 图片文件 */}
                    <div className="bg-gradient-to-br from-white to-orange-50/30 rounded-xl shadow-sm border border-gray-200/50 p-4 md:p-5 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-orange-100/50 to-orange-200/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
                      <div className="flex items-center justify-between relative z-10">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs md:text-sm font-medium text-gray-600 truncate">图片文件</p>
                          <p className="text-xl md:text-2xl font-bold text-gray-900">{stats?.image_count || 0}</p>
                        </div>
                        <div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-orange-100 to-orange-200 rounded-xl flex items-center justify-center ml-2 shadow-sm">
                          <FileImage className="w-5 h-5 md:w-6 md:h-6 text-orange-600" />
                        </div>
                      </div>
                    </div>

                    {/* AI分类状态 */}
                    <div className="bg-gradient-to-br from-white to-purple-50/30 rounded-xl shadow-sm border border-gray-200/50 p-4 md:p-5 hover:shadow-md transition-all duration-300 hover:-translate-y-1 relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-16 h-16 bg-gradient-to-br from-purple-100/50 to-pink-100/50 rounded-full -translate-y-8 translate-x-8 opacity-50"></div>
                      <div className="flex items-center justify-between relative z-10">
                        <div className="min-w-0 flex-1">
                          <p className="text-xs md:text-sm font-medium text-gray-600 truncate">AI分类队列</p>
                          <div className="flex items-center space-x-1">
                            <p className="text-xl md:text-2xl font-bold text-gray-900">
                              {queueStats?.pending_tasks || 0}
                            </p>
                            <span className="text-xs text-gray-500">待处理</span>
                          </div>
                          {queueStats?.processing_tasks && queueStats.processing_tasks > 0 && (
                            <p className="text-xs text-purple-600 mt-1 font-medium">
                              {queueStats.processing_tasks} 个正在处理
                            </p>
                          )}
                        </div>
                        <div className="w-10 h-10 md:w-12 md:h-12 bg-gradient-to-br from-purple-100 to-pink-100 rounded-xl flex items-center justify-center ml-2 shadow-sm">
                          <Brain className="w-5 h-5 md:w-6 md:h-6 text-purple-600" />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                {/* AI视频分类进度 */}
                {project && (
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">AI分析进度</h3>
                    <VideoClassificationProgress
                      projectId={project.id}
                      autoRefresh={true}
                      refreshInterval={3000}
                    />
                  </div>
                )}
                {/* 片段管理统计 */}
                {project && (
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-4">片段统计</h3>
                    <MaterialSegmentStats
                      stats={segmentStats}
                      viewMode={MaterialSegmentViewMode.ByClassification}
                    />
                  </div>
                )}


              </div>
            )}

            {/* 素材管理选项卡 */}
            {activeTab === 'materials' && (
              <div className="p-4 md:p-6 space-y-6">
                {/* 素材筛选条件 */}
                <div className="space-y-4 animate-fadeIn">
                  {/* AI分类筛选 */}
                  <div className="flex items-center gap-4 p-4 bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <Brain size={16} className="text-gray-600" />
                      <span className="text-sm font-medium text-gray-700">AI分类：</span>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {materialClassificationOptions.map(option => (
                        <button
                          key={option.value}
                          onClick={() => setMaterialClassificationFilter(option.value)}
                          className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium transition-all duration-200 hover:scale-105 ${materialClassificationFilter === option.value
                            ? 'bg-blue-100 text-blue-800 border border-blue-200 shadow-sm'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-200'
                            }`}
                        >
                          <span>{option.label}</span>
                          <span className="ml-1.5 px-1.5 py-0.5 bg-white rounded-full text-xs shadow-sm">
                            {option.count}
                          </span>
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* 模特筛选 */}
                  <div className="flex items-center gap-4 p-4 bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <Users size={16} className="text-gray-600" />
                      <span className="text-sm font-medium text-gray-700">模特：</span>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {materialModelOptions.map(option => (
                        <button
                          key={option.value}
                          onClick={() => setMaterialModelFilter(option.value)}
                          className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium transition-all duration-200 hover:scale-105 ${materialModelFilter === option.value
                            ? 'bg-green-100 text-green-800 border border-green-200 shadow-sm'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-200'
                            }`}
                        >
                          <span>{option.label}</span>
                          <span className="ml-1.5 px-1.5 py-0.5 bg-white rounded-full text-xs shadow-sm">
                            {option.count}
                          </span>
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* 使用状态筛选 */}
                  <div className="flex items-center gap-4 p-4 bg-white rounded-lg border border-gray-200 shadow-sm">
                    <div className="flex items-center gap-2 flex-shrink-0">
                      <CheckCircle size={16} className="text-gray-600" />
                      <span className="text-sm font-medium text-gray-700">是否使用：</span>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      {materialUsageOptions.map(option => (
                        <button
                          key={option.value}
                          onClick={() => setMaterialUsageFilter(option.value)}
                          className={`inline-flex items-center px-3 py-1.5 rounded-full text-sm font-medium transition-all duration-200 hover:scale-105 ${materialUsageFilter === option.value
                            ? 'bg-purple-100 text-purple-800 border border-purple-200 shadow-sm'
                            : 'bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-200'
                            }`}
                        >
                          <span>{option.label}</span>
                          <span className="ml-1.5 px-1.5 py-0.5 bg-white rounded-full text-xs shadow-sm">
                            {option.count}
                          </span>
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* 当前筛选条件显示 */}
                  {(materialClassificationFilter !== '全部' || materialModelFilter !== '全部' || materialUsageFilter !== '全部') && (
                    <div className="flex items-center gap-2 p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border border-blue-200 shadow-sm animate-slideIn">
                      <Filter size={16} className="text-blue-600" />
                      <span className="text-sm font-medium text-gray-700">当前筛选：</span>
                      {materialClassificationFilter !== '全部' && (
                        <span className="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full">
                          AI分类: {materialClassificationFilter}
                        </span>
                      )}
                      {((materialClassificationFilter !== '全部') && (materialModelFilter !== '全部')) && (
                        <span className="text-xs text-gray-500">AND</span>
                      )}
                      {materialModelFilter !== '全部' && (
                        <span className="inline-flex items-center px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full">
                          模特: {materialModelFilter}
                        </span>
                      )}
                      {((materialClassificationFilter !== '全部' || materialModelFilter !== '全部') && materialUsageFilter !== '全部') && (
                        <span className="text-xs text-gray-500">AND</span>
                      )}
                      {materialUsageFilter !== '全部' && (
                        <span className="inline-flex items-center px-2 py-1 bg-purple-100 text-purple-800 text-xs rounded-full">
                          使用状态: {materialUsageFilter}
                        </span>
                      )}
                      <button
                        onClick={() => {
                          setMaterialClassificationFilter('全部');
                          setMaterialModelFilter('全部');
                          setMaterialUsageFilter('全部');
                        }}
                        className="ml-auto inline-flex items-center px-3 py-1.5 text-xs font-medium text-gray-600 bg-white border border-gray-300 rounded-full hover:bg-gray-50 hover:text-gray-700 transition-all duration-200 hover:scale-105 shadow-sm"
                      >
                        <Filter size={12} className="mr-1" />
                        清除筛选
                      </button>
                    </div>
                  )}
                </div>

                {/* 素材列表 */}
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-4">
                      <h3 className="text-lg font-medium text-gray-900">项目素材</h3>

                      {/* 批量选择控制 */}
                      {filteredMaterials.length > 0 && (
                        <div className="flex items-center gap-2">
                          <button
                            onClick={batchSelection.toggleSelectionMode}
                            className={`inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-lg transition-colors ${
                              batchSelection.isSelectionMode
                                ? 'bg-blue-100 text-blue-700 hover:bg-blue-200'
                                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                            }`}
                          >
                            {batchSelection.isSelectionMode ? (
                              <>
                                <CheckSquare className="w-4 h-4 mr-1" />
                                退出选择
                              </>
                            ) : (
                              <>
                                <Square className="w-4 h-4 mr-1" />
                                批量选择
                              </>
                            )}
                          </button>

                          {/* 批量选择模式下的控制按钮 */}
                          {batchSelection.isSelectionMode && (
                            <>
                              <button
                                onClick={() => batchSelection.toggleAll(filteredMaterials.map(m => m.id))}
                                className="inline-flex items-center px-3 py-1.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
                              >
                                {selectionState.isAllSelected ? (
                                  <>
                                    <MinusSquare className="w-4 h-4 mr-1" />
                                    取消全选
                                  </>
                                ) : (
                                  <>
                                    <CheckSquare className="w-4 h-4 mr-1" />
                                    全选
                                  </>
                                )}
                              </button>

                              {batchSelection.selectedCount > 0 && (
                                <span className="text-sm text-gray-600">
                                  已选择 {batchSelection.selectedCount} 个素材
                                </span>
                              )}
                            </>
                          )}
                        </div>
                      )}
                    </div>

                    <div className="flex items-center gap-2">
                      {/* 批量删除按钮 */}
                      {batchSelection.isSelectionMode && batchSelection.selectedCount > 0 && (
                        <button
                          onClick={handleBatchDelete}
                          disabled={isBatchDeleting}
                          className="inline-flex items-center px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                          <Trash2 className="w-4 h-4 mr-2" />
                          删除选中 ({batchSelection.selectedCount})
                        </button>
                      )}

                      <button
                        onClick={() => setShowImportDialog(true)}
                        className="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        <Upload className="w-4 h-4 mr-2" />
                        导入素材
                      </button>
                    </div>
                  </div>

                  {materialsLoading ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3 md:gap-4">
                      <MaterialCardSkeleton count={8} />
                    </div>
                  ) : filteredMaterials.length > 0 ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-3 md:gap-4">
                      {filteredMaterials.map((material) => (
                        <MaterialCard
                          key={material.id}
                          material={material}
                          onEdit={handleEditMaterial}
                          onDelete={handleDeleteMaterial}
                          onReprocess={handleReprocessMaterial}
                          onUsageReset={() => project && loadUsageOverview(project.id)}
                          isSelectionMode={batchSelection.isSelectionMode}
                          isSelected={batchSelection.isSelected(material.id)}
                          onToggleSelection={batchSelection.toggleItem}
                        />
                      ))}
                    </div>
                  ) : materials.length > 0 ? (
                    <div className="text-center py-16">
                      <div className="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                        <Filter className="w-10 h-10 text-gray-400" />
                      </div>
                      <h4 className="text-xl font-medium text-gray-900 mb-2">没有找到匹配的素材</h4>
                      <p className="text-gray-500 mb-6 max-w-sm mx-auto">
                        尝试调整筛选条件或清除所有筛选来查看更多素材
                      </p>
                      <button
                        onClick={() => {
                          setMaterialClassificationFilter('全部');
                          setMaterialModelFilter('全部');
                          setMaterialUsageFilter('全部');
                        }}
                        className="inline-flex items-center px-6 py-3 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        <Filter className="w-5 h-5 mr-2" />
                        清除所有筛选
                      </button>
                    </div>
                  ) : (
                    <div className="text-center py-16">
                      <div className="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                        <FolderOpen className="w-10 h-10 text-gray-400" />
                      </div>
                      <h4 className="text-xl font-medium text-gray-900 mb-2">暂无素材</h4>
                      <p className="text-gray-500 mb-6 max-w-sm mx-auto">
                        开始导入视频、音频或图片素材，让AI帮助您进行智能分类和管理
                      </p>
                      <button
                        onClick={() => setShowImportDialog(true)}
                        className="inline-flex items-center px-6 py-3 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                      >
                        <Upload className="w-5 h-5 mr-2" />
                        导入第一个素材
                      </button>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* 片段管理选项卡 */}
            {activeTab === 'segments' && project && (
              <div className="p-4 md:p-6">
                <MaterialSegmentView projectId={project.id} />
              </div>
            )}

            {/* 模板绑定选项卡 */}
            {activeTab === 'templates' && project && (
              <div className="p-4 md:p-6 space-y-6">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-lg font-medium text-gray-900">模板绑定管理</h3>
                    <p className="text-sm text-gray-600 mt-1">
                      管理项目与模板的绑定关系，设置主要模板和备用模板。
                    </p>
                  </div>
                  <div className="flex items-center space-x-3">
                    <button
                      onClick={handleBatchMatching}
                      disabled={batchMatchingLoading || filteredBindingDetails.length === 0}
                      className="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg transition-all duration-200 hover:scale-105 shadow-sm hover:shadow-md text-sm font-medium"
                    >
                      {batchMatchingLoading ? (
                        <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      ) : (
                        <Shuffle className="w-4 h-4 mr-2" />
                      )}
                      {batchMatchingLoading ? '匹配中...' : '一键匹配'}
                    </button>
                  </div>
                </div>

                {bindingError && (
                  <ErrorMessage message={bindingError} />
                )}

                <ProjectTemplateBindingList
                  bindings={filteredBindingDetails}
                  loading={bindingLoading}
                  selectedIds={selectedBindingIds}
                  onSelectionChange={bindingActions.setSelectedBindingIds}
                  onAdd={handleAddBinding}
                  onEdit={handleEditBinding}
                  onDelete={handleDeleteBinding}
                  onBatchDelete={async (ids) => {
                    await bindingActions.batchDeleteBindings(ids);
                    // 删除成功后重新获取项目的模板绑定列表
                    if (project) {
                      await bindingActions.fetchTemplatesByProject(project.id);
                    }
                  }}
                  onToggleStatus={handleToggleBindingStatus}
                  onSetPrimary={handleSetPrimaryTemplate}
                  onMatchMaterials={handleMatchMaterials}
                  searchQuery={bindingFilters.search || ''}
                  onSearchChange={(query) => bindingActions.setFilters({ search: query })}
                  typeFilter={bindingFilters.binding_type || ''}
                  onTypeFilterChange={(type) => bindingActions.setFilters({ binding_type: type || undefined })}
                  statusFilter={bindingFilters.binding_status || ''}
                  onStatusFilterChange={(status) => bindingActions.setFilters({ binding_status: status || undefined })}
                  activeFilter={bindingFilters.is_active ?? null}
                  onActiveFilterChange={(active) => bindingActions.setFilters({ is_active: active ?? undefined })}
                />
              </div>
            )}

            {/* 匹配记录选项卡 */}
            {activeTab === 'matching-results' && project && (
              <div className="p-4 md:p-6 space-y-6">
                <div className="mb-4">
                  <h3 className="text-lg font-medium text-gray-900 mb-2">模板匹配记录</h3>
                  <p className="text-sm text-gray-600">
                    查看项目中所有模板匹配的结果记录，包括匹配统计和详细信息。
                  </p>
                </div>
                <TemplateMatchingResultManager
                  projectId={project.id}
                  showStats={false}
                />
              </div>
            )}

            {/* 导出记录选项卡 */}
            {activeTab === 'export-records' && project && (
              <div className="p-4 md:p-6 space-y-6">
                <div className="mb-4">
                  <h3 className="text-lg font-medium text-gray-900 mb-2">导出记录</h3>
                  <p className="text-sm text-gray-600">
                    查看项目中所有导出操作的记录，包括导出状态、文件信息和统计数据。
                  </p>
                </div>
                <ExportRecordManager
                  projectId={project.id}
                  showHeader={false}
                  compact={true}
                />
              </div>
            )}

            {/* 素材使用状态选项卡 */}
            {activeTab === 'usage-stats' && project && (
              <div className="p-4 md:p-6 space-y-6">
                <div className="mb-4">
                  <h3 className="text-lg font-medium text-gray-900 mb-2">素材使用状态</h3>
                  <p className="text-sm text-gray-600">
                    查看项目中素材的使用情况，包括使用统计、使用历史和状态管理。
                  </p>
                </div>

                {usageError && (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="flex">
                      <div className="flex-shrink-0">
                        <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                          <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                        </svg>
                      </div>
                      <div className="ml-3">
                        <h3 className="text-sm font-medium text-red-800">加载使用状态失败</h3>
                        <div className="mt-2 text-sm text-red-700">
                          <p>{usageError}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {usageOverview ? (
                  <ProjectMaterialUsageOverviewComponent
                    overview={usageOverview}
                    onRefresh={() => loadUsageOverview(project.id)}
                    onResetAll={() => handleResetProjectUsage()}
                    isLoading={usageLoading}
                  />
                ) : (
                  <div className="text-center py-16">
                    <div className="w-20 h-20 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center">
                      <svg className="w-10 h-10 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                    <h4 className="text-xl font-medium text-gray-900 mb-2">暂无使用数据</h4>
                    <p className="text-gray-500 mb-6 max-w-sm mx-auto">
                      开始进行模板匹配并应用结果，系统将自动记录素材使用状态
                    </p>
                    <button
                      onClick={() => setActiveTab('templates')}
                      className="inline-flex items-center px-6 py-3 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      前往模板绑定
                    </button>
                  </div>
                )}
              </div>
            )}

            {/* AI分析日志选项卡 */}
            {activeTab === 'ai-logs' && project && (
              <div className="p-4 md:p-6 space-y-6">
                <div className="mb-4">
                  <h3 className="text-lg font-medium text-gray-900 mb-2">AI分析日志</h3>
                  <p className="text-sm text-gray-600">
                    查看项目中所有AI视频分类的详细日志，包括分类记录和任务执行情况。
                  </p>
                </div>
                <AiAnalysisLogViewer projectId={project.id} />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 素材导入对话框 */}
      {project && (
        <MaterialImportDialog
          isOpen={showImportDialog}
          projectId={project.id}
          onClose={() => setShowImportDialog(false)}
          onImportComplete={handleImportComplete}
        />
      )}

      {/* 模板绑定表单对话框 */}
      {project && (
        <ProjectTemplateBindingForm
          isOpen={showBindingForm}
          onClose={() => {
            setShowBindingForm(false);
            setEditingBinding(null);
          }}
          onSubmit={handleBindingFormSubmit}
          projectId={project.id}
          templates={templates}
          binding={editingBinding?.binding}
          loading={bindingLoading}
          error={bindingError}
        />
      )}

      {/* 素材编辑对话框 */}
      <MaterialEditDialog
        isOpen={showMaterialEditDialog}
        onClose={() => {
          setShowMaterialEditDialog(false);
          setEditingMaterial(null);
        }}
        material={editingMaterial}
        onSave={handleMaterialSave}
      />

      {/* 素材匹配结果对话框 */}
      <MaterialMatchingResultDialog
        isOpen={showMatchingResultDialog}
        onClose={handleCloseMatchingDialog}
        result={matchingResult}
        loading={matchingLoading}
        onApplyResult={handleApplyMatchingResult}
        onRetryMatching={handleRetryMatching}
      />

      {/* 一键匹配结果对话框 */}
      <BatchMatchingResultDialog
        isOpen={showBatchMatchingResultDialog}
        onClose={handleCloseBatchMatchingDialog}
        result={batchMatchingResult}
        loading={batchMatchingLoading}
      />

      {/* 一键匹配进度对话框 */}
      <BatchMatchingProgressDialog
        isOpen={showBatchMatchingProgressDialog}
        onClose={handleCloseBatchMatchingProgressDialog}
        onCancel={handleCancelBatchMatching}
        progress={batchMatchingProgress}
        canCancel={batchMatchingLoading}
      />

      {/* 批量删除确认对话框 */}
      <BatchDeleteConfirmDialog
        isOpen={showBatchDeleteDialog}
        materials={selectedMaterials}
        deleting={isBatchDeleting}
        deleteResult={batchDeleteResult}
        onConfirm={handleConfirmBatchDelete}
        onCancel={handleCloseBatchDeleteDialog}
        onCloseResult={handleCloseBatchDeleteDialog}
      />
    </div>
  );
};
