import React, { useState, useEffect } from 'react'
import { invoke } from '@tauri-apps/api/core'
import { useNavigate } from 'react-router-dom'
import { TemplateServiceV2, type TemplateInfo, type TemplateStats, type TagInfo } from '../services/TemplateServiceV2'
import { 
  Search, 
  Grid, 
  List, 
  Upload, 
  Tag, 
  BarChart3,
  RefreshCw,
  Eye,
  Trash2
} from 'lucide-react'

const TemplateManagePageV2: React.FC = () => {
  const navigate = useNavigate()

  // State
  const [templates, setTemplates] = useState<TemplateInfo[]>([])
  const [filteredTemplates, setFilteredTemplates] = useState<TemplateInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [importing, setImporting] = useState(false)
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedTag, setSelectedTag] = useState<string>('')
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [includeCloud, setIncludeCloud] = useState(true)
  const [showStats, setShowStats] = useState(false)
  
  // Stats and tags
  const [stats, setStats] = useState<TemplateStats | null>(null)
  const [popularTags, setPopularTags] = useState<TagInfo[]>([])

  useEffect(() => {
    loadTemplates()
    loadStats()
    loadPopularTags()
  }, [includeCloud])

  useEffect(() => {
    filterTemplates()
  }, [templates, searchTerm, selectedTag])

  // 过滤模板
  const filterTemplates = () => {
    let filtered = templates

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(template => 
        template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        template.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
        template.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
      )
    }

    // 标签过滤
    if (selectedTag) {
      filtered = filtered.filter(template => 
        template.tags.includes(selectedTag)
      )
    }

    setFilteredTemplates(filtered)
  }

  // 加载模板列表
  const loadTemplates = async () => {
    try {
      setLoading(true)
      const templateList = await TemplateServiceV2.getTemplates(includeCloud, 200)
      setTemplates(templateList)
    } catch (error) {
      console.error('Error loading templates:', error)
      setTemplates([])
    } finally {
      setLoading(false)
    }
  }

  // 加载统计信息
  const loadStats = async () => {
    try {
      const templateStats = await TemplateServiceV2.getTemplateStats()
      setStats(templateStats)
    } catch (error) {
      console.error('Error loading stats:', error)
    }
  }

  // 加载热门标签
  const loadPopularTags = async () => {
    try {
      const tags = await TemplateServiceV2.getPopularTags(15)
      setPopularTags(tags)
    } catch (error) {
      console.error('Error loading popular tags:', error)
    }
  }

  // 批量导入
  const handleBatchImport = async () => {
    try {
      const folderResult = await invoke<string>('select_folder')
      if (!folderResult) return

      setImporting(true)
      const result = await TemplateServiceV2.batchImportTemplates(folderResult)
      
      if (result.imported_count > 0) {
        await loadTemplates() // 重新加载模板列表
        await loadStats() // 重新加载统计信息
        alert(`导入成功！成功导入 ${result.imported_count} 个模板，失败 ${result.failed_count} 个`)
      } else {
        alert('导入失败：' + result.message)
      }
    } catch (error) {
      console.error('Import failed:', error)
      alert('导入失败: ' + (error instanceof Error ? error.message : 'Unknown error'))
    } finally {
      setImporting(false)
    }
  }

  // 删除模板
  const handleDeleteTemplate = async (templateId: string) => {
    if (!confirm('确定要删除这个模板吗？此操作不可撤销。')) return

    try {
      const success = await TemplateServiceV2.deleteTemplate(templateId)
      if (success) {
        setTemplates(templates.filter(t => t.id !== templateId))
        await loadStats() // 重新加载统计信息
      } else {
        alert('删除失败')
      }
    } catch (error) {
      console.error('Delete failed:', error)
      alert('删除失败: ' + (error instanceof Error ? error.message : 'Unknown error'))
    }
  }

  // 查看模板详情
  const viewTemplateDetail = (template: TemplateInfo) => {
    navigate(`/templates/${template.id}`)
  }

  // 按标签搜索
  const handleTagClick = async (tag: string) => {
    if (selectedTag === tag) {
      setSelectedTag('')
      return
    }
    
    setSelectedTag(tag)
    try {
      const templatesByTag = await TemplateServiceV2.getTemplatesByTag(tag, includeCloud, 100)
      setTemplates(templatesByTag)
    } catch (error) {
      console.error('Error loading templates by tag:', error)
    }
  }

  // 搜索模板
  const handleSearch = async () => {
    if (!searchTerm.trim()) {
      await loadTemplates()
      return
    }

    try {
      setLoading(true)
      const searchResults = await TemplateServiceV2.searchTemplates(searchTerm, includeCloud, 100)
      setTemplates(searchResults)
    } catch (error) {
      console.error('Search failed:', error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold text-gray-900">模板管理 V2</h1>
              <p className="text-gray-600">管理和导入视频编辑模板 - 新版本</p>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={() => setShowStats(!showStats)}
                className="flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                <BarChart3 size={20} />
                <span>统计</span>
              </button>
              <button
                onClick={loadTemplates}
                disabled={loading}
                className="flex items-center space-x-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
              >
                <RefreshCw size={20} className={loading ? 'animate-spin' : ''} />
                <span>刷新</span>
              </button>
            </div>
          </div>
        </div>

        {/* Stats Panel */}
        {showStats && stats && (
          <div className="bg-white rounded-lg shadow-sm p-6 mb-6">
            <h2 className="text-xl font-semibold mb-4">模板统计</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">{stats.total_templates}</div>
                <div className="text-sm text-gray-600">总模板数</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">{stats.user_templates}</div>
                <div className="text-sm text-gray-600">用户模板</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-purple-600">{stats.cloud_templates}</div>
                <div className="text-sm text-gray-600">云端模板</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-orange-600">{stats.total_materials}</div>
                <div className="text-sm text-gray-600">总素材数</div>
              </div>
            </div>
          </div>
        )}

        {/* Search and Filters */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
            {/* Search */}
            <div className="flex items-center space-x-4">
              <div className="relative flex-1 lg:w-80">
                <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="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
              </div>
              <button
                onClick={handleSearch}
                disabled={loading}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              >
                搜索
              </button>
            </div>

            {/* Controls */}
            <div className="flex items-center space-x-4">
              {/* Cloud Toggle */}
              <label className="flex items-center space-x-2">
                <input
                  type="checkbox"
                  checked={includeCloud}
                  onChange={(e) => setIncludeCloud(e.target.checked)}
                  className="rounded"
                />
                <span className="text-sm">包含云端模板</span>
              </label>

              {/* View Mode */}
              <div className="flex items-center space-x-2">
                <button
                  onClick={() => setViewMode('grid')}
                  className={`p-2 rounded ${viewMode === 'grid' ? 'bg-blue-100 text-blue-600' : 'text-gray-400'}`}
                >
                  <Grid size={20} />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={`p-2 rounded ${viewMode === 'list' ? 'bg-blue-100 text-blue-600' : 'text-gray-400'}`}
                >
                  <List size={20} />
                </button>
              </div>

              {/* Import Button */}
              <button
                onClick={handleBatchImport}
                disabled={importing}
                className="flex items-center space-x-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
              >
                <Upload size={20} />
                <span>{importing ? '导入中...' : '批量导入'}</span>
              </button>
            </div>
          </div>
        </div>

        {/* Popular Tags */}
        {popularTags.length > 0 && (
          <div className="bg-white rounded-lg shadow-sm p-4 mb-6">
            <h3 className="text-lg font-medium mb-3">热门标签</h3>
            <div className="flex flex-wrap gap-2">
              {popularTags.map((tagInfo) => (
                <button
                  key={tagInfo.tag}
                  onClick={() => handleTagClick(tagInfo.tag)}
                  className={`flex items-center space-x-1 px-3 py-1 rounded-full text-sm ${
                    selectedTag === tagInfo.tag
                      ? 'bg-blue-100 text-blue-700 border border-blue-300'
                      : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                  }`}
                >
                  <Tag size={14} />
                  <span>{tagInfo.tag}</span>
                  <span className="text-xs opacity-75">({tagInfo.count})</span>
                </button>
              ))}
              {selectedTag && (
                <button
                  onClick={() => {
                    setSelectedTag('')
                    loadTemplates()
                  }}
                  className="px-3 py-1 bg-red-100 text-red-700 rounded-full text-sm hover:bg-red-200"
                >
                  清除筛选
                </button>
              )}
            </div>
          </div>
        )}

        {/* Template Grid/List */}
        <div className="bg-white rounded-lg shadow-sm p-6">
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <RefreshCw className="animate-spin mr-2" size={24} />
              <span>加载中...</span>
            </div>
          ) : filteredTemplates.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-gray-400 mb-4">
                <Grid size={48} className="mx-auto" />
              </div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无模板</h3>
              <p className="text-gray-600">点击"批量导入"按钮开始导入模板</p>
            </div>
          ) : (
            <>
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-lg font-medium">
                  模板列表 ({filteredTemplates.length})
                </h2>
                {selectedTag && (
                  <div className="text-sm text-gray-600">
                    筛选标签: <span className="font-medium">{selectedTag}</span>
                  </div>
                )}
              </div>
              
              {viewMode === 'grid' ? (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                  {filteredTemplates.map((template) => (
                    <TemplateCardV2
                      key={template.id}
                      template={template}
                      onView={viewTemplateDetail}
                      onDelete={handleDeleteTemplate}
                    />
                  ))}
                </div>
              ) : (
                <div className="space-y-4">
                  {filteredTemplates.map((template) => (
                    <TemplateListItemV2
                      key={template.id}
                      template={template}
                      onView={viewTemplateDetail}
                      onDelete={handleDeleteTemplate}
                    />
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  )
}

// 模板卡片组件
const TemplateCardV2: React.FC<{
  template: TemplateInfo
  onView: (template: TemplateInfo) => void
  onDelete: (templateId: string) => void
}> = ({ template, onView, onDelete }) => {
  const thumbnailUrl = TemplateServiceV2.getThumbnailUrl(template)
  const isCloud = TemplateServiceV2.isCloudTemplate(template)

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
      {/* Thumbnail */}
      <div className="aspect-video bg-gray-100 flex items-center justify-center relative">
        {thumbnailUrl ? (
          <img
            src={thumbnailUrl}
            alt={template.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="text-gray-400">
            <Eye size={32} />
          </div>
        )}
        {isCloud && (
          <div className="absolute top-2 right-2 bg-blue-500 text-white px-2 py-1 rounded text-xs">
            云端
          </div>
        )}
      </div>

      {/* Content */}
      <div className="p-4">
        <h3 className="font-medium text-gray-900 mb-1 truncate">{template.name}</h3>
        <p className="text-sm text-gray-600 mb-3 line-clamp-2">{template.description}</p>
        
        {/* Stats */}
        <div className="flex items-center justify-between text-xs text-gray-500 mb-3">
          <span>{TemplateServiceV2.formatDuration(template.duration)}</span>
          <span>{template.material_count} 素材</span>
          <span>{template.track_count} 轨道</span>
        </div>

        {/* Tags */}
        {template.tags.length > 0 && (
          <div className="flex flex-wrap gap-1 mb-3">
            {template.tags.slice(0, 3).map((tag) => (
              <span
                key={tag}
                className="px-2 py-1 bg-gray-100 text-gray-600 rounded text-xs"
              >
                {tag}
              </span>
            ))}
            {template.tags.length > 3 && (
              <span className="px-2 py-1 bg-gray-100 text-gray-600 rounded text-xs">
                +{template.tags.length - 3}
              </span>
            )}
          </div>
        )}

        {/* Actions */}
        <div className="flex items-center justify-between">
          <span className="text-xs text-gray-500">
            {TemplateServiceV2.formatDate(template.created_at)}
          </span>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => onView(template)}
              className="p-1 text-blue-600 hover:text-blue-700"
            >
              <Eye size={16} />
            </button>
            <button
              onClick={() => onDelete(template.id)}
              className="p-1 text-red-600 hover:text-red-700"
            >
              <Trash2 size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

// 模板列表项组件
const TemplateListItemV2: React.FC<{
  template: TemplateInfo
  onView: (template: TemplateInfo) => void
  onDelete: (templateId: string) => void
}> = ({ template, onView, onDelete }) => {
  const thumbnailUrl = TemplateServiceV2.getThumbnailUrl(template)
  const isCloud = TemplateServiceV2.isCloudTemplate(template)

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 hover:shadow-md transition-shadow">
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          {/* Thumbnail */}
          <div className="w-16 h-12 bg-gray-100 rounded flex items-center justify-center flex-shrink-0 relative">
            {thumbnailUrl ? (
              <img
                src={thumbnailUrl}
                alt={template.name}
                className="w-full h-full object-cover rounded"
              />
            ) : (
              <Eye size={16} className="text-gray-400" />
            )}
            {isCloud && (
              <div className="absolute -top-1 -right-1 bg-blue-500 text-white px-1 rounded text-xs">
                云
              </div>
            )}
          </div>

          {/* Info */}
          <div className="flex-1">
            <h3 className="font-medium text-gray-900">{template.name}</h3>
            <p className="text-sm text-gray-600 mb-1">{template.description}</p>
            {template.tags.length > 0 && (
              <div className="flex flex-wrap gap-1">
                {template.tags.slice(0, 5).map((tag) => (
                  <span
                    key={tag}
                    className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs"
                  >
                    {tag}
                  </span>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="flex items-center space-x-6 text-sm text-gray-500">
          <span>{TemplateServiceV2.formatDuration(template.duration)}</span>
          <span>{template.material_count} 素材</span>
          <span>{template.track_count} 轨道</span>
          <span>{TemplateServiceV2.formatDate(template.created_at)}</span>
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={() => onView(template)}
            className="p-2 text-blue-600 hover:text-blue-700"
          >
            <Eye size={16} />
          </button>
          <button
            onClick={() => onDelete(template.id)}
            className="p-2 text-red-600 hover:text-red-700"
          >
            <Trash2 size={16} />
          </button>
        </div>
      </div>
    </div>
  )
}

export default TemplateManagePageV2
