"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";

export function SitePageForm({
  keyName,
  initial,
}: {
  keyName: string;
  initial?: { titleFa: string; content: string };
}) {
  const router = useRouter();
  const [titleFa, setTitleFa] = useState(initial?.titleFa ?? "");
  const [content, setContent] = useState(initial?.content ?? "");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    await fetch(`/api/admin/pages/${keyName}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ titleFa, content }),
    });
    setLoading(false);
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label>عنوان</Label>
        <Input value={titleFa} onChange={(e) => setTitleFa(e.target.value)} className="mt-1" />
      </div>
      <div>
        <Label>محتوا</Label>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          className="flex min-h-[300px] 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>
  );
}
