import React, { useState, useEffect } from 'react'
import { Search, Upload, Filter, TrendingUp, Video } from 'lucide-react'
import { MediaService, VideoSegment } from '../services/mediaService'
import VideoSegmentCard from '../components/VideoSegmentCard'
import VideoUpload from '../components/VideoUpload'

const MediaLibraryPage: React.FC = () => {
  const [segments, setSegments] = useState<VideoSegment[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [showUpload, setShowUpload] = useState(false)
  const [filterTags, setFilterTags] = useState<string[]>([])
  const [showPopular, setShowPopular] = useState(false)

  useEffect(() => {
    loadSegments()
  }, [])

  const loadSegments = async () => {
    try {
      setLoading(true)
      const response = await MediaService.getAllSegments()
      if (response.status && response.data) {
        setSegments(response.data)
      } else {
        console.error('Failed to load segments:', response.msg)
      }
    } catch (error) {
      console.error('Failed to load segments:', error)
    } finally {
      setLoading(false)
    }
  }

  const loadPopularSegments = async () => {
    try {
      setLoading(true)
      const response = await MediaService.getPopularSegments(20)
      if (response.status && response.data) {
        setSegments(response.data)
        setShowPopular(true)
      } else {
        console.error('Failed to load popular segments:', response.msg)
      }
    } catch (error) {
      console.error('Failed to load popular segments:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleDeleteSegment = async (segmentId: string) => {
    const isOk = confirm('确定要删除这个视频片段吗？')
    if (!isOk) return

    try {
      const response = await MediaService.deleteSegment(segmentId)
      if (response.status) {
        setSegments(segments.filter(segment => segment.id !== segmentId))
      } else {
        console.error('删除失败:', response.msg || '未知错误')
        alert('删除失败: ' + (response.msg || '未知错误'))
      }
    } catch (error) {
      console.error('Failed to delete segment:', error)
      alert('删除失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleTagsUpdate = async (segmentId: string, newTags: string[]) => {
    // 找到当前片段
    const segment = segments.find(s => s.id === segmentId)
    if (!segment) return

    const currentTags = segment.tags
    const tagsToAdd = newTags.filter(tag => !currentTags.includes(tag))
    const tagsToRemove = currentTags.filter(tag => !newTags.includes(tag))

    try {
      // 添加新标签
      if (tagsToAdd.length > 0) {
        await MediaService.addSegmentTags({ segment_id: segmentId, tags: tagsToAdd })
      }

      // 移除标签
      if (tagsToRemove.length > 0) {
        await MediaService.removeSegmentTags({ segment_id: segmentId, tags: tagsToRemove })
      }

      // 更新本地状态
      setSegments(segments.map(s => 
        s.id === segmentId ? { ...s, tags: newTags } : s
      ))
    } catch (error) {
      console.error('Failed to update tags:', error)
      alert('标签更新失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleUseSegment = (segmentId: string) => {
    // 更新使用次数
    setSegments(segments.map(s => 
      s.id === segmentId ? { ...s, use_count: s.use_count + 1 } : s
    ))
  }

  const handleUploadComplete = () => {
    loadSegments()
    setShowPopular(false)
  }

  const handleSearch = async () => {
    if (!searchTerm.trim()) {
      loadSegments()
      return
    }

    try {
      setLoading(true)
      const response = await MediaService.searchSegments(searchTerm)
      if (response.status && response.data) {
        setSegments(response.data)
        setShowPopular(false)
      } else {
        console.error('Search failed:', response.msg)
      }
    } catch (error) {
      console.error('Failed to search segments:', error)
    } finally {
      setLoading(false)
    }
  }

  const filteredSegments = segments.filter(segment => {
    if (filterTags.length === 0) return true
    return filterTags.some(tag => segment.tags.includes(tag))
  })

  // 获取所有标签
  const allTags = Array.from(new Set(segments.flatMap(s => s.tags)))

  return (
    <div className="p-6">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">媒体库</h1>
        <p className="text-gray-600 mt-2">管理视频素材，支持智能分割、标签管理和使用统计</p>
      </div>

      {/* 搜索和操作栏 */}
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between mb-6 space-y-4 lg:space-y-0">
        {/* 搜索框 */}
        <div className="flex space-x-2">
          <div className="relative flex-1 max-w-md">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
            <input
              type="text"
              placeholder="搜索视频片段..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent w-full"
            />
          </div>
          <button
            onClick={handleSearch}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
          >
            搜索
          </button>
        </div>

        {/* 操作按钮 */}
        <div className="flex space-x-2">
          <button
            onClick={loadPopularSegments}
            className="flex items-center px-4 py-2 bg-purple-100 text-purple-700 rounded-lg hover:bg-purple-200 transition-colors"
          >
            <TrendingUp size={16} className="mr-2" />
            热门片段
          </button>
          <button
            onClick={() => {
              loadSegments()
              setShowPopular(false)
            }}
            className="flex items-center px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
          >
            <Video size={16} className="mr-2" />
            全部片段
          </button>
          <button
            onClick={() => setShowUpload(true)}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Upload size={16} className="mr-2" />
            上传视频
          </button>
        </div>
      </div>

      {/* 标签过滤器 */}
      {allTags.length > 0 && (
        <div className="mb-6">
          <div className="flex items-center space-x-2 mb-2">
            <Filter size={16} className="text-gray-400" />
            <span className="text-sm text-gray-600">标签过滤:</span>
          </div>
          <div className="flex flex-wrap gap-2">
            {allTags.map((tag, index) => (
              <button
                key={index}
                onClick={() => {
                  if (filterTags.includes(tag)) {
                    setFilterTags(filterTags.filter(t => t !== tag))
                  } else {
                    setFilterTags([...filterTags, tag])
                  }
                }}
                className={`px-3 py-1 text-sm rounded-full transition-colors ${
                  filterTags.includes(tag)
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                {tag}
              </button>
            ))}
            {filterTags.length > 0 && (
              <button
                onClick={() => setFilterTags([])}
                className="px-3 py-1 text-sm bg-red-100 text-red-700 rounded-full hover:bg-red-200 transition-colors"
              >
                清除过滤
              </button>
            )}
          </div>
        </div>
      )}

      {/* 状态指示 */}
      {showPopular && (
        <div className="mb-4 p-3 bg-purple-50 border border-purple-200 rounded-lg">
          <div className="flex items-center text-purple-700">
            <TrendingUp size={16} className="mr-2" />
            <span className="text-sm">正在显示热门片段（按使用次数排序）</span>
          </div>
        </div>
      )}

      {/* 视频片段列表 */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {Array.from({ length: 8 }).map((_, index) => (
            <div key={index} className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
              <div className="h-48 bg-gray-200 animate-pulse"></div>
              <div className="p-4 space-y-3">
                <div className="h-4 bg-gray-200 rounded animate-pulse"></div>
                <div className="h-4 bg-gray-200 rounded animate-pulse w-2/3"></div>
                <div className="h-4 bg-gray-200 rounded animate-pulse w-1/2"></div>
              </div>
            </div>
          ))}
        </div>
      ) : filteredSegments.length === 0 ? (
        <div className="text-center py-12">
          <Video className="mx-auto text-gray-400 mb-4" size={64} />
          <div className="text-gray-400 mb-4">
            {searchTerm || filterTags.length > 0 ? '没有找到匹配的视频片段' : '暂无视频片段'}
          </div>
          {!searchTerm && filterTags.length === 0 && (
            <button
              onClick={() => setShowUpload(true)}
              className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Upload size={16} className="mr-2" />
              上传第一个视频
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
          {filteredSegments.map((segment) => (
            <VideoSegmentCard
              key={segment.id}
              segment={segment}
              onDelete={handleDeleteSegment}
              onTagsUpdate={handleTagsUpdate}
              onUse={handleUseSegment}
            />
          ))}
        </div>
      )}

      {/* 上传对话框 */}
      <VideoUpload
        isOpen={showUpload}
        onClose={() => setShowUpload(false)}
        onUploadComplete={handleUploadComplete}
      />
    </div>
  )
}

export default MediaLibraryPage
