"use client";

import { useState } from "react";

export default function QuickAsk({
  contextTitle,
  contextSummary,
}: {
  contextTitle: string;
  contextSummary: string;
}) {
  const [q, setQ] = useState("");
  const [answer, setAnswer] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  async function ask() {
    setLoading(true);
    setErr(null);
    setAnswer(null);

    try {
      const res = await fetch("/api/quick-ask", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          question: q.trim(),
          contextTitle,
          contextSummary,
        }),
      });
      const data = await res.json();

      if (!res.ok || !data?.ok) {
        throw new Error(data?.message || "Błąd");
      }

      setAnswer(data.answer);
    } catch (e: any) {
      setErr(e?.message || "Błąd połączenia");
    } finally {
      setLoading(false);
    }
  }

  return (
    <section className="mt-8">
      <h3 className="text-lg font-semibold">Pomoc kontekstowa</h3>
      <p className="mt-1 text-gray-700 max-w-2xl">
        Zadaj krótkie pytanie dotyczące tej konsultacji. Otrzymasz jedną, zwięzłą odpowiedź.
      </p>

      <div className="mt-4 rounded-2xl border p-5">
        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Np. Jakie są realne opcje w tym temacie?"
            className="w-full rounded-xl border p-3 outline-none focus:ring-2 focus:ring-gray-900"
            maxLength={200}
          />
          <button
            onClick={ask}
            disabled={loading || q.trim().length < 3}
            className="rounded-full bg-gray-900 px-5 py-2.5 text-sm font-medium text-white hover:opacity-90 disabled:opacity-40"
          >
            {loading ? "..." : "Zapytaj"}
          </button>
        </div>

        {err && <p className="mt-3 text-sm text-red-600">{err}</p>}

        {answer && (
          <div className="mt-4 rounded-2xl bg-gray-50 border p-4">
            <p className="text-sm text-gray-900 whitespace-pre-wrap">{answer}</p>
            <p className="mt-3 text-xs text-gray-500">
              To jest pomoc ogólna. Stowarzyszenie analizuje stanowiska i publikuje wnioski w etapie „Wnioski".
            </p>
          </div>
        )}
      </div>
    </section>
  );
}
