"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { Trophy, Shuffle, RotateCcw, Ticket, Users, ShieldCheck, Code2 } from "lucide-react";

type TicketData = {
  ticketNum: string;
  name: string;
};

type Phase = "idle" | "spinning" | "slowing" | "winner";

/** r uniforme en [0, 2³²) y índice equiprobable en [0, n) */
function pickIndexCrypto(n: number): { randomUint: number; index: number } {
  const buf = new Uint32Array(1);
  crypto.getRandomValues(buf);
  const r = buf[0];
  const index = Math.floor((r / 0x1_0000_0000) * n);
  return { randomUint: r, index: Math.min(index, n - 1) };
}

type DrawProof = {
  randomUint: number;
  total: number;
  index: number;
  formula: string;
};

export default function AdminTombolaClient({
  tickets,
  participantCount,
}: {
  tickets: TicketData[];
  participantCount: number;
}) {
  const [phase, setPhase] = useState<Phase>("idle");
  const [displayCode, setDisplayCode] = useState("--------");
  const [winner, setWinner] = useState<TicketData | null>(null);
  const [drawProof, setDrawProof] = useState<DrawProof | null>(null);
  const [particles, setParticles] = useState<{ id: number; x: number; y: number; color: string }[]>([]);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);
  const winnerRef = useRef<TicketData | null>(null);
  const proofRef = useRef<DrawProof | null>(null);

  const clearTimers = useCallback(() => {
    if (intervalRef.current) clearInterval(intervalRef.current);
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
  }, []);

  useEffect(() => () => clearTimers(), [clearTimers]);

  const randomCode = useCallback(() => {
    if (tickets.length === 0) return "SIN-TICKETS";
    return tickets[Math.floor(Math.random() * tickets.length)].ticketNum;
  }, [tickets]);

  const launchParticles = useCallback(() => {
    const colors = ["#39ff14", "#00d4ff", "#bf5af2", "#ff6b35", "#ffd700", "#ff3399"];
    const newParticles = Array.from({ length: 40 }, (_, i) => ({
      id: i,
      x: 20 + Math.random() * 60,
      y: 20 + Math.random() * 60,
      color: colors[Math.floor(Math.random() * colors.length)],
    }));
    setParticles(newParticles);
    setTimeout(() => setParticles([]), 3000);
  }, []);

  const startDraw = useCallback(() => {
    if (tickets.length === 0 || phase !== "idle") return;

    setWinner(null);
    setDrawProof(null);
    setPhase("spinning");

    const n = tickets.length;
    const { randomUint, index } = pickIndexCrypto(n);
    const selected = tickets[index];
    const formula = `índice = floor((${randomUint} / 2³²) × ${n}) = ${index}`;
    proofRef.current = { randomUint, total: n, index, formula };
    winnerRef.current = selected;

    // Fase 1: giro rápido (2.5s)
    let fast = true;
    intervalRef.current = setInterval(() => {
      setDisplayCode(randomCode());
    }, fast ? 50 : 50);

    // Fase 2: girar más lento
    timeoutRef.current = setTimeout(() => {
      setPhase("slowing");
      clearInterval(intervalRef.current!);
      let delay = 60;
      const slowDown = () => {
        setDisplayCode(randomCode());
        delay += 40;
        if (delay < 500) {
          intervalRef.current = setTimeout(slowDown, delay);
        } else {
          // Fase 3: revelar ganador
          setDisplayCode(winnerRef.current!.ticketNum);
          setWinner(winnerRef.current);
          if (proofRef.current) setDrawProof(proofRef.current);
          setPhase("winner");
          launchParticles();
        }
      };
      slowDown();
    }, 2500);
  }, [tickets, phase, randomCode, launchParticles]);

  const reset = useCallback(() => {
    clearTimers();
    setPhase("idle");
    setWinner(null);
    setDrawProof(null);
    setDisplayCode("--------");
    setParticles([]);
    winnerRef.current = null;
    proofRef.current = null;
  }, [clearTimers]);

  const isSpinning = phase === "spinning" || phase === "slowing";

  return (
    <div className="min-h-screen flex flex-col items-center justify-start py-8 px-4 relative overflow-hidden">

      {/* Partículas de confeti */}
      {particles.map((p) => (
        <span
          key={p.id}
          className="absolute w-3 h-3 rounded-full pointer-events-none animate-bounce"
          style={{
            left: `${p.x}%`,
            top: `${p.y}%`,
            backgroundColor: p.color,
            boxShadow: `0 0 8px ${p.color}`,
            animationDuration: `${0.4 + Math.random() * 0.6}s`,
            animationDelay: `${Math.random() * 0.5}s`,
          }}
        />
      ))}

      {/* Header */}
      <div className="text-center mb-10 z-10">
        <div className="inline-flex items-center gap-3 mb-3">
          <Trophy className="w-8 h-8 text-yellow-400 drop-shadow-[0_0_12px_rgba(250,204,21,0.8)]" />
          <h1 className="text-4xl font-black text-transparent bg-clip-text bg-gradient-to-r from-yellow-400 via-orange-400 to-pink-500">
            TÓMBOLA
          </h1>
          <Trophy className="w-8 h-8 text-yellow-400 drop-shadow-[0_0_12px_rgba(250,204,21,0.8)]" />
        </div>
        <p className="text-gray-400 text-sm">Sorteo oficial — solo visible desde el panel de administración</p>
      </div>

      {/* Stats */}
      <div className="flex gap-6 mb-10 z-10">
        <div className="glass-panel px-6 py-3 rounded-xl flex items-center gap-2">
          <Ticket className="w-5 h-5 text-neon-blue" />
          <span className="text-white font-bold text-lg">{tickets.length}</span>
          <span className="text-gray-400 text-sm">tickets</span>
        </div>
        <div className="glass-panel px-6 py-3 rounded-xl flex items-center gap-2">
          <Users className="w-5 h-5 text-neon-purple" />
          <span className="text-white font-bold text-lg">
            {participantCount}
          </span>
          <span className="text-gray-400 text-sm">participantes</span>
        </div>
      </div>

      {/* Transparencia: algoritmo visible */}
      <div className="z-10 w-full max-w-lg mb-8">
        <div className="glass-panel rounded-2xl p-6 border border-emerald-500/20 bg-emerald-500/[0.03]">
          <h2 className="text-sm font-black uppercase tracking-widest text-emerald-400 mb-4 flex items-center gap-2">
            <ShieldCheck className="w-5 h-5 shrink-0" />
            Transparencia del sorteo
          </h2>
          <p className="text-gray-400 text-sm mb-4 leading-relaxed">
            El ganador no se elige a mano: se calcula con un número aleatorio del navegador (
            <code className="text-neon-blue text-xs">crypto.getRandomValues</code>
            , estándar Web Crypto) sobre la lista ordenada de tickets pagados que ves abajo.
          </p>
          <ol className="text-sm text-gray-300 space-y-2 mb-4 list-decimal list-inside marker:text-emerald-400">
            <li>
              <span className="text-gray-400">Se arma la lista </span>
              <code className="text-xs text-white bg-white/10 px-1.5 py-0.5 rounded">L</code>
              <span className="text-gray-400">: todos los códigos de órdenes con estado PAID, en el mismo orden que la tabla (por fecha de creación del ticket).</span>
            </li>
            <li>
              <span className="text-gray-400">Se obtiene un entero </span>
              <code className="text-xs text-white bg-white/10 px-1.5 py-0.5 rounded">r</code>
              <span className="text-gray-400"> uniforme entre 0 y 2³² − 1.</span>
            </li>
            <li>
              <span className="text-gray-400">Se calcula el índice ganador (cada posición tiene la misma probabilidad):</span>
            </li>
          </ol>
          <div className="rounded-xl bg-black/50 border border-white/10 p-4 font-mono text-xs sm:text-sm text-left overflow-x-auto">
            <div className="flex items-start gap-2 text-gray-500 mb-2">
              <Code2 className="w-4 h-4 shrink-0 mt-0.5" />
              <span>Pseudocódigo (equivalente a lo que ejecuta esta pantalla)</span>
            </div>
            <pre className="text-emerald-300/90 whitespace-pre-wrap break-all leading-relaxed">
{`n = L.length
[r] = crypto.getRandomValues(new Uint32Array(1))
r = r[0]                    // 0 … 2³² − 1
índice = floor((r / 2³²) × n)
ganador = L[índice]`}
            </pre>
          </div>
          {drawProof && winner && (
            <div className="mt-4 rounded-xl border border-yellow-400/30 bg-yellow-400/5 p-4 text-sm">
              <p className="text-yellow-400/90 font-bold uppercase tracking-wide text-xs mb-3">Comprobante de este sorteo</p>
              <ul className="space-y-2 text-gray-300 font-mono text-xs break-all">
                <li>
                  <span className="text-gray-500">r (aleatorio) = </span>
                  <span className="text-white">{drawProof.randomUint}</span>
                </li>
                <li>
                  <span className="text-gray-500">|L| = </span>
                  <span className="text-white">{drawProof.total}</span>
                </li>
                <li>
                  <span className="text-gray-500">índice = </span>
                  <span className="text-white">{drawProof.index}</span>
                  <span className="text-gray-500"> → </span>
                  <span className="text-neon-blue">{winner.ticketNum}</span>
                </li>
                <li className="text-gray-500 pt-1 border-t border-white/10">{drawProof.formula}</li>
              </ul>
            </div>
          )}
        </div>
      </div>

      {/* Máquina principal */}
      <div className="z-10 w-full max-w-lg">
        <div className="glass-panel rounded-3xl p-8 border border-white/10 shadow-2xl relative">

          {/* Glow de fondo dinámico */}
          <div
            className={`absolute inset-0 rounded-3xl transition-all duration-500 pointer-events-none ${
              phase === "winner"
                ? "bg-gradient-to-br from-yellow-500/10 via-orange-500/5 to-pink-500/10"
                : isSpinning
                ? "bg-gradient-to-br from-neon-blue/10 via-neon-purple/5 to-neon-blue/10"
                : "bg-transparent"
            }`}
          />

          {/* Display del código */}
          <div className="relative mb-8">
            <div
              className={`rounded-2xl border-2 py-8 px-6 text-center transition-all duration-300 ${
                phase === "winner"
                  ? "border-yellow-400/60 bg-yellow-400/5 shadow-[0_0_40px_rgba(250,204,21,0.3)]"
                  : isSpinning
                  ? "border-neon-blue/60 bg-neon-blue/5 shadow-[0_0_30px_rgba(0,212,255,0.25)]"
                  : "border-white/10 bg-white/5"
              }`}
            >
              <p className="text-xs uppercase tracking-widest text-gray-500 mb-3">
                {phase === "winner" ? "🏆 Ticket Ganador" : phase === "idle" ? "Ticket sorteado" : "Sorteando..."}
              </p>
              <p
                className={`font-mono font-black tracking-widest transition-all duration-200 ${
                  phase === "winner"
                    ? "text-4xl text-yellow-400 drop-shadow-[0_0_20px_rgba(250,204,21,0.8)]"
                    : isSpinning
                    ? "text-3xl text-neon-blue drop-shadow-[0_0_12px_rgba(0,212,255,0.6)]"
                    : "text-3xl text-gray-500"
                }`}
              >
                {displayCode}
              </p>
            </div>
          </div>

          {/* Nombre del ganador */}
          <div
            className={`mb-8 text-center transition-all duration-700 ${
              phase === "winner" ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"
            }`}
          >
            {winner && (
              <div className="rounded-2xl border border-yellow-400/30 bg-yellow-400/5 py-6 px-4">
                <p className="text-xs uppercase tracking-widest text-yellow-400/70 mb-2">Ganador</p>
                <p className="text-3xl font-black text-white drop-shadow-[0_0_16px_rgba(255,255,255,0.4)] leading-tight">
                  {winner.name}
                </p>
              </div>
            )}
          </div>

          {/* Botones */}
          <div className="flex gap-3">
            {phase !== "winner" ? (
              <button
                onClick={startDraw}
                disabled={isSpinning || tickets.length === 0}
                className={`flex-1 flex items-center justify-center gap-3 py-4 rounded-xl font-black text-lg uppercase tracking-wider transition-all duration-300 ${
                  isSpinning || tickets.length === 0
                    ? "bg-white/5 text-gray-600 cursor-not-allowed"
                    : "bg-gradient-to-r from-yellow-500 to-orange-500 hover:from-yellow-400 hover:to-orange-400 text-black shadow-[0_0_30px_rgba(250,204,21,0.4)] hover:shadow-[0_0_50px_rgba(250,204,21,0.6)] hover:scale-105 active:scale-95"
                }`}
              >
                <Shuffle className={`w-6 h-6 ${isSpinning ? "animate-spin" : ""}`} />
                {isSpinning ? "Sorteando..." : "¡Sortear!"}
              </button>
            ) : (
              <>
                <button
                  onClick={reset}
                  className="flex-1 flex items-center justify-center gap-2 py-4 rounded-xl font-bold text-base uppercase tracking-wider bg-white/10 hover:bg-white/15 text-white transition-all hover:scale-105 active:scale-95"
                >
                  <RotateCcw className="w-5 h-5" />
                  Nuevo Sorteo
                </button>
              </>
            )}
          </div>

          {tickets.length === 0 && (
            <p className="text-center text-red-400 text-sm mt-4">
              No hay tickets pagados disponibles para sortear.
            </p>
          )}
        </div>
      </div>

      {/* Lista de participantes */}
      {tickets.length > 0 && (
        <div className="z-10 w-full max-w-lg mt-8">
          <div className="glass-panel rounded-2xl p-6 border border-white/10">
            <h3 className="text-sm font-bold uppercase tracking-widest text-gray-400 mb-4 flex items-center gap-2">
              <Ticket className="w-4 h-4" />
              Todos los tickets participantes
            </h3>
            <div className="max-h-64 overflow-y-auto space-y-1 pr-1 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent">
              {tickets.map((t) => (
                <div
                  key={t.ticketNum}
                  className={`flex items-center justify-between px-3 py-2 rounded-lg transition-all duration-300 ${
                    winner?.ticketNum === t.ticketNum
                      ? "bg-yellow-400/15 border border-yellow-400/40"
                      : "bg-white/5 hover:bg-white/8"
                  }`}
                >
                  <span className="font-mono text-xs text-neon-blue font-bold">{t.ticketNum}</span>
                  <span className="text-gray-300 text-sm truncate ml-4 max-w-[180px]">{t.name}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
