import React, { useState, useEffect } from 'react'
import { Video, Play, Search, Filter, Tag, Clock, HardDrive, Eye, User, Folder, Upload } from 'lucide-react'
import { Project } from '../services/projectService'
import { VideoSegment, MediaService } from '../services/mediaService'
import { Model } from '../services/modelService'
import { ResourceCategory, ResourceCategoryService } from '../services/resourceCategoryService'
import { BatchUploadResult } from '../services/mediaService'
import VideoPlayer from './VideoPlayer'
import ImportMaterialModal from './ImportMaterialModal'
import { VideoPlayer2 } from './VideoPlayer2'

interface ProjectMaterialsCenterProps {
  project: Project
  materials: VideoSegment[]
  models: Model[]
  onMaterialsChange: (materials: VideoSegment[]) => void
  onRefreshMaterials?: () => void
}

const ProjectMaterialsCenter: React.FC<ProjectMaterialsCenterProps> = ({
  project,
  materials,
  models,
  onMaterialsChange,
  onRefreshMaterials
}) => {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedModelIds, setSelectedModelIds] = useState<string[]>([])
  const [filterType, setFilterType] = useState<'all' | '分镜' | '原始'>('all')
  const [usageFilter, setUsageFilter] = useState<'all' | 'used' | 'unused'>('all')
  const [selectedMaterial, setSelectedMaterial] = useState<VideoSegment | null>(null)
  const [showVideoPlayer, setShowVideoPlayer] = useState(false)
  const [showImportModal, setShowImportModal] = useState(false)

  // 素材分类相关状态
  const [categories, setCategories] = useState<ResourceCategory[]>([])
  const [selectedCategoryId, setSelectedCategoryId] = useState<string>('')
  const [loadingCategories, setLoadingCategories] = useState(false)

  // 加载分类数据
  useEffect(() => {
    loadCategories()
  }, [])

  const loadCategories = async () => {
    setLoadingCategories(true)
    try {
      const response = await ResourceCategoryService.getAllCategories()
      if (response.status && response.data) {
        setCategories(response.data.filter(cat => cat.is_active))
      }
    } catch (error) {
      console.error('Failed to load categories:', error)
    } finally {
      setLoadingCategories(false)
    }
  }

  // 计算每个分类的素材数量
  const getCategoryMaterialCount = (categoryId: string): number => {
    if (!categoryId) return materials.length // 全部分类

    const category = categories.find(cat => cat.id === categoryId)
    if (!category) return 0

    return materials.filter(material => {
      const categoryTitle = category.title.toLowerCase()
      const materialTags = (material.tags || []).map(tag => tag.toLowerCase())
      const filename = material.filename.toLowerCase()

      return materialTags.includes(categoryTitle) ||
             materialTags.some(tag => tag.includes(categoryTitle)) ||
             filename.includes(categoryTitle) ||
             Boolean(category.ai_prompt &&
              category.ai_prompt.toLowerCase().split(/[,，、\s]+/)
                .some(keyword => keyword.length > 1 &&
                  (materialTags.includes(keyword) || filename.includes(keyword))))
    }).length
  }

  // 过滤素材
  const filteredMaterials = materials.filter(material => {
    // 搜索过滤
    const matchesSearch = material.filename.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (material.tags || []).some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))

    // 模特过滤（如果选择了模特）
    const matchesModel = selectedModelIds.length === 0 ||
                        selectedModelIds.some(modelId => {
                          const model = models.find(m => m.id === modelId)
                          return model && (material.tags || []).includes(model.model_number)
                        })

    // 类型过滤
    let matchesType = filterType === 'all' ? true : material.tags.includes(filterType)

    // 使用状态过滤
    let matchesUsage = true
    if (usageFilter === 'used') {
      matchesUsage = material.use_count > 0
    } else if (usageFilter === 'unused') {
      matchesUsage = material.use_count === 0
    }

    // 分类过滤
    let matchesCategory = true
    if (selectedCategoryId) {
      const category = categories.find(cat => cat.id === selectedCategoryId)
      if (category) {
        // 检查素材标签是否包含分类标题，或者文件名是否包含分类相关关键词
        const categoryTitle = category.title.toLowerCase()
        const materialTags = (material.tags || []).map(tag => tag.toLowerCase())
        const filename = material.filename.toLowerCase()

        matchesCategory = materialTags.includes(categoryTitle) ||
                         materialTags.some(tag => tag.includes(categoryTitle)) ||
                         filename.includes(categoryTitle) ||
                         // 检查AI提示中的关键词
                         Boolean(category.ai_prompt &&
                          category.ai_prompt.toLowerCase().split(/[,，、\s]+/)
                            .some(keyword => keyword.length > 1 &&
                              (materialTags.includes(keyword) || filename.includes(keyword))))
      }
    }

    return matchesSearch && matchesModel && matchesType && matchesUsage && matchesCategory
  })

  const handleModelToggle = (modelId: string) => {
    setSelectedModelIds(prev => {
      // 如果当前模特已选中，则取消选择
      if (prev.includes(modelId)) {
        return prev.filter(id => id !== modelId)
      }
      // 如果当前模特未选中，则添加到选择列表
      return [...prev, modelId]
    })
  }

  const handleUseMaterial = async (material: VideoSegment) => {
    try {
      await MediaService.incrementSegmentUsage(material.id)
      const updatedMaterials = materials.map(m => 
        m.id === material.id ? { ...m, use_count: m.use_count + 1 } : m
      )
      onMaterialsChange(updatedMaterials)
    } catch (error) {
      console.error('Failed to use material:', error)
    }
  }

  const handlePlayMaterial = (material: VideoSegment) => {
    setSelectedMaterial(material)
    setShowVideoPlayer(true)
  }

  // 处理导入完成
  const handleImportComplete = async (result: BatchUploadResult) => {
    setShowImportModal(false)

    console.log('导入完成，结果:', result)
    console.log('项目信息:', project)

    // 显示导入结果
    const message = `导入完成！\n成功: ${result.uploaded_files} 个文件\n生成片段: ${result.total_segments} 个`
    alert(message)

    // 重新加载项目素材
    if (onRefreshMaterials) {
      onRefreshMaterials()
    } else {
      // 如果没有刷新回调，则刷新页面
      window.location.reload()
    }
  }

  const formatDuration = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  }

  const formatFileSize = (bytes: number) => {
    const sizes = ['B', 'KB', 'MB', 'GB']
    if (bytes === 0) return '0 B'
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-lg shadow-sm border border-gray-200">
      {/* 顶部搜索栏 */}
      <div className="p-4 border-b border-gray-200 bg-gray-50">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
          <input
            type="text"
            placeholder="搜索素材名称或标签..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 pr-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent w-full text-sm"
          />
        </div>
      </div>

      {/* 筛选和标题区域 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold text-gray-900">项目素材</h2>
          <div className="flex items-center space-x-3">
            <div className="text-sm text-gray-600">
              {filteredMaterials.length} / {materials.length} 个素材
            </div>
            <button
              onClick={() => setShowImportModal(true)}
              className="flex items-center px-3 py-1.5 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Upload size={14} className="mr-1" />
              导入素材
            </button>
          </div>
        </div>

        {/* 筛选器 - 紧凑布局 */}
        <div className="space-y-3">
          {/* 使用状态筛选 */}
          <div className="flex items-center space-x-3">
            <div className="flex items-center">
              <Tag size={14} className="text-gray-400 mr-1" />
              <span className="text-xs font-medium text-gray-700">使用状态:</span>
            </div>
            <div className="flex space-x-1.5">
              {[
                { value: 'all', label: '全部' },
                { value: 'unused', label: '未使用' },
                { value: 'used', label: '已使用' }
              ].map((option) => (
                <button
                  key={option.value}
                  onClick={() => setUsageFilter(option.value as any)}
                  className={`px-2 py-1 text-xs rounded transition-colors ${
                    usageFilter === option.value
                      ? 'bg-green-100 text-green-700'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>

          {/* 模特筛选 */}
          {models.length > 0 && (
            <div className="flex items-center space-x-3">
              <div className="flex items-center">
                <User size={14} className="text-gray-400 mr-1" />
                <span className="text-xs font-medium text-gray-700">模特:</span>
              </div>
              <div className="flex flex-wrap gap-1.5">
                <button
                  onClick={() => setSelectedModelIds([])}
                  className={`px-2 py-1 text-xs rounded transition-colors ${
                    selectedModelIds.length === 0
                      ? 'bg-blue-100 text-blue-700'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  全部
                </button>
                {models.map((model) => (
                  <button
                    key={model.id}
                    onClick={() => handleModelToggle(model.id)}
                    className={`px-2 py-1 text-xs rounded transition-colors ${
                      selectedModelIds.includes(model.id)
                        ? 'bg-blue-100 text-blue-700'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    {model.model_number}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* 类型过滤 */}
          <div className="flex items-center space-x-3">
            <div className="flex items-center">
              <Filter size={14} className="text-gray-400 mr-1" />
              <span className="text-xs font-medium text-gray-700">类型:</span>
            </div>
            <div className="flex space-x-1.5">
              {[
                { value: 'all', label: '全部' },
                { value: '原始', label: '原始' },
                { value: '分镜', label: '分镜' }
              ].map((option) => (
                <button
                  key={option.value}
                  onClick={() => setFilterType(option.value as any)}
                  className={`px-2 py-1 text-xs rounded transition-colors ${
                    filterType === option.value
                      ? 'bg-blue-100 text-blue-700'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  {option.label}
                </button>
              ))}
            </div>
          </div>

          {/* 素材分类过滤 */}
          <div className="flex items-center space-x-3">
            <div className="flex items-center">
              <Folder size={14} className="text-gray-400 mr-1" />
              <span className="text-xs font-medium text-gray-700">分类:</span>
            </div>
            <div className="flex flex-wrap gap-1.5">
              <button
                onClick={() => setSelectedCategoryId('')}
                className={`px-2 py-1 text-xs rounded transition-colors ${
                  selectedCategoryId === ''
                    ? 'bg-blue-100 text-blue-700'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                全部 ({getCategoryMaterialCount('')})
              </button>
              {loadingCategories ? (
                <div className="px-2 py-1 text-xs text-gray-500">加载中...</div>
              ) : (
                categories.map((category) => {
                  const count = getCategoryMaterialCount(category.id)
                  return (
                    <button
                      key={category.id}
                      onClick={() => setSelectedCategoryId(category.id)}
                      className={`px-2 py-1 text-xs rounded transition-colors ${
                        selectedCategoryId === category.id
                          ? 'bg-blue-100 text-blue-700'
                          : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                      }`}
                      style={{
                        backgroundColor: selectedCategoryId === category.id
                          ? undefined
                          : `${category.color}20`,
                        borderColor: category.color,
                        borderWidth: '1px'
                      }}
                    >
                      {category.title} ({count})
                    </button>
                  )
                })
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 素材网格 */}
      <div className="flex-1 overflow-y-auto p-4">
        {filteredMaterials.length === 0 ? (
          <div className="text-center py-8">
            <Video className="mx-auto text-gray-400 mb-3" size={48} />
            <h3 className="text-base font-medium text-gray-900 mb-1">
              {searchTerm || selectedModelIds.length > 0 || filterType !== 'all' || usageFilter !== 'all' || selectedCategoryId
                ? '没有找到匹配的素材'
                : '暂无项目素材'
              }
            </h3>
            <p className="text-sm text-gray-600">
              {searchTerm || selectedModelIds.length > 0 || filterType !== 'all' || usageFilter !== 'all' || selectedCategoryId
                ? '尝试调整搜索条件或筛选器'
                : `上传包含"${project.product_name}"标签的视频素材`
              }
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 gap-4">
            {filteredMaterials.map((material) => (
              <div key={material.id} className="bg-gray-50 rounded-lg overflow-hidden hover:shadow-md transition-shadow border border-gray-200">
                {/* 视频缩略图 */}
                <div className="relative h-32 bg-gray-100">
                  {material.thumbnail_path ? (
                    <img
                      src={material.thumbnail_path}
                      alt={material.filename}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <VideoPlayer2 src={material.file_path} />
                    </div>
                  )}

                  {/* 播放按钮 */}
                  <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-30 transition-all flex items-center justify-center">
                    <button
                      onClick={() => handlePlayMaterial(material)}
                      className="p-2 bg-white/80 rounded-full hover:bg-white transition-colors opacity-0 hover:opacity-100"
                    >
                      <Play size={20} className="text-gray-800" />
                    </button>
                  </div>

                  {/* 类型标识 */}
                  <div className="absolute top-1.5 left-1.5">
                    <span className={`px-1.5 py-0.5 text-xs rounded`}>
                      {material.tags.join(' ')}
                    </span>
                  </div>

                  {/* 使用次数 */}
                  <div className="absolute top-1.5 right-1.5">
                    <span className="px-1.5 py-0.5 text-xs bg-black/60 text-white rounded">
                      {material.use_count}次
                    </span>
                  </div>
                </div>

                {/* 素材信息 */}
                <div className="p-3">
                  <h4 className="font-medium text-gray-900 mb-1.5 truncate text-sm" title={material.filename}>
                    {material.filename}
                  </h4>

                  {/* 基本信息 */}
                  <div className="flex items-center text-xs text-gray-600 mb-2">
                    <Clock size={12} className="mr-1" />
                    <span>{formatDuration(material.duration)}</span>
                    <span className="mx-1.5">•</span>
                    <HardDrive size={12} className="mr-1" />
                    <span>{formatFileSize(material.file_size)}</span>
                  </div>

                  {/* 标签 */}
                  <div className="flex flex-wrap gap-1 mb-2">
                    {(material.tags || []).slice(0, 2).map((tag, index) => (
                      <span
                        key={index}
                        className={`inline-flex items-center px-1.5 py-0.5 text-xs rounded ${
                          tag === project.product_name
                            ? 'bg-blue-100 text-blue-800'
                            : 'bg-gray-100 text-gray-700'
                        }`}
                      >
                        <Tag size={8} className="mr-0.5" />
                        {tag}
                      </span>
                    ))}
                    {(material.tags || []).length > 2 && (
                      <span className="text-xs text-gray-500">+{(material.tags || []).length - 2}</span>
                    )}
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex items-center justify-between gap-2">
                    <button
                      onClick={() => handlePlayMaterial(material)}
                      className="flex items-center px-2 py-1 text-xs text-blue-600 hover:text-blue-700 transition-colors"
                    >
                      <Eye size={12} className="mr-1" />
                      预览
                    </button>
                    <button
                      onClick={() => handleUseMaterial(material)}
                      className="px-3 py-1.5 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
                    >
                      使用
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* 视频播放器 */}
      {selectedMaterial && (
        <VideoPlayer
          videoPath={selectedMaterial.file_path}
          isOpen={showVideoPlayer}
          onClose={() => {
            setShowVideoPlayer(false)
            setSelectedMaterial(null)
          }}
          title={`${selectedMaterial.filename} - ${
            selectedMaterial.segment_index === 0 ? '原始素材' : `片段 ${selectedMaterial.segment_index}`
          }`}
        />
      )}

      {/* 导入素材模态框 */}
      {showImportModal && (
        <ImportMaterialModal
          project={project}
          models={models}
          onConfirm={handleImportComplete}
          onCancel={() => setShowImportModal(false)}
        />
      )}
    </div>
  )
}

export default ProjectMaterialsCenter
