'use client'

import { useState } from "react"
import { useRouter } from "next/navigation"

export default function CategoryForm({
  category,
}: {
  category?: {
    id?: number
    name: string
    icon?: string
    description?: string
  }
}) {
  const router = useRouter()
  const [formData, setFormData] = useState({
    name: category?.name || "",
    icon: category?.icon || "",
    description: category?.description || "",
  })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")
  const [success, setSuccess] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError("")

    try {
      const url = category?.id
        ? `/api/admin/categories/${category.id}`
        : "/api/admin/categories"

      const method = category?.id ? "PUT" : "POST"

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      })

      if (res.ok) {
        setSuccess(true)
        await new Promise(r => setTimeout(r, 1000))
        router.push("/admin/categories")
      } else {
        const data = await res.json().catch(() => ({}))
        setError(data.error || "保存失败")
      }
    } catch (err) {
      setError("保存失败，请稍后重试")
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          名称
        </label>
        <input
          type="text"
          required
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
          placeholder="客服"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          图标 (Emoji)
        </label>
        <input
          type="text"
          value={formData.icon}
          onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
          placeholder="🤖"
        />
      </div>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">
          描述
        </label>
        <textarea
          rows={4}
          value={formData.description}
          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
          placeholder="描述分类的用途和场景..."
        />
      </div>

      {success && (
        <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg text-sm">
          保存成功
        </div>
      )}

      {error && (
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm">
          {error}
        </div>
      )}

      <div className="flex gap-4">
        <button
          type="submit"
          disabled={loading || success}
          className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 disabled:bg-blue-400"
        >
          {loading ? "保存中..." : "保存"}
        </button>
        <button
          type="button"
          onClick={() => window.history.back()}
          className="border border-gray-300 text-gray-700 px-6 py-2 rounded-lg hover:bg-gray-50"
        >
          取消
        </button>
      </div>
    </form>
  )
}
