"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";

interface Source {
  file: string;
  paragraph: string;
  score: number;
}

const CONFIDENCE_STYLE: Record<string, string> = {
  wysoka: "bg-emerald-50 text-emerald-700 border-emerald-200",
  średnia: "bg-amber-50 text-amber-700 border-amber-200",
  niska: "bg-amber-50 text-amber-700 border-amber-200",
  brak: "bg-slate-100 text-slate-500 border-slate-200",
};

export default function ChatClient() {
  const searchParams = useSearchParams();
  const [question, setQuestion] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [answer, setAnswer] = useState<string | null>(null);
  const [sources, setSources] = useState<Source[]>([]);
  const [confidence, setConfidence] = useState<string | null>(null);
  const [historyId, setHistoryId] = useState<string | null>(null);
  const [feedback, setFeedback] = useState<"up" | "down" | null>(null);

  useEffect(() => {
    const client = searchParams.get("client");
    const product = searchParams.get("product");
    const insurer = searchParams.get("insurer");
    if (client) {
      let prefix = `Klient: ${client}`;
      if (product) prefix += ` — produkt: ${product}`;
      if (insurer) prefix += ` — towarzystwo: ${insurer}`;
      prefix += ".\nPytanie: ";
      setQuestion(prefix);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  async function ask() {
    if (!question.trim()) return;
    setLoading(true);
    setError(null);
    setAnswer(null);
    setSources([]);
    setConfidence(null);
    setHistoryId(null);
    setFeedback(null);

    try {
      const res = await fetch("/api/ask", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Nieznany błąd.");
        return;
      }
      setAnswer(data.answer);
      setSources(data.sources || []);
      setConfidence(data.confidence);
      setHistoryId(data.historyId);
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }

  async function sendFeedback(value: "up" | "down") {
    if (!historyId) return;
    const newValue = feedback === value ? null : value;
    setFeedback(newValue);
    await fetch("/api/history/feedback", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: historyId, value: newValue }),
    });
  }

  return (
    <div className="max-w-2xl mx-auto px-6 py-8">
      <h1 className="text-lg font-semibold text-slate-900">Asystent AI</h1>
      <p className="text-sm text-slate-500 mt-1">
        Zadaj pytanie o OWU w naturalnym języku. Każdą odpowiedź zweryfikuj z oryginałem dokumentu.
      </p>

      <textarea
        value={question}
        onChange={(e) => setQuestion(e.target.value)}
        placeholder="np. Czy AC obejmuje szkodę na parkingu?"
        rows={3}
        className="mt-4 w-full rounded-lg border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 resize-y"
      />
      <div className="mt-2">
        <button
          onClick={ask}
          disabled={loading}
          className="rounded-lg bg-indigo-600 text-white text-sm font-medium px-4 py-2 hover:bg-indigo-700 disabled:opacity-60"
        >
          {loading ? "Szukam odpowiedzi..." : "Zapytaj"}
        </button>
      </div>

      {error && (
        <div className="mt-4 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm px-3 py-2">
          {error}
        </div>
      )}

      {answer && (
        <div className="mt-6 rounded-xl border border-slate-200 bg-white p-4">
          <p className="text-sm text-slate-800 whitespace-pre-wrap">{answer}</p>

          <div className="mt-4 flex items-center gap-2">
            <span className="text-xs text-slate-500">Trafność w bazie:</span>
            <span
              className={`text-xs px-2 py-0.5 rounded-full border ${
                CONFIDENCE_STYLE[confidence || "brak"]
              }`}
            >
              {confidence}
            </span>
          </div>

          {historyId && (
            <div className="mt-3 flex items-center gap-2">
              <span className="text-xs text-slate-500">Trafna odpowiedź?</span>
              <button
                onClick={() => sendFeedback("up")}
                className={`text-sm px-2 py-1 rounded-md border ${
                  feedback === "up"
                    ? "bg-emerald-50 border-emerald-300"
                    : "bg-slate-50 border-slate-200"
                }`}
              >
                👍
              </button>
              <button
                onClick={() => sendFeedback("down")}
                className={`text-sm px-2 py-1 rounded-md border ${
                  feedback === "down" ? "bg-red-50 border-red-300" : "bg-slate-50 border-slate-200"
                }`}
              >
                👎
              </button>
            </div>
          )}

          {sources.length > 0 && (
            <div className="mt-4 text-xs text-slate-500 space-y-1">
              <div className="font-medium text-slate-600">Znalezione fragmenty:</div>
              {sources.map((s, i) => (
                <div key={i}>
                  • {s.file} — {s.paragraph} (trafność {s.score})
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
