"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import type { TarotCard } from "@prisma/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function CardEditForm({ card }: { card: TarotCard }) {
  const router = useRouter();
  const [nameFa, setNameFa] = useState(card.nameFa);
  const [slug, setSlug] = useState(card.slug);
  const [meaningShort, setMeaningShort] = useState(card.meaningShort ?? "");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    await fetch(`/api/admin/cards/${card.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        nameFa,
        slug,
        meaningShort: meaningShort || undefined,
      }),
    });
    setLoading(false);
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label>نام (فارسی)</Label>
        <Input value={nameFa} onChange={(e) => setNameFa(e.target.value)} className="mt-1" />
      </div>
      <div>
        <Label>اسلاگ</Label>
        <Input value={slug} onChange={(e) => setSlug(e.target.value)} className="mt-1" />
      </div>
      <div>
        <Label>معنی کوتاه (اختیاری)</Label>
        <textarea
          value={meaningShort}
          onChange={(e) => setMeaningShort(e.target.value)}
          className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm mt-1"
        />
      </div>
      <Button type="submit" disabled={loading}>
        {loading ? "در حال ذخیره..." : "ذخیره"}
      </Button>
    </form>
  );
}
