"use client";

import { useEffect, useState } from "react";

type Category = "organizacja" | "bezpieczenstwo" | "koszty" | "inne";

const categoryLabel: Record<Category, string> = {
  organizacja: "Organizacja",
  bezpieczenstwo: "Bezpieczeństwo",
  koszty: "Koszty",
  inne: "Inne",
};

type Quote = {
  id: string;
  category: Category;
  text: string;
  createdAt: string;
};

export default function PublicQuotes({ consultationId }: { consultationId: string }) {
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [loading, setLoading] = useState(true);

  async function load() {
    setLoading(true);
    try {
      const res = await fetch(
        `/api/stanowiska?consultationId=${encodeURIComponent(consultationId)}`
      );
      const data = await res.json();
      setQuotes(Array.isArray(data?.publicQuotes) ? data.publicQuotes : []);
    } catch {
      setQuotes([]);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [consultationId]);

  if (loading) {
    return (
      <section className="mt-8">
        <h3 className="text-lg font-semibold">Wybrane głosy mieszkańców</h3>
        <p className="mt-2 text-gray-600">Ładowanie…</p>
      </section>
    );
  }

  if (quotes.length === 0) return null;

  return (
    <section className="mt-8">
      <h3 className="text-lg font-semibold">Wybrane głosy mieszkańców</h3>
      <p className="mt-1 text-gray-700 max-w-2xl">
        Cytaty wybrane i zaakceptowane przez stowarzyszenie (redakcja/anonimizacja).
      </p>

      <div className="mt-4 space-y-3">
        {quotes.map((q) => (
          <div key={q.id} className="rounded-2xl border p-5 bg-gray-50">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <span className="text-xs font-medium rounded-full border px-3 py-1 bg-white">
                {categoryLabel[q.category]}
              </span>
              <span className="text-xs text-gray-500">
                {new Date(q.createdAt).toLocaleDateString("pl-PL")}
              </span>
            </div>

            <p className="mt-3 text-gray-900 whitespace-pre-wrap">„{q.text}"</p>
          </div>
        ))}
      </div>
    </section>
  );
}
