"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

export function ReadingCommentForm({ readingId }: { readingId: 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/readings/${readingId}/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 (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg">ثبت نظر</CardTitle>
        <p className="text-sm text-muted-foreground">
          نظر شما پس از تأیید مدیر نمایش داده می‌شود.
        </p>
      </CardHeader>
      <CardContent>
        <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 ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
            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>
      </CardContent>
    </Card>
  );
}
