import React, { useState } from 'react'
import { Layout, Plus, X, Search, Play } from 'lucide-react'
import { Project } from '../services/projectService'

interface Template {
  id: string
  name: string
  description: string
  thumbnail?: string
  duration: number
  track_count: number
  tags: string[]
  created_at: string
}

interface ProjectTemplatesProps {
  project: Project
  templates: Template[]
  onTemplatesChange: (templates: Template[]) => void
}

const ProjectTemplates: React.FC<ProjectTemplatesProps> = ({
  project,
  templates,
  onTemplatesChange
}) => {
  const [showAddModal, setShowAddModal] = useState(false)
  const [availableTemplates, setAvailableTemplates] = useState<Template[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [loading, setLoading] = useState(false)

  const loadAvailableTemplates = async () => {
    try {
      setLoading(true)
      // 这里需要调用模板服务获取所有可用模板
      // const response = await TemplateService.getAllTemplates()
      // 暂时使用模拟数据
      const mockTemplates: Template[] = [
        {
          id: '1',
          name: '商品展示模板',
          description: '适合商品展示的基础模板',
          duration: 30,
          track_count: 3,
          tags: ['商品', '展示', '基础'],
          created_at: new Date().toISOString()
        },
        {
          id: '2',
          name: '动感宣传模板',
          description: '动感十足的宣传视频模板',
          duration: 60,
          track_count: 5,
          tags: ['宣传', '动感', '营销'],
          created_at: new Date().toISOString()
        }
      ]
      
      // 过滤掉已经添加到项目的模板
      const projectTemplateIds = templates.map(t => t.id)
      const available = mockTemplates.filter(template => !projectTemplateIds.includes(template.id))
      setAvailableTemplates(available)
    } catch (error) {
      console.error('Failed to load available templates:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleAddTemplate = (template: Template) => {
    const updatedTemplates = [...templates, template]
    onTemplatesChange(updatedTemplates)
    
    // 从可用列表中移除
    setAvailableTemplates(availableTemplates.filter(t => t.id !== template.id))
  }

  const handleRemoveTemplate = (templateId: string) => {
    const removedTemplate = templates.find(t => t.id === templateId)
    if (removedTemplate) {
      const updatedTemplates = templates.filter(t => t.id !== templateId)
      onTemplatesChange(updatedTemplates)
      
      // 添加回可用列表
      setAvailableTemplates([...availableTemplates, removedTemplate])
    }
  }

  const filteredAvailableTemplates = availableTemplates.filter(template =>
    template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    template.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (template.tags || []).some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()))
  )

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

  return (
    <div className="space-y-6">
      {/* 头部操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-medium text-gray-900">项目模板</h3>
          <p className="text-sm text-gray-600">管理此项目可使用的视频模板</p>
        </div>
        <button
          onClick={() => {
            setShowAddModal(true)
            loadAvailableTemplates()
          }}
          className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
        >
          <Plus size={16} className="mr-2" />
          添加模板
        </button>
      </div>

      {/* 已添加的模板列表 */}
      {templates.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <Layout className="mx-auto text-gray-400 mb-4" size={48} />
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无模板</h3>
          <p className="text-gray-600 mb-4">为此项目添加可使用的视频模板</p>
          <button
            onClick={() => {
              setShowAddModal(true)
              loadAvailableTemplates()
            }}
            className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            <Plus size={16} className="mr-2" />
            添加第一个模板
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {templates.map((template) => (
            <div key={template.id} className="bg-white border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow">
              {/* 模板缩略图 */}
              <div className="relative h-32 bg-gradient-to-br from-blue-500 to-purple-600">
                {template.thumbnail ? (
                  <img
                    src={template.thumbnail}
                    alt={template.name}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center">
                    <Layout size={32} 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 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>

                {/* 移除按钮 */}
                <button
                  onClick={() => handleRemoveTemplate(template.id)}
                  className="absolute top-2 right-2 p-1 bg-black/50 text-white rounded-full hover:bg-black/70 transition-colors"
                  title="移除模板"
                >
                  <X size={16} />
                </button>
              </div>

              {/* 模板信息 */}
              <div className="p-4">
                <h4 className="font-medium text-gray-900 mb-1">{template.name}</h4>
                <p className="text-sm text-gray-600 mb-2">{template.description}</p>
                
                <div className="flex items-center justify-between text-sm text-gray-500 mb-2">
                  <span>{formatDuration(template.duration)}</span>
                  <span>{template.track_count} 轨道</span>
                </div>

                <div className="flex flex-wrap gap-1">
                  {(template.tags || []).map((tag, index) => (
                    <span
                      key={index}
                      className="inline-block px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 添加模板模态框 */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-xl w-full max-w-4xl mx-4 max-h-[80vh] overflow-hidden">
            {/* 模态框头部 */}
            <div className="flex items-center justify-between p-6 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">添加模板到项目</h2>
              <button
                onClick={() => setShowAddModal(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <X size={24} />
              </button>
            </div>

            {/* 搜索框 */}
            <div className="p-6 border-b border-gray-200">
              <div className="relative">
                <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)}
                  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>
            </div>

            {/* 可用模板列表 */}
            <div className="p-6 overflow-y-auto max-h-96">
              {loading ? (
                <div className="text-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
                  <p className="text-gray-600 mt-2">加载中...</p>
                </div>
              ) : filteredAvailableTemplates.length === 0 ? (
                <div className="text-center py-8">
                  <Layout className="mx-auto text-gray-400 mb-4" size={48} />
                  <p className="text-gray-600">
                    {searchTerm ? '没有找到匹配的模板' : '没有可用的模板'}
                  </p>
                </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredAvailableTemplates.map((template) => (
                    <div
                      key={template.id}
                      className="border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow"
                    >
                      {/* 模板缩略图 */}
                      <div className="relative h-24 bg-gradient-to-br from-blue-500 to-purple-600">
                        {template.thumbnail ? (
                          <img
                            src={template.thumbnail}
                            alt={template.name}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center">
                            <Layout size={24} className="text-white" />
                          </div>
                        )}
                      </div>

                      {/* 模板信息 */}
                      <div className="p-3">
                        <h4 className="font-medium text-gray-900 text-sm mb-1">{template.name}</h4>
                        <p className="text-xs text-gray-600 mb-2">{template.description}</p>
                        
                        <div className="flex items-center justify-between text-xs text-gray-500 mb-2">
                          <span>{formatDuration(template.duration)}</span>
                          <span>{template.track_count} 轨道</span>
                        </div>

                        <div className="flex items-center justify-between">
                          <div className="flex flex-wrap gap-1">
                            {(template.tags || []).slice(0, 2).map((tag, index) => (
                              <span
                                key={index}
                                className="inline-block px-1 py-0.5 bg-gray-100 text-gray-700 text-xs rounded"
                              >
                                {tag}
                              </span>
                            ))}
                            {(template.tags || []).length > 2 && (
                              <span className="text-xs text-gray-500">+{(template.tags || []).length - 2}</span>
                            )}
                          </div>
                          <button
                            onClick={() => handleAddTemplate(template)}
                            className="px-2 py-1 bg-blue-600 text-white text-xs rounded hover:bg-blue-700 transition-colors"
                          >
                            添加
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* 模态框底部 */}
            <div className="flex justify-end p-6 border-t border-gray-200">
              <button
                onClick={() => setShowAddModal(false)}
                className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default ProjectTemplates
