"use client";

import { useState } from "react";
import type { Section, SectionOpinionPoll } from "@/types/api/section.types";
import { getStoredUser } from "@/lib/utils/persistAuth";
import { useRouter } from "next/navigation";
import { useToast } from "@/lib/toast";

async function submitPollAnswer(pollId: number, answer: string): Promise<void> {
  const userId = getStoredUser()?.id ?? 0;
  if (!userId) return;
  const { default: apiClient } = await import("@/services/api.client");
  const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
  await apiClient.post(API_ENDPOINTS.OPINION_POLL_ANSWER, {
    opinion_poll_id: pollId,
    user_id: userId,
    answer,
  });
}

const OPTION_KEYS = ["a", "b", "c", "d"] as const;
const OPTION_LABELS: Record<string, string> = { a: "A", b: "B", c: "C", d: "D" };

interface PollCardProps {
  poll: SectionOpinionPoll;
}

function PollCard({ poll }: PollCardProps) {
  const [voted, setVoted] = useState<string | null>(poll.user_ans || null);
  const { success, error: showError } = useToast();
  const router = useRouter();

  async function handleVote(optionKey: string) {
    if (voted) return; // already voted
    const userId = getStoredUser()?.id ?? 0;
    if (!userId) { showError("Sign in to vote"); router.push("/login"); return; }
    setVoted(optionKey);
    try {
      await submitPollAnswer(poll.id, optionKey);
      success("Vote recorded!");
    } catch {
      showError("Failed to submit vote");
      // Keep the local voted state — optimistic update
    }
  }

  const options = [
    { key: "a", label: poll.option_a, count: poll.option_a_count, pct: parseFloat(poll.percentage_option_a) || 0 },
    { key: "b", label: poll.option_b, count: poll.option_b_count, pct: parseFloat(poll.percentage_option_b) || 0 },
    { key: "c", label: poll.option_c, count: poll.option_c_count, pct: parseFloat(poll.percentage_option_c) || 0 },
    { key: "d", label: poll.option_d, count: poll.option_d_count, pct: parseFloat(poll.percentage_option_d) || 0 },
  ].filter((o) => o.label);

  const showResults = !!voted;
  const maxPct = Math.max(...options.map((o) => o.pct), 1);

  return (
    <div style={{
      background: "var(--surf)",
      border: "1px solid var(--line-hi)",
      borderRadius: 8,
      overflow: "hidden",
      maxWidth: 560,
      width: "100%",
    }}>
      {/* Poll header */}
      <div style={{
        borderLeft: "4px solid var(--brand)",
        padding: "1.25rem 1.5rem 1rem",
        background: "var(--cream)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", marginBottom: "0.75rem" }}>
          <div style={{
            width: 6, height: 6, borderRadius: "50%",
            background: "var(--brand)",
            animation: "pulse-ring 1.5s cubic-bezier(0.215,0.61,0.355,1) infinite",
          }} />
          <span style={{ fontFamily: "var(--mono)", fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase" as const, color: "var(--brand)" }}>
            Opinion Poll
          </span>
          {poll.channel_name && (
            <>
              <span style={{ color: "var(--line-hi)", fontSize: 14 }}>·</span>
              <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--text-3)" }}>{poll.channel_name}</span>
            </>
          )}
        </div>
        <p style={{
          fontFamily: "var(--serif)",
          fontStyle: "italic",
          fontSize: "1.1rem",
          fontWeight: 600,
          lineHeight: 1.45,
          color: "var(--ink)",
          margin: 0,
        }}>
          {poll.question}
        </p>
      </div>

      {/* Options */}
      <div style={{ padding: "1rem 1.5rem 1.25rem" }}>
        {!showResults ? (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.625rem" }}>
            {options.map((opt) => (
              <button
                key={opt.key}
                onClick={() => handleVote(opt.key)}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "0.625rem",
                  padding: "0.75rem 1rem",
                  border: "1.5px solid var(--line-hi)",
                  borderRadius: 6,
                  background: "var(--bg)",
                  cursor: "pointer",
                  textAlign: "left" as const,
                  transition: "border-color 0.15s, background 0.15s",
                  fontFamily: "var(--sans)",
                  fontSize: 14,
                  fontWeight: 500,
                  color: "var(--ink)",
                }}
              >
                <span style={{
                  width: 24, height: 24,
                  borderRadius: "50%",
                  border: "1.5px solid var(--brand-30)",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontFamily: "var(--mono)", fontSize: 10, fontWeight: 700, color: "var(--brand)",
                  flexShrink: 0,
                }}>
                  {OPTION_LABELS[opt.key]}
                </span>
                {opt.label}
              </button>
            ))}
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
            {options.map((opt) => {
              const isWinner = opt.pct === maxPct;
              const isMyVote = voted === opt.key;
              return (
                <div key={opt.key}>
                  <div style={{ display: "flex", alignItems: "center", gap: "0.625rem", marginBottom: "0.25rem" }}>
                    <span style={{
                      width: 20, height: 20,
                      borderRadius: "50%",
                      background: isMyVote ? "var(--brand)" : "var(--surf-hi)",
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "var(--mono)", fontSize: 9, fontWeight: 700,
                      color: isMyVote ? "#fff" : "var(--text-2)",
                      flexShrink: 0,
                      border: isMyVote ? "none" : "1px solid var(--line-hi)",
                    }}>
                      {OPTION_LABELS[opt.key]}
                    </span>
                    <span style={{ fontFamily: "var(--sans)", fontSize: 13, color: "var(--ink)", flex: 1 }}>{opt.label}</span>
                    <span style={{ fontFamily: "var(--mono)", fontSize: 11, fontWeight: 600, color: isWinner ? "var(--brand)" : "var(--text-2)", minWidth: 36, textAlign: "right" as const }}>
                      {opt.pct.toFixed(0)}%
                    </span>
                  </div>
                  {/* Bar */}
                  <div style={{ height: 6, background: "var(--surf-hi)", borderRadius: 3, overflow: "hidden" }}>
                    <div style={{
                      height: "100%",
                      width: `${opt.pct}%`,
                      background: isWinner ? "var(--brand)" : "var(--brand-30)",
                      borderRadius: 3,
                      transition: "width 0.8s cubic-bezier(0.34,1.56,0.64,1)",
                    }} />
                  </div>
                </div>
              );
            })}

            <div style={{ marginTop: "0.5rem", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--text-3)" }}>
                {poll.total_opinions.toLocaleString()} votes cast
              </span>
              <span style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--text-3)" }}>
                Closes {poll.closing_date}
              </span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

interface OpinionPollSectionProps { section: Section; locale: string; }

export default function OpinionPollSection({ section }: OpinionPollSectionProps) {
  const polls = section.data as SectionOpinionPoll[];
  if (polls.length === 0) return null;

  return (
    <section className="sec">
      <div className="wrap">
        <div className="sec-head">
          <div className="sec-title">
            <h2 style={{ fontFamily: "var(--italic)", fontStyle: "italic" }}>{section.title}</h2>
            {section.sub_title && <span className="count">{section.sub_title}</span>}
          </div>
        </div>

        <div style={{ display: "flex", flexWrap: "wrap" as const, gap: "1.5rem" }}>
          {polls.map((poll) => (
            <PollCard key={poll.id} poll={poll} />
          ))}
        </div>
      </div>
    </section>
  );
}
