"use client";

import { useEffect, useState } from "react";

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

interface HistoryEntry {
  id: string;
  question: string;
  answer: string;
  sources: Source[];
  confidence: string | null;
  feedback: "up" | "down" | null;
  created_at: string;
}

export default function HistoryClient() {
  const [history, setHistory] = useState<HistoryEntry[]>([]);

  async function load() {
    const res = await fetch("/api/history");
    const data = await res.json();
    setHistory(data.history || []);
  }

  useEffect(() => {
    load();
  }, []);

  async function clearHistory() {
    if (!confirm("Na pewno wyczyścić całą historię pytań?")) return;
    await fetch("/api/history", { method: "DELETE" });
    load();
  }

  async function setFeedback(id: string, value: "up" | "down") {
    const entry = history.find((h) => h.id === id);
    const newValue = entry?.feedback === value ? null : value;
    setHistory((prev) => prev.map((h) => (h.id === id ? { ...h, feedback: newValue } : h)));
    await fetch("/api/history/feedback", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, value: newValue }),
    });
  }

  return (
    <div className="max-w-2xl mx-auto px-6 py-8">
      <div className="flex items-center justify-between">
        <h1 className="text-lg font-semibold text-slate-900">Historia pytań</h1>
        <button
          onClick={clearHistory}
          className="text-xs px-3 py-1.5 rounded-md bg-slate-100 text-slate-600 hover:bg-slate-200"
        >
          Wyczyść historię
        </button>
      </div>
      <p className="text-sm text-slate-500 mt-1">
        Wszystkie pytania zadane asystentowi przez Ciebie — pomaga zauważyć, o co pytasz najczęściej.
      </p>

      <div className="mt-6 space-y-4">
        {history.length === 0 && (
          <div className="text-sm text-slate-400">
            Brak historii — zadaj pierwsze pytanie w zakładce Asystent AI.
          </div>
        )}
        {history.map((h) => (
          <div key={h.id} className="rounded-xl border border-slate-200 bg-white p-4">
            <div className="text-xs text-slate-400">{new Date(h.created_at).toLocaleString("pl-PL")}</div>
            <div className="mt-1 font-medium text-slate-900 text-sm">{h.question}</div>
            <div className="mt-2 text-sm text-slate-700 whitespace-pre-wrap">{h.answer}</div>
            <div className="mt-3 flex items-center gap-2">
              <span className="text-xs text-slate-500">Trafna odpowiedź?</span>
              <button
                onClick={() => setFeedback(h.id, "up")}
                className={`text-sm px-2 py-1 rounded-md border ${
                  h.feedback === "up" ? "bg-emerald-50 border-emerald-300" : "bg-slate-50 border-slate-200"
                }`}
              >
                👍
              </button>
              <button
                onClick={() => setFeedback(h.id, "down")}
                className={`text-sm px-2 py-1 rounded-md border ${
                  h.feedback === "down" ? "bg-red-50 border-red-300" : "bg-slate-50 border-slate-200"
                }`}
              >
                👎
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
