import React, { useState } from 'react'
import { Play, Video, Trash2, Tag, Eye, Clock, HardDrive, Hash, TrendingUp, X } from 'lucide-react'
import { VideoSegment, MediaService } from '../services/mediaService'
import ProjectImage from './ProjectImage'
import VideoPlayer from './VideoPlayer'

interface VideoSegmentCardProps {
  segment: VideoSegment
  onDelete: (segmentId: string) => void
  onTagsUpdate: (segmentId: string, tags: string[]) => void
  onUse: (segmentId: string) => void
}

const VideoSegmentCard: React.FC<VideoSegmentCardProps> = ({
  segment,
  onDelete,
  onTagsUpdate,
  onUse
}) => {
  const [showVideoPlayer, setShowVideoPlayer] = useState(false)
  const [showTagEditor, setShowTagEditor] = useState(false)
  const [newTag, setNewTag] = useState('')

  const handlePlayVideo = () => {
    setShowVideoPlayer(true)
  }

  const handleUse = () => {
    onUse(segment.id)
    // 增加使用次数
    MediaService.incrementSegmentUsage(segment.id)
  }

  const handleDelete = () => {
    onDelete(segment.id)
  }

  const handleAddTag = () => {
    if (newTag.trim()) {
      const updatedTags = [...segment.tags, newTag.trim()]
      onTagsUpdate(segment.id, updatedTags)
      setNewTag('')
    }
  }

  const handleRemoveTag = (tagToRemove: string) => {
    const updatedTags = segment.tags.filter(tag => tag !== tagToRemove)
    onTagsUpdate(segment.id, updatedTags)
  }

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
      {/* 视频缩略图 */}
      <div className="relative h-48 bg-gray-100 overflow-hidden">
        {segment.thumbnail_path ? (
          <ProjectImage
            imagePath={segment.thumbnail_path}
            alt={`片段 ${segment.segment_index + 1}`}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="w-full h-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
            <Video size={48} className="text-white" />
          </div>
        )}
        
        {/* 播放按钮覆盖层 */}
        <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-30 transition-all flex items-center justify-center">
          <button
            onClick={handlePlayVideo}
            className="p-3 bg-white/80 rounded-full hover:bg-white transition-colors opacity-0 hover:opacity-100"
            title="播放视频"
          >
            <Play size={24} className="text-gray-800" />
          </button>
        </div>

        {/* 片段信息覆盖层 */}
        <div className="absolute top-2 left-2 bg-black/70 text-white px-2 py-1 rounded text-xs">
          片段 {segment.segment_index + 1}
        </div>
        
        {/* 使用次数 */}
        {segment.use_count > 0 && (
          <div className="absolute top-2 right-2 bg-green-500 text-white px-2 py-1 rounded text-xs flex items-center">
            <TrendingUp size={12} className="mr-1" />
            {segment.use_count}
          </div>
        )}
      </div>

      {/* 片段详细信息 */}
      <div className="p-4 space-y-3">
        {/* 基本信息 */}
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div className="flex items-center space-x-2">
            <Clock size={14} className="text-gray-400" />
            <span className="text-gray-600">时长:</span>
            <span className="font-medium">{MediaService.formatDuration(segment.duration)}</span>
          </div>
          <div className="flex items-center space-x-2">
            <HardDrive size={14} className="text-gray-400" />
            <span className="text-gray-600">大小:</span>
            <span className="font-medium">{MediaService.formatFileSize(segment.file_size)}</span>
          </div>
        </div>

        {/* 视频参数 */}
        <div className="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span className="text-gray-600">分辨率:</span>
            <span className="ml-2 font-medium">{MediaService.formatResolution(segment.width, segment.height)}</span>
          </div>
          <div>
            <span className="text-gray-600">帧率:</span>
            <span className="ml-2 font-medium">{segment.fps.toFixed(1)} fps</span>
          </div>
        </div>

        {/* 时间范围 */}
        <div className="text-sm">
          <span className="text-gray-600">时间范围:</span>
          <span className="ml-2 font-medium">
            {MediaService.formatDuration(segment.start_time)} - {MediaService.formatDuration(segment.end_time)}
          </span>
        </div>

        {/* 标签 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-600">标签:</span>
            <button
              onClick={() => setShowTagEditor(!showTagEditor)}
              className="p-1 text-gray-400 hover:text-blue-600 transition-colors"
              title="编辑标签"
            >
              <Tag size={14} />
            </button>
          </div>
          
          {/* 标签列表 */}
          <div className="flex flex-wrap gap-1">
            {segment.tags.map((tag, index) => (
              <span
                key={index}
                className="inline-flex items-center px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full cursor-pointer hover:bg-blue-200"
                onClick={() => handleRemoveTag(tag)}
                title="点击移除标签"
              >
                {tag}
                <X size={10} className="ml-1" />
              </span>
            ))}
          </div>

          {/* 标签编辑器 */}
          {showTagEditor && (
            <div className="flex space-x-2">
              <input
                type="text"
                value={newTag}
                onChange={(e) => setNewTag(e.target.value)}
                placeholder="添加标签"
                className="flex-1 px-2 py-1 text-xs border border-gray-300 rounded focus:ring-1 focus:ring-blue-500 focus:border-transparent"
                onKeyDown={(e) => e.key === 'Enter' && handleAddTag()}
              />
              <button
                onClick={handleAddTag}
                className="px-2 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700"
              >
                添加
              </button>
            </div>
          )}
        </div>

        {/* MD5哈希 */}
        <div className="text-xs text-gray-500 flex items-center space-x-1">
          <Hash size={12} />
          <span>MD5:</span>
          <code className="bg-gray-100 px-1 rounded font-mono">
            {segment.md5_hash.substring(0, 8)}...
          </code>
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-between pt-2 border-t border-gray-100">
          <div className="text-xs text-gray-400">
            {new Date(segment.created_at).toLocaleDateString()}
          </div>
          
          <div className="flex space-x-2">
            {/* 使用按钮 */}
            <button
              onClick={handleUse}
              className="p-2 text-gray-400 hover:text-green-600 transition-colors"
              title="使用此片段"
            >
              <Eye size={16} />
            </button>
            
            {/* 删除按钮 */}
            <button
              onClick={handleDelete}
              className="p-2 text-gray-400 hover:text-red-600 transition-colors"
              title="删除"
            >
              <Trash2 size={16} />
            </button>
          </div>
        </div>
      </div>

      {/* 视频播放器 */}
      <VideoPlayer
        videoPath={segment.file_path}
        isOpen={showVideoPlayer}
        onClose={() => setShowVideoPlayer(false)}
        title={`片段 ${segment.segment_index + 1} - ${segment.filename}`}
      />
    </div>
  )
}

export default VideoSegmentCard
