import React, { useState } from 'react'
import { Video, Play, Filter, Search, Tag, Clock, HardDrive, Eye } from 'lucide-react'
import { Project } from '../services/projectService'
import { VideoSegment, MediaService } from '../services/mediaService'
import VideoPlayer from './VideoPlayer'

interface ProjectMaterialsProps {
  project: Project
  materials: VideoSegment[]
  onMaterialsChange: (materials: VideoSegment[]) => void
}

const ProjectMaterials: React.FC<ProjectMaterialsProps> = ({
  project,
  materials,
  onMaterialsChange
}) => {
  const [searchTerm, setSearchTerm] = useState('')
  const [filterType, setFilterType] = useState<'all' | 'original' | 'segmented'>('all')
  const [selectedMaterial, setSelectedMaterial] = useState<VideoSegment | null>(null)
  const [showVideoPlayer, setShowVideoPlayer] = useState(false)

  // 过滤素材
  const filteredMaterials = materials.filter(material => {
    // 搜索过滤
    const matchesSearch = material.filename.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         (material.tags || []).some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
    
    // 类型过滤
    let matchesType = true
    if (filterType === 'original') {
      // 原始素材：segment_index为0或者是原始视频
      matchesType = material.segment_index === 0
    } else if (filterType === 'segmented') {
      // 已分镜头素材：segment_index大于0
      matchesType = material.segment_index > 0
    }
    
    return matchesSearch && matchesType
  })

  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 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="space-y-6">
      {/* 头部操作 */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
        <div>
          <h3 className="text-lg font-medium text-gray-900">项目素材</h3>
          <p className="text-sm text-gray-600">
            包含商品标签"{project.product_name}"且未使用的素材
          </p>
        </div>

        <div className="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-4">
          {/* 搜索框 */}
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={16} />
            <input
              type="text"
              placeholder="搜索素材..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
            />
          </div>

          {/* 类型过滤 */}
          <select
            value={filterType}
            onChange={(e) => setFilterType(e.target.value as any)}
            className="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
          >
            <option value="all">全部素材</option>
            <option value="original">原始素材</option>
            <option value="segmented">已分镜头</option>
          </select>
        </div>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="bg-blue-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-blue-600">{materials.length}</div>
          <div className="text-sm text-blue-600">总素材数</div>
        </div>
        <div className="bg-green-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-green-600">
            {materials.filter(m => m.segment_index === 0).length}
          </div>
          <div className="text-sm text-green-600">原始素材</div>
        </div>
        <div className="bg-purple-50 rounded-lg p-4">
          <div className="text-2xl font-bold text-purple-600">
            {materials.filter(m => m.segment_index > 0).length}
          </div>
          <div className="text-sm text-purple-600">已分镜头</div>
        </div>
      </div>

      {/* 素材列表 */}
      {filteredMaterials.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <Video className="mx-auto text-gray-400 mb-4" size={48} />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            {searchTerm || filterType !== 'all' ? '没有找到匹配的素材' : '暂无项目素材'}
          </h3>
          <p className="text-gray-600">
            {searchTerm || filterType !== 'all' 
              ? '尝试调整搜索条件或过滤器' 
              : `上传包含"${project.product_name}"标签的视频素材`
            }
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredMaterials.map((material) => (
            <div key={material.id} className="bg-white border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow">
              {/* 视频缩略图 */}
              <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">
                    <Video size={32} className="text-gray-400" />
                  </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"
                    title="播放视频"
                  >
                    <Play size={20} className="text-gray-800" />
                  </button>
                </div>

                {/* 素材类型标识 */}
                <div className="absolute top-2 left-2">
                  <span className={`px-2 py-1 text-xs rounded-full ${
                    material.segment_index === 0 
                      ? 'bg-green-100 text-green-800' 
                      : 'bg-purple-100 text-purple-800'
                  }`}>
                    {material.segment_index === 0 ? '原始' : `片段${material.segment_index}`}
                  </span>
                </div>
              </div>

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

                {/* 基本信息 */}
                <div className="space-y-1 text-sm text-gray-600 mb-3">
                  <div className="flex items-center">
                    <Clock size={14} className="mr-1" />
                    <span>{formatDuration(material.duration)}</span>
                    <span className="mx-2">•</span>
                    <span>{material.width}×{material.height}</span>
                  </div>
                  <div className="flex items-center">
                    <HardDrive size={14} className="mr-1" />
                    <span>{formatFileSize(material.file_size)}</span>
                    <span className="mx-2">•</span>
                    <span>{material.fps} fps</span>
                  </div>
                </div>

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

                {/* 操作按钮 */}
                <div className="flex items-center justify-between">
                  <div className="text-xs text-gray-500">
                    使用次数: {material.use_count}
                  </div>
                  <div className="flex space-x-2">
                    <button
                      onClick={() => handlePlayMaterial(material)}
                      className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
                      title="预览"
                    >
                      <Eye size={16} />
                    </button>
                    <button
                      onClick={() => handleUseMaterial(material)}
                      className="px-3 py-1 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}`
          }`}
        />
      )}
    </div>
  )
}

export default ProjectMaterials
