import React, { useState, useEffect } from 'react'
import { ModelService, Model } from '../services/modelService'
import ModelSearchBar from '../components/ModelSearchBar'
import ModelList from '../components/ModelList'
import ModelForm from '../components/ModelForm'

interface FormData {
  model_number: string
  model_image: string
}

const ModelManagePage: React.FC = () => {
  const [models, setModels] = useState<Model[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [editingModel, setEditingModel] = useState<Model | null>(null)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [formData, setFormData] = useState<FormData>({
    model_number: '',
    model_image: ''
  })

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

  const loadModels = async () => {
    try {
      setLoading(true)
      const response = await ModelService.getAllModels()
      if (response.status && response.data) {
        setModels(response.data)
      } else {
        console.error('Failed to load models:', response.msg)
      }
    } catch (error) {
      console.error('Failed to load models:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCreateModel = async () => {
    try {
      const response = await ModelService.createModel(formData)
      console.log(`handleCreateModel`, response)
      if (response.status && response.data) {
        setModels([...models, response.data])
        handleCancelForm()
      } else {
        console.error('创建失败:', response.msg || '未知错误')
        alert('创建失败: ' + (response.msg || '未知错误'))
      }
    } catch (error) {
      console.error('Failed to create model:', error)
      alert('创建失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleUpdateModel = async () => {
    if (!editingModel) return

    try {
      const response = await ModelService.updateModel(editingModel.id, formData)
      if (response.status && response.data) {
        const updatedModels = models.map(model =>
          model.id === editingModel.id ? response.data! : model
        )
        setModels(updatedModels)
        handleCancelForm()
      } else {
        console.error('更新失败:', response.msg || '未知错误')
        alert('更新失败: ' + (response.msg || '未知错误'))
      }
    } catch (error) {
      console.error('Failed to update model:', error)
      alert('更新失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleDeleteModel = async (modelId: string) => {
    console.log('handleDeleteModel called with:', modelId)
    const isOk = confirm('确定要删除这个模特吗？')
    console.log('User confirmed deletion:', isOk)
    if (!isOk) {
      console.log('User cancelled deletion, returning early')
      return
    }

    try {
      console.log('Calling ModelService.deleteModel...')
      const response = await ModelService.deleteModel(modelId)
      console.log('Delete response:', response)

      if (response.status) {
        console.log('Delete successful, updating models list')
        setModels(models.filter(model => model.id !== modelId))
      } else {
        console.error('删除失败:', response.msg || '未知错误')
        alert('删除失败: ' + (response.msg || '未知错误'))
      }
    } catch (error) {
      console.error('Failed to delete model:', error)
      alert('删除失败: ' + (error instanceof Error ? error.message : '未知错误'))
    }
  }

  const handleEditModel = (model: Model) => {
    setEditingModel(model)
    setFormData({
      model_number: model.model_number,
      model_image: model.model_image
    })
    setShowCreateForm(true)
  }

  const handleCreateNew = () => {
    setEditingModel(null)
    setFormData({ model_number: '', model_image: '' })
    setShowCreateForm(true)
  }

  const handleCancelForm = () => {
    setEditingModel(null)
    setShowCreateForm(false)
    setFormData({ model_number: '', model_image: '' })
  }

  const handleSubmitForm = () => {
    if (editingModel) {
      handleUpdateModel()
    } else {
      handleCreateModel()
    }
  }

  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>

      {/* 搜索和操作栏 */}
      <ModelSearchBar
        searchTerm={searchTerm}
        onSearchChange={setSearchTerm}
        onCreateNew={handleCreateNew}
      />

      {/* 模特列表 */}
      <ModelList
        models={models}
        loading={loading}
        searchTerm={searchTerm}
        onEdit={handleEditModel}
        onDelete={handleDeleteModel}
        onCreateNew={handleCreateNew}
      />

      {/* 模特表单 */}
      <ModelForm
        isOpen={showCreateForm}
        isEditing={!!editingModel}
        formData={formData}
        onFormDataChange={setFormData}
        onSubmit={handleSubmitForm}
        onCancel={handleCancelForm}
      />
    </div>
  )
}

export default ModelManagePage
