"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";

export function BlogPostCommentForm({ slug }: { slug: string }) {
  const router = useRouter();
  const [content, setContent] = useState("");
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!content.trim()) return;
    setLoading(true);
    setMessage(null);
    try {
      const res = await fetch(`/api/blog/${slug}/comments`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ content: content.trim() }),
      });
      const data = await res.json();
      if (!res.ok) {
        setMessage({ type: "error", text: data.error ?? "خطا در ثبت نظر" });
        return;
      }
      setMessage({ type: "success", text: "نظر شما پس از تأیید نمایش داده می‌شود." });
      setContent("");
      router.refresh();
    } catch {
      setMessage({ type: "error", text: "خطایی رخ داد" });
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder="نظر خود را بنویسید..."
        className="flex min-h-[100px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
        maxLength={2000}
      />
      {message && (
        <p
          className={`text-sm ${message.type === "success" ? "text-green-600" : "text-destructive"}`}
          role="alert"
        >
          {message.text}
        </p>
      )}
      <Button type="submit" disabled={loading}>
        {loading ? "در حال ارسال..." : "ارسال نظر"}
      </Button>
    </form>
  );
}
