"use client";

import { useEffect, useState } from "react";
import type { Topic } from "@/data/topics";

type VoteValue = "yes" | "no" | "unsure";
type Counts = { yes: number; no: number; unsure: number; total: number };

const label: Record<VoteValue, string> = {
  yes: "Tak",
  no: "Nie",
  unsure: "Nie wiem",
};

export default function TopicVoteCard({ topic }: { topic: Topic }) {
  const [counts, setCounts] = useState<Counts>({ yes: 0, no: 0, unsure: 0, total: 0 });
  const [myVote, setMyVote] = useState<VoteValue | null>(null);
  const [loading, setLoading] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  async function refresh() {
    const r = await fetch(`/api/votes?topicId=${encodeURIComponent(topic.id)}`, { cache: "no-store" });
    const d = await r.json();
    if (d?.ok) {
      setCounts(d.counts);
      setMyVote(d.myVote ?? null);
    }
  }

  useEffect(() => {
    // zapewnij cookie voter_id (anonimowe)
    fetch("/api/voter").catch(() => {});
    refresh();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [topic.id]);

  async function vote(value: VoteValue) {
    if (myVote) return; // już oddany

    setLoading(true);
    setMsg(null);

    try {
      const r = await fetch("/api/votes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ topicId: topic.id, value }),
      });
      const d = await r.json();

      if (!r.ok || !d?.ok) {
        setMsg(d?.message || "Nie udało się oddać głosu.");
        return;
      }

      setMyVote(value);
      setMsg(`Oddano głos: ${label[value]}.`);
      await refresh();
    } finally {
      setLoading(false);
    }
  }

  const disabled = loading || !!myVote;

  return (
    <div className="rounded-2xl border p-5">
      <h2 className="text-lg font-semibold">{topic.title}</h2>
      <p className="mt-2 text-gray-900">{topic.question}</p>

      <div className="mt-4 flex flex-wrap gap-2">
        <button
          className="rounded-full bg-gray-900 text-white px-4 py-2 text-sm disabled:opacity-40"
          disabled={disabled}
          onClick={() => vote("yes")}
        >
          Tak
        </button>

        <button
          className="rounded-full border px-4 py-2 text-sm disabled:opacity-40"
          disabled={disabled}
          onClick={() => vote("no")}
        >
          Nie
        </button>

        <button
          className="rounded-full border px-4 py-2 text-sm disabled:opacity-40"
          disabled={disabled}
          onClick={() => vote("unsure")}
        >
          Nie wiem
        </button>
      </div>

      {/* komunikat i wybór */}
      {myVote && (
        <div className="mt-4 rounded-2xl border bg-gray-50 p-4">
          <p className="text-sm text-gray-900">
            <b>Oddano głos:</b> {label[myVote]}
          </p>
          <p className="mt-1 text-xs text-gray-600">
            Ten temat jest liczony jako konsultacja (bez mocy decyzyjnej).
          </p>
        </div>
      )}

      {msg && !myVote && <p className="mt-3 text-sm text-gray-600">{msg}</p>}

      <div className="mt-4 text-sm text-gray-700">
        Wynik (MVP): Tak <b>{counts.yes}</b> • Nie <b>{counts.no}</b> • Nie wiem <b>{counts.unsure}</b> • Razem{" "}
        <b>{counts.total}</b>
      </div>
    </div>
  );
}
