import React, { useState, useEffect } from 'react'
import { ProjectService, Project } from '../services/projectService'
import ProjectSearchBar from '../components/ProjectSearchBar'
import ProjectList from '../components/ProjectList'
import ProjectForm from '../components/ProjectForm'

interface FormData {
  name: string
  local_directory: string
  product_name: string
  product_image: string
}

const ProjectManagePage: React.FC = () => {
  const [projects, setProjects] = useState<Project[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [editingProject, setEditingProject] = useState<Project | null>(null)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [formData, setFormData] = useState<FormData>({
    name: '',
    local_directory: '',
    product_name: '',
    product_image: ''
  })

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

  const loadProjects = async () => {
    try {
      setLoading(true)
      const response = await ProjectService.getAllProjects()
      if (response.status && response.data) {
        setProjects(response.data)
      } else {
        console.error('Failed to load projects:', response.msg)
      }
    } catch (error) {
      console.error('Failed to load projects:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCreateProject = async () => {
    try {
      const response = await ProjectService.createProject(formData)
      if (response.status && response.data) {
        setProjects([...projects, response.data])
        handleCancelForm()
      } else {
        console.error('创建失败:', response.msg || '未知错误')
      }
    } catch (error) {
      console.error('Failed to create project:', error)
    }
  }

  const handleUpdateProject = async () => {
    if (!editingProject) return
    
    try {
      const response = await ProjectService.updateProject(editingProject.id, formData)
      if (response.status && response.data) {
        const updatedProjects = projects.map(proj =>
          proj.id === editingProject.id ? response.data! : proj
        )
        setProjects(updatedProjects)
        handleCancelForm()
      } else {
        console.error('更新失败:', response.msg || '未知错误')
      }
    } catch (error) {
      console.error('Failed to update project:', error)
    }
  }

  const handleDeleteProject = async (projectId: string) => {
    if (!confirm('确定要删除这个项目吗？')) return
    
    try {
      const response = await ProjectService.deleteProject(projectId)
      if (response.status) {
        setProjects(projects.filter(proj => proj.id !== projectId))
      } else {
        console.error('删除失败:', response.msg || '未知错误')
      }
    } catch (error) {
      console.error('Failed to delete project:', error)
    }
  }

  const handleOpenDirectory = async (projectId: string) => {
    try {
      const response = await ProjectService.openProjectDirectory(projectId)
      if (!response.status) {
        console.error('打开目录失败:', response.msg || '未知错误')
      }
    } catch (error) {
      console.error('Failed to open directory:', error)
    }
  }

  const handleEditProject = (project: Project) => {
    setEditingProject(project)
    setFormData({
      name: project.name,
      local_directory: project.local_directory,
      product_name: project.product_name,
      product_image: project.product_image
    })
    setShowCreateForm(true)
  }

  const handleCreateNew = () => {
    setEditingProject(null)
    setFormData({ name: '', local_directory: '', product_name: '', product_image: '' })
    setShowCreateForm(true)
  }

  const handleCancelForm = () => {
    setEditingProject(null)
    setShowCreateForm(false)
    setFormData({ name: '', local_directory: '', product_name: '', product_image: '' })
  }

  const handleSubmitForm = () => {
    if (editingProject) {
      handleUpdateProject()
    } else {
      handleCreateProject()
    }
  }

  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>

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

      {/* 项目列表 */}
      <ProjectList
        projects={projects}
        loading={loading}
        searchTerm={searchTerm}
        onEdit={handleEditProject}
        onDelete={handleDeleteProject}
        onOpenDirectory={handleOpenDirectory}
        onCreateNew={handleCreateNew}
      />

      {/* 项目表单 */}
      <ProjectForm
        isOpen={showCreateForm}
        isEditing={!!editingProject}
        formData={formData}
        onFormDataChange={setFormData}
        onSubmit={handleSubmitForm}
        onCancel={handleCancelForm}
      />
    </div>
  )
}

export default ProjectManagePage
