"use client";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  createCategoryAction,
  updateCategoryAction,
} from "@/lib/actions/categories";
import type { CategoryKind } from "@/lib/queries/categories";
import type { Category } from "@/app/generated/prisma/client";

interface CategoryFormProps {
  kind: CategoryKind;
  category?: Category;
}

export function CategoryForm({ kind, category }: CategoryFormProps) {
  const isEdit = !!category;
  const action = isEdit
    ? updateCategoryAction.bind(null, category.id)
    : createCategoryAction;

  return (
    <form action={action} className="max-w-md space-y-4">
      <input type="hidden" name="kind" value={kind} />

      <div>
        <Label htmlFor="nameZh">分類名稱 *</Label>
        <Input
          id="nameZh"
          name="nameZh"
          defaultValue={category?.nameZh}
          required
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="slug">Slug *</Label>
        <Input
          id="slug"
          name="slug"
          defaultValue={category?.slug}
          required
          placeholder="例如：bar"
          className="mt-1"
        />
      </div>

      <div>
        <Label htmlFor="sortOrder">排序（數字越小越前）</Label>
        <Input
          id="sortOrder"
          name="sortOrder"
          type="number"
          defaultValue={category?.sortOrder ?? 0}
          className="mt-1"
        />
      </div>

      <label className="flex items-center gap-2 text-sm">
        <input
          type="checkbox"
          name="published"
          defaultChecked={category?.published ?? true}
          className="size-4 rounded border-input"
        />
        已啟用
      </label>

      <Button type="submit" className="bg-primary text-primary-foreground">
        {isEdit ? "更新分類" : "新增分類"}
      </Button>
    </form>
  );
}