import React, { useState } from 'react'
import { User, Plus, X, Search } from 'lucide-react'
import { Project } from '../services/projectService'
import { Model, ModelService } from '../services/modelService'

interface ProjectModelsProps {
  project: Project
  models: Model[]
  onModelsChange: (models: Model[]) => void
}

const ProjectModels: React.FC<ProjectModelsProps> = ({
  project,
  models,
  onModelsChange
}) => {
  const [showAddModal, setShowAddModal] = useState(false)
  const [availableModels, setAvailableModels] = useState<Model[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [loading, setLoading] = useState(false)

  const loadAvailableModels = async () => {
    try {
      setLoading(true)
      const response = await ModelService.getAllModels()
      if (response.status && response.data) {
        // 过滤掉已经添加到项目的模特
        const projectModelIds = models.map(m => m.id)
        const available = response.data.filter((model: Model) => !projectModelIds.includes(model.id))
        setAvailableModels(available)
      }
    } catch (error) {
      console.error('Failed to load available models:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleAddModel = (model: Model) => {
    const updatedModels = [...models, model]
    onModelsChange(updatedModels)
    
    // 从可用列表中移除
    setAvailableModels(availableModels.filter(m => m.id !== model.id))
  }

  const handleRemoveModel = (modelId: string) => {
    const removedModel = models.find(m => m.id === modelId)
    if (removedModel) {
      const updatedModels = models.filter(m => m.id !== modelId)
      onModelsChange(updatedModels)
      
      // 添加回可用列表
      setAvailableModels([...availableModels, removedModel])
    }
  }

  const filteredAvailableModels = availableModels.filter(model =>
    model.model_number.toLowerCase().includes(searchTerm.toLowerCase())
  )

  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)
            loadAvailableModels()
          }}
          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>

      {/* 已添加的模特列表 */}
      {models.length === 0 ? (
        <div className="text-center py-12 bg-gray-50 rounded-lg">
          <User 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)
              loadAvailableModels()
            }}
            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-4">
          {models.map((model) => (
            <div key={model.id} className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <h4 className="font-medium text-gray-900 mb-1">{model.model_number}</h4>
                  <p className="text-sm text-gray-600 mb-2">
                    创建于 {new Date(model.created_at).toLocaleDateString()}
                  </p>
                  {model.model_image && (
                    <div className="w-16 h-16 bg-gray-100 rounded-lg overflow-hidden mb-2">
                      <img
                        src={model.model_image}
                        alt={model.model_number}
                        className="w-full h-full object-cover"
                      />
                    </div>
                  )}
                </div>
                <button
                  onClick={() => handleRemoveModel(model.id)}
                  className="p-1 text-gray-400 hover:text-red-600 transition-colors"
                  title="移除模特"
                >
                  <X size={16} />
                </button>
              </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-2xl 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>
              ) : filteredAvailableModels.length === 0 ? (
                <div className="text-center py-8">
                  <User className="mx-auto text-gray-400 mb-4" size={48} />
                  <p className="text-gray-600">
                    {searchTerm ? '没有找到匹配的模特' : '没有可用的模特'}
                  </p>
                </div>
              ) : (
                <div className="space-y-3">
                  {filteredAvailableModels.map((model) => (
                    <div
                      key={model.id}
                      className="flex items-center justify-between p-3 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                      <div className="flex-1">
                        <h4 className="font-medium text-gray-900">{model.model_number}</h4>
                        <p className="text-sm text-gray-600">
                          创建于 {new Date(model.created_at).toLocaleDateString()}
                        </p>
                        {model.model_image && (
                          <div className="w-12 h-12 bg-gray-100 rounded-lg overflow-hidden mt-1">
                            <img
                              src={model.model_image}
                              alt={model.model_number}
                              className="w-full h-full object-cover"
                            />
                          </div>
                        )}
                      </div>
                      <button
                        onClick={() => handleAddModel(model)}
                        className="ml-4 px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700 transition-colors"
                      >
                        添加
                      </button>
                    </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 ProjectModels
