'use client';

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

type PublishedTopic = {
  id: string;
  content: string;
  publishedAt: string;
  closesAt: string | null;
};

type VoteValue = 'yes' | 'no';
type Counts = { yes: number; no: number; total: number };

const voteLabel: Record<VoteValue, string> = {
  yes: 'Tak',
  no: 'Nie',
};

function formatRemaining(ms: number): string {
  if (ms <= 0) return 'Konsultacja zakonczona';
  const totalMinutes = Math.floor(ms / 60000);
  const days = Math.floor(totalMinutes / (60 * 24));
  const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
  const minutes = totalMinutes % 60;

  if (days > 0) return `${days}d ${hours}h ${minutes}m`;
  if (hours > 0) return `${hours}h ${minutes}m`;
  return `${minutes}m`;
}

export default function TematyPage() {
  const router = useRouter();
  const [topics, setTopics] = useState<PublishedTopic[]>([]);
  const [loading, setLoading] = useState(true);
  const [allCounts, setAllCounts] = useState<Record<string, Counts>>({});
  const [myVotes, setMyVotes] = useState<Record<string, VoteValue | null>>({});
  const [showResult, setShowResult] = useState<Record<string, boolean>>({});
  const [busyId, setBusyId] = useState<string | null>(null);
  const [msg, setMsg] = useState<Record<string, string>>({});
  const [accessOk, setAccessOk] = useState<boolean | null>(null);
  const [nowTs, setNowTs] = useState<number>(() => Date.now());

  async function refreshCounts(topicId: string) {
    try {
      const r = await fetch(`/api/votes?topicId=${encodeURIComponent(topicId)}`, { cache: 'no-store' });
      const d = await r.json();
      if (d?.ok) {
        setAllCounts((prev) => ({
          ...prev,
          [topicId]: { yes: d.counts.yes, no: d.counts.no, total: d.counts.total },
        }));
        setMyVotes((prev) => ({ ...prev, [topicId]: d.myVote ?? null }));
      }
    } catch {}
  }

  useEffect(() => {
    async function load() {
      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);

      const res = await fetch('/api/publikuj', { cache: 'no-store' });
      const data = await res.json();
      const list: PublishedTopic[] = Array.isArray(data) ? data : [];
      setTopics(list);
      setLoading(false);

      // Pobierz głosy dla każdego tematu
      await Promise.all(list.map((t) => refreshCounts(t.id)));
    }
    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]);

  useEffect(() => {
    const timer = window.setInterval(() => setNowTs(Date.now()), 30000);
    return () => window.clearInterval(timer);
  }, []);

  async function vote(topicId: string, value: VoteValue) {
    setBusyId(topicId);
    setMsg((prev) => ({ ...prev, [topicId]: '' }));
    try {
      const r = await fetch('/api/votes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ topicId, value }),
      });
      const d = await r.json();
      if (!r.ok || !d?.ok) {
        if (d?.needCode || r.status === 401 || r.status === 403) {
          // Brak kodu dostępu — przekieruj
          window.location.href = '/kod';
          return;
        }
        setMsg((prev) => ({ ...prev, [topicId]: d?.message || 'Nie udało się oddać głosu.' }));
        return;
      }
      setMyVotes((prev) => ({ ...prev, [topicId]: value }));
      setMsg((prev) => ({ ...prev, [topicId]: `Oddano głos: ${voteLabel[value]}` }));
      // Automatycznie pokaż wynik po głosowaniu
      setShowResult((prev) => ({ ...prev, [topicId]: true }));
      await refreshCounts(topicId);
    } finally {
      setBusyId(null);
    }
  }

  function toggleResult(topicId: string) {
    setShowResult((prev) => ({ ...prev, [topicId]: !prev[topicId] }));
    refreshCounts(topicId);
  }

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

  return (
    <div className="max-w-4xl 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 mb-2">Aktualne tematy do konsultacji</h1>
      <p className="mb-6 text-gray-700">
        Zagłosuj Tak lub Nie. Po oddaniu głosu zobaczysz wynik. To konsultacje społeczne (bez mocy decyzyjnej).
      </p>

      {loading ? (
        <p>Wczytywanie...</p>
      ) : topics.length === 0 ? (
        <p className="text-gray-600">Brak tematów do konsultacji.</p>
      ) : (
        <div className="space-y-4">
          {topics.map((t) => {
            const c = allCounts[t.id] ?? { yes: 0, no: 0, total: 0 };
            const voted = myVotes[t.id] != null;
            const visible = showResult[t.id] ?? false;
            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;
            const closesTs = t.closesAt ? new Date(t.closesAt).getTime() : null;
            const remainingMs = closesTs ? closesTs - nowTs : null;

            return (
              <div key={t.id} className="rounded-2xl border overflow-hidden">
                <div className="grid lg:grid-cols-[1fr_280px]">
                  {/* Lewa strona: temat + głosowanie */}
                  <div className="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-2">
                      Opublikowano: {new Date(t.publishedAt).toLocaleString('pl-PL')}
                    </p>
                    {t.closesAt && (
                      <p className="text-sm text-gray-500">
                        Glosowanie do: {new Date(t.closesAt).toLocaleString('pl-PL')}
                      </p>
                    )}
                    {remainingMs !== null && (
                      <p className="text-sm font-medium text-blue-700 mt-1">
                        Koniec glosowania za: {formatRemaining(remainingMs)}
                      </p>
                    )}

                    <div className="mt-4 flex flex-wrap items-center gap-2">
                      <button
                        className="bg-green-600 text-white px-4 py-2 rounded-full text-sm font-medium disabled:opacity-40"
                        disabled={busyId === t.id || voted}
                        onClick={() => vote(t.id, 'yes')}
                      >
                        Tak
                      </button>
                      <button
                        className="bg-red-500 text-white px-4 py-2 rounded-full text-sm font-medium disabled:opacity-40"
                        disabled={busyId === t.id || voted}
                        onClick={() => vote(t.id, 'no')}
                      >
                        Nie
                      </button>
                      <button
                        className="ml-auto text-sm text-gray-600 hover:text-gray-900 hover:underline"
                        onClick={() => toggleResult(t.id)}
                      >
                        {visible ? 'Ukryj wynik' : 'Pokaż wynik →'}
                      </button>
                    </div>

                    {msg[t.id] && (
                      <p className="mt-2 text-sm text-gray-600">{msg[t.id]}</p>
                    )}

                    {voted && (
                      <p className="mt-2 text-xs text-gray-500">
                        Twój głos: <b>{voteLabel[myVotes[t.id] as VoteValue]}</b>
                      </p>
                    )}
                  </div>

                  {/* Prawa strona: wynik tematu */}
                  {visible && (
                    <div className="bg-gray-50 border-l p-5 flex flex-col justify-center">
                      <h3 className="text-sm font-semibold text-gray-900 mb-3">Wynik tematu</h3>

                      {/* Pasek TAK */}
                      <div className="mb-2">
                        <div className="flex items-center justify-between text-sm mb-1">
                          <span className="font-medium text-green-700">Tak</span>
                          <span className="font-bold">{c.yes} ({yesPercent}%)</span>
                        </div>
                        <div className="h-4 bg-gray-200 rounded-full overflow-hidden">
                          <div
                            className="h-4 bg-green-500 rounded-full transition-all duration-500"
                            style={{ width: `${Math.max(yesPercent, 2)}%` }}
                          />
                        </div>
                      </div>

                      {/* Pasek NIE */}
                      <div className="mb-3">
                        <div className="flex items-center justify-between text-sm mb-1">
                          <span className="font-medium text-red-700">Nie</span>
                          <span className="font-bold">{c.no} ({noPercent}%)</span>
                        </div>
                        <div className="h-4 bg-gray-200 rounded-full overflow-hidden">
                          <div
                            className="h-4 bg-red-500 rounded-full transition-all duration-500"
                            style={{ width: `${Math.max(noPercent, 2)}%` }}
                          />
                        </div>
                      </div>

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