"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

type Props = {
  token: string;
  entityType: "task" | "deliverable";
  entityId: string;
};

export function CommentForm({ token, entityType, entityId }: Props) {
  const router = useRouter();
  const [body, setBody] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!body.trim()) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/client/comment", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, entity_type: entityType, entity_id: entityId, body }),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error ?? "Errore durante l'invio");
        return;
      }
      setBody("");
      router.refresh(); // Re-fetch Server Component to show new comment
    } catch {
      setError("Errore di rete");
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="mt-3 flex gap-2 items-end">
      <Textarea
        value={body}
        onChange={(e) => setBody(e.target.value)}
        placeholder="Lascia un commento..."
        rows={2}
        className="text-sm resize-none flex-1"
      />
      <div className="flex flex-col justify-end">
        <Button
          type="submit"
          size="sm"
          disabled={loading || !body.trim()}
          className="text-xs"
        >
          {loading ? "Invio..." : "Invia"}
        </Button>
      </div>
      {error && <p className="text-xs text-red-500 mt-1">{error}</p>}
    </form>
  );
}