"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { toast } from "sonner";

const categories = [
  { value: "general", label: "通用" },
  { value: "gameplay", label: "游戏玩法" },
  { value: "ui", label: "界面增强" },
  { value: "combat", label: "战斗" },
  { value: "raid", label: "团队副本" },
  { value: "pvp", label: "PvP" },
  { value: "tradeskill", label: "专业技能" },
  { value: "utility", label: "实用工具" },
];

interface AddonFormProps {
  initialData?: {
    id: string;
    name: string;
    slug: string;
    summary: string;
    description: string;
    iconUrl: string | null;
    category: string;
    published: boolean;
  };
}

export function AddonForm({ initialData }: AddonFormProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const isEdit = !!initialData;

  function generateSlug(name: string) {
    return name
      .toLowerCase()
      .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, "-")
      .replace(/^-|-$/g, "");
  }

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);

    const formData = new FormData(e.currentTarget);
    const data = {
      name: formData.get("name"),
      slug: formData.get("slug"),
      summary: formData.get("summary"),
      description: formData.get("description"),
      iconUrl: formData.get("iconUrl") || null,
      category: formData.get("category"),
      published: formData.get("published") === "on",
    };

    const url = isEdit ? `/api/addons/${initialData.id}` : "/api/addons";
    const method = isEdit ? "PUT" : "POST";

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

    if (res.ok) {
      toast.success(isEdit ? "更新成功" : "创建成功");
      router.push("/admin/addons");
      router.refresh();
    } else {
      const err = await res.json();
      toast.error(err.error || "操作失败");
    }

    setLoading(false);
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{isEdit ? "编辑插件" : "新建插件"}</CardTitle>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="name">插件名称 *</Label>
              <Input
                id="name"
                name="name"
                required
                defaultValue={initialData?.name}
                onChange={(e) => {
                  if (!isEdit) {
                    const slugInput = document.getElementById(
                      "slug"
                    ) as HTMLInputElement;
                    if (slugInput) slugInput.value = generateSlug(e.target.value);
                  }
                }}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="slug">Slug (URL 标识) *</Label>
              <Input
                id="slug"
                name="slug"
                required
                defaultValue={initialData?.slug}
                pattern="[a-z0-9-]+"
                title="只能包含小写字母、数字和连字符"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="summary">简介 *</Label>
            <Input
              id="summary"
              name="summary"
              required
              defaultValue={initialData?.summary}
              placeholder="一句话描述插件功能"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">详细描述 (支持 Markdown)</Label>
            <Textarea
              id="description"
              name="description"
              rows={12}
              defaultValue={initialData?.description}
              placeholder="# 插件名称&#10;&#10;详细描述..."
            />
          </div>

          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="iconUrl">图标 URL</Label>
              <Input
                id="iconUrl"
                name="iconUrl"
                defaultValue={initialData?.iconUrl || ""}
                placeholder="https://example.com/icon.png"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="category">分类</Label>
              <Select
                name="category"
                defaultValue={initialData?.category || "general"}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {categories.map((cat) => (
                    <SelectItem key={cat.value} value={cat.value}>
                      {cat.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="published"
              name="published"
              defaultChecked={initialData?.published ?? false}
              className="h-4 w-4 rounded border-input"
            />
            <Label htmlFor="published">发布（公开显示）</Label>
          </div>

          <div className="flex gap-3">
            <Button type="submit" disabled={loading}>
              {loading ? "保存中..." : isEdit ? "更新" : "创建"}
            </Button>
            <Button
              type="button"
              variant="outline"
              onClick={() => router.back()}
            >
              取消
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
