"use client";

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

type PublishedTopic = {
  id: string;
  content: string;
  submittedAt: string | null;
  publishedAt: string;
  closesAt: string | null;
  yes: number;
  no: number;
  total: number;
};

export default function KonsultacjePage() {
  const router = useRouter();
  const [topics, setTopics] = useState<PublishedTopic[]>([]);
  const [loading, setLoading] = useState(true);
  const [accessOk, setAccessOk] = useState<boolean | null>(null);

  useEffect(() => {
    async function load() {
      try {
        const codeCheck = await fetch("/api/kod", { cache: "no-store" }).then((r) => r.json()).catch(() => null);
        if (!codeCheck?.active) {
          router.push("/kod");
          setAccessOk(false);
          return;
        }
        setAccessOk(true);

        // Pobierz zamkniete tematy (wyniki) — tylko 5 najnowszych
        const res = await fetch("/api/published?limit=5", { cache: "no-store" });
        const data = await res.json();
        const list: PublishedTopic[] = Array.isArray(data) ? data : [];
        setTopics(list);
      } catch {
        setTopics([]);
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [router]);

  useEffect(() => {
    const interval = window.setInterval(async () => {
      const codeCheck = await fetch("/api/kod", { cache: "no-store" }).then((r) => r.json()).catch(() => null);
      if (!codeCheck?.active) {
        setAccessOk(false);
        router.push("/kod");
      }
    }, 15000);
    return () => window.clearInterval(interval);
  }, [router]);

  if (accessOk === false) {
    return null;
  }

  return (
    <div className="max-w-3xl mx-auto py-8 px-4">
      <a href="/" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-4">
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
        </svg>
        Powrot do menu
      </a>
      <h1 className="text-2xl sm:text-3xl font-bold">Konsultacje – wyniki</h1>
      <p className="mt-2 text-gray-700 max-w-2xl">
        Podsumowanie głosów mieszkańców w poszczególnych tematach.
        To konsultacje społeczne (bez mocy decyzyjnej).
      </p>

      {loading ? (
        <p className="mt-8 text-gray-500">Wczytywanie wyników...</p>
      ) : topics.length === 0 ? (
        <div className="mt-8 rounded-2xl border p-6 text-center">
          <p className="text-gray-600">
            Brak wynikow. Zaglosuj w zakladce{" "}
            <a href="/tematy" className="underline text-blue-600">
              Tematy do konsultacji
            </a>
            .
          </p>
        </div>
      ) : (
        <div className="mt-8 space-y-4">
          {topics.map((t) => {
            const c = { yes: t.yes, no: t.no, total: t.total };
            const yesPercent = c.total > 0 ? Math.round((c.yes / c.total) * 100) : 0;
            const noPercent = c.total > 0 ? Math.round((c.no / c.total) * 100) : 0;

            return (
              <div key={t.id} className="rounded-2xl border p-5">
                <p className="text-lg font-semibold text-gray-900 whitespace-pre-line">
                  {t.content}
                </p>
                <p className="text-sm text-gray-500 mt-1">
                  Wyslano do moderacji:{" "}
                  {t.submittedAt ? new Date(t.submittedAt).toLocaleString("pl-PL") : "brak danych"}
                </p>
                <p className="text-sm text-gray-500">
                  Wystawiono do konsultacji: {new Date(t.publishedAt).toLocaleString("pl-PL")}
                </p>
                {t.closesAt && (
                  <p className="text-sm text-gray-500">
                    Zamknieto glosowanie: {new Date(t.closesAt).toLocaleString("pl-PL")}
                  </p>
                )}
                <p className="text-xs text-gray-500 mt-1">
                  Pokazujemy 5 najnowszych wynikow. Starsze sa w historii moderatora.
                </p>

                <div className="mt-4">
                  {/* Pasek TAK */}
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-sm font-medium w-12 text-green-700">Tak</span>
                    <div className="flex-1 h-6 bg-gray-100 rounded-full overflow-hidden">
                      <div
                        className="h-6 bg-green-500 rounded-full flex items-center justify-end pr-2 transition-all duration-500"
                        style={{ width: `${Math.max(yesPercent, 2)}%` }}
                      >
                        {yesPercent > 10 && (
                          <span className="text-xs font-bold text-white">{yesPercent}%</span>
                        )}
                      </div>
                    </div>
                    <span className="text-sm font-bold w-10 text-right">{c.yes}</span>
                  </div>

                  {/* Pasek NIE */}
                  <div className="flex items-center gap-3">
                    <span className="text-sm font-medium w-12 text-red-700">Nie</span>
                    <div className="flex-1 h-6 bg-gray-100 rounded-full overflow-hidden">
                      <div
                        className="h-6 bg-red-500 rounded-full flex items-center justify-end pr-2 transition-all duration-500"
                        style={{ width: `${Math.max(noPercent, 2)}%` }}
                      >
                        {noPercent > 10 && (
                          <span className="text-xs font-bold text-white">{noPercent}%</span>
                        )}
                      </div>
                    </div>
                    <span className="text-sm font-bold w-10 text-right">{c.no}</span>
                  </div>
                </div>

                <p className="mt-3 text-sm text-gray-500">
                  Łącznie głosów: <b>{c.total}</b>
                </p>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
