"use client";

import Image from "next/image";
import Link from "next/link";
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import {
  ArrowLeft,
  BadgeEuro,
  Check,
  Clock3,
  Flame,
  Gift,
  ShieldCheck,
  TicketCheck,
  TrendingUp,
  Trophy,
  UserRound
} from "lucide-react";
import { notifyWalletUpdated } from "@/lib/client-events";

type PresenceSnapshot = {
  rules: {
    baseAmount: string;
    dailyIncrease: string;
    maxAmount: string;
    resetAt: string;
    activeWagerRequirement: string;
    drawTime: string;
    claimHours: number;
    doubleTicketStreak: number;
  };
  currentDraw: {
    id: string;
    drawDate: string;
    drawAt: string;
    claimUntil: string;
    amount: string;
    currency: string;
    status: "CLAIMABLE" | "CLAIMED" | "EXPIRED" | "NO_ELIGIBLE";
    winner: { id: string; username: string } | null;
    claimedAt: string | null;
  };
  nextDraw: {
    drawDate: string;
    drawAt: string;
    amountIfUnclaimed: string;
  };
  user: {
    authenticated: true;
    isWinner: boolean;
    canClaim: boolean;
    currentEntry: { tickets: number; loginStreakDays: number; activeWagerAmount: string } | null;
    nextDraw: {
      hasLoginTicket: boolean;
      eligible: boolean;
      tickets: number;
      loginStreakDays: number;
      activeWagerAmount: string;
      missingWagerAmount: string;
    };
  } | null;
};

const progression = [10, 15, 20, 25, 30, 35, 40, 45, 50];

export function PresenceJackpotExperience() {
  const [snapshot, setSnapshot] = useState<PresenceSnapshot | null>(null);
  const [loading, setLoading] = useState(true);
  const [claiming, setClaiming] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const currentAmount = Number(snapshot?.currentDraw.amount ?? 0);

  useEffect(() => {
    void load();
  }, []);

  async function load() {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/promotions/presence-jackpot", { cache: "no-store" });
      const payload = await response.json();
      if (!response.ok || !payload.ok) {
        throw new Error(payload.error?.message ?? "Jackpot indisponible.");
      }
      setSnapshot(payload.data);
    } catch (loadError) {
      setError(loadError instanceof Error ? loadError.message : "Jackpot indisponible.");
    } finally {
      setLoading(false);
    }
  }

  async function claim() {
    if (!snapshot?.user?.canClaim || claiming) return;
    setClaiming(true);
    setError(null);

    try {
      const response = await fetch("/api/promotions/presence-jackpot/claim", { method: "POST" });
      const payload = await response.json();
      if (!response.ok || !payload.ok) {
        throw new Error(payload.error?.message ?? "Réclamation impossible.");
      }
      setSnapshot(payload.data.snapshot);
      notifyWalletUpdated({ force: true });
    } catch (claimError) {
      setError(claimError instanceof Error ? claimError.message : "Réclamation impossible.");
    } finally {
      setClaiming(false);
    }
  }

  return (
    <main className="mx-auto max-w-[820px] space-y-2.5 pb-4">
      <header className="flex items-center justify-between gap-3">
        <div className="flex min-w-0 items-center gap-2.5">
          <Link
            href="/"
            aria-label="Retour"
            className="grid h-9 w-9 shrink-0 place-items-center rounded-lg border border-white/10 bg-white/[0.035] text-slate-200 transition hover:border-felt/30 hover:text-felt"
          >
            <ArrowLeft className="h-4 w-4" />
          </Link>
          <h1 className="truncate text-lg font-extrabold text-white sm:text-2xl">Jackpot Présence</h1>
        </div>
        <span className="grid h-10 w-10 shrink-0 place-items-center rounded-full border border-white/10 bg-[#0d1821] text-slate-200 shadow-panel">
          <Gift className="h-5 w-5" />
        </span>
      </header>

      <section className="relative overflow-hidden rounded-lg border border-white/10 bg-[#07110f] p-3 shadow-panel sm:p-4">
        <Image
          src="/images/home/jackpot-presence.png"
          alt=""
          fill
          priority
          sizes="(max-width: 768px) 100vw, 820px"
          className="object-cover object-[66%_center] opacity-88"
        />
        <div className="absolute inset-0 bg-[linear-gradient(90deg,#07100f_0%,rgba(7,16,15,.97)_34%,rgba(7,16,15,.68)_66%,rgba(7,16,15,.2)_100%)]" />
        <div className="absolute inset-x-0 bottom-0 h-28 bg-gradient-to-t from-[#07100f] to-transparent" />

        <div className="relative z-10 max-w-[520px]">
          <div className="inline-flex h-7 items-center gap-1.5 rounded-full border border-felt/20 bg-felt/10 px-2.5 text-[10px] font-black uppercase tracking-[0.08em] text-felt">
            <Gift className="h-3.5 w-3.5" />
            Tirage quotidien
          </div>
          <div className="mt-3 text-[50px] font-black leading-none text-[#b8ffe6] drop-shadow-[0_0_22px_rgba(15,191,143,.48)] sm:text-[76px]">
            {loading ? "--" : formatEuro(currentAmount)}
          </div>
          <p className="mt-3 max-w-[470px] text-[13px] font-medium leading-5 text-slate-300 sm:text-sm">
            Un compte éligible est tiré au sort chaque jour. Le gagnant dispose de 24h pour réclamer son gain, sinon le jackpot augmente de{" "}
            <span className="font-extrabold text-felt">+5€</span>.
          </p>

          <WinnerBadge snapshot={snapshot} loading={loading} />

          <div className="mt-3 grid grid-cols-3 gap-1.5">
            <SignalCard icon={<TicketCheck className="h-4 w-4" />} title={snapshot?.user?.currentEntry ? `${snapshot.user.currentEntry.tickets} ticket${snapshot.user.currentEntry.tickets > 1 ? "s" : ""}` : "Ticket"} detail="tirage du jour" />
            <SignalCard icon={<Clock3 className="h-4 w-4" />} title="Tirage" detail={snapshot?.rules.drawTime ?? "20:00"} />
            <SignalCard icon={<ShieldCheck className="h-4 w-4" />} title="24h" detail="réclamation" />
          </div>

          <ClaimAction snapshot={snapshot} loading={loading} claiming={claiming} onClaim={claim} />
          {error ? <p className="mt-2 rounded-lg border border-red-400/20 bg-red-500/10 px-3 py-2 text-xs font-semibold text-red-200">{error}</p> : null}
        </div>
      </section>

      <section className="rounded-lg border border-white/10 bg-[#09131b] p-3 shadow-panel">
        <SectionTitle icon={<TrendingUp className="h-4 w-4" />} title="Progression du jackpot" />
        <div className="mt-3 grid grid-cols-9 gap-1">
          {progression.map((amount) => (
            <ProgressStep key={amount} amount={amount} current={Math.round(currentAmount) === amount} completed={currentAmount > amount} next={snapshot?.nextDraw.amountIfUnclaimed ? Number(snapshot.nextDraw.amountIfUnclaimed) === amount : false} />
          ))}
        </div>
        <p className="mt-2 text-right text-[10px] font-semibold text-slate-400">
          Demain : {snapshot ? formatEuro(Number(snapshot.nextDraw.amountIfUnclaimed)) : "--"} si non réclamé
        </p>
      </section>

      <section className="rounded-lg border border-white/10 bg-[#09131b] p-3 shadow-panel">
        <SectionTitle icon={<Gift className="h-4 w-4" />} title="Comment ça marche ?" />
        <div className="mt-3 grid gap-2 sm:grid-cols-3">
          <StepCard icon={<UserRound className="h-5 w-5" />} number="1" label="Connectez-vous chaque jour." />
          <StepCard icon={<Trophy className="h-5 w-5" />} number="2" label="Un compte est tiré à 20:00." />
          <StepCard icon={<Gift className="h-5 w-5" />} number="3" label="Le gagnant réclame sous 24h." />
        </div>
      </section>

      <section className="grid gap-2 sm:grid-cols-3">
        <MetricCard icon={<Flame className="h-4 w-4" />} label="Série 7 jours" value="Ticket x2" tone="text-amber-300" />
        <MetricCard icon={<TicketCheck className="h-4 w-4" />} label="Prochain tirage" value={snapshot?.user?.nextDraw.tickets ? `${snapshot.user.nextDraw.tickets} ticket${snapshot.user.nextDraw.tickets > 1 ? "s" : ""}` : "0 ticket"} tone="text-felt" />
        <MetricCard icon={<BadgeEuro className="h-4 w-4" />} label="Mises 7 jours" value={`${formatCompactEuro(Number(snapshot?.user?.nextDraw.activeWagerAmount ?? 0))} / 10€`} tone={snapshot?.user?.nextDraw.eligible ? "text-felt" : "text-slate-400"} />
      </section>

      <section id="conditions" className="rounded-lg border border-white/10 bg-[#09131b] p-3 shadow-panel">
        <div className="flex gap-2.5">
          <span className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-felt/10 text-felt">
            <ShieldCheck className="h-5 w-5" />
          </span>
          <div className="min-w-0">
            <h2 className="text-sm font-extrabold text-felt">Conditions</h2>
            <div className="mt-2 grid gap-1.5 sm:grid-cols-2">
              {conditions(snapshot).map((item) => (
                <div key={item} className="flex gap-1.5 text-xs font-medium leading-4 text-slate-300">
                  <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-felt" />
                  <span>{item}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function WinnerBadge({ snapshot, loading }: { snapshot: PresenceSnapshot | null; loading: boolean }) {
  const winnerName = snapshot?.currentDraw.winner?.username;
  const status = snapshot?.currentDraw.status;

  return (
    <div className="mt-3 rounded-lg border border-felt/15 bg-[#071c18]/85 p-2.5 backdrop-blur">
      <div className="flex items-center justify-between gap-2">
        <span className="text-[10px] font-black uppercase tracking-[0.08em] text-felt">Gagnant du jour</span>
        <span className="text-[10px] font-bold text-slate-500">20:00</span>
      </div>
      <div className="mt-1 flex items-center gap-2">
        <span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-felt/12 text-felt">
          <Trophy className="h-4 w-4" />
        </span>
        <div className="min-w-0">
          <p className="truncate text-sm font-extrabold text-white">
            {loading ? "Chargement..." : winnerName ?? "Aucun compte éligible"}
          </p>
          <p className="text-[11px] font-medium text-slate-400">
            {status === "CLAIMED" ? "Gain déjà réclamé" : status === "NO_ELIGIBLE" ? "Le jackpot reste en jeu" : "Réclamable pendant 24h"}
          </p>
        </div>
      </div>
    </div>
  );
}

function ClaimAction({
  snapshot,
  loading,
  claiming,
  onClaim
}: {
  snapshot: PresenceSnapshot | null;
  loading: boolean;
  claiming: boolean;
  onClaim: () => void;
}) {
  const canClaim = snapshot?.user?.canClaim;
  const isWinner = snapshot?.user?.isWinner;
  const claimed = snapshot?.currentDraw.status === "CLAIMED";
  const noWinner = snapshot?.currentDraw.status === "NO_ELIGIBLE";

  if (canClaim) {
    return (
      <button
        onClick={onClaim}
        disabled={claiming}
        className="mt-3 grid h-10 w-full place-items-center rounded-lg bg-felt px-3 text-xs font-black text-ink-950 shadow-[0_14px_28px_rgba(15,191,143,.24)] transition hover:bg-[#18d6a2] disabled:cursor-wait disabled:opacity-70"
      >
        {claiming ? "Réclamation..." : "Réclamer mon gain"}
      </button>
    );
  }

  const label = loading
    ? "Chargement du tirage..."
    : noWinner
      ? "Aucun gagnant éligible aujourd’hui."
      : claimed && isWinner
        ? "Votre gain a déjà été réclamé."
        : isWinner
          ? "Le délai de réclamation est terminé."
          : "Pas votre tirage aujourd’hui. Revenez demain.";

  return (
    <button disabled className="mt-3 min-h-10 w-full rounded-lg border border-white/10 bg-white/[0.045] px-3 py-2 text-xs font-extrabold leading-4 text-slate-400">
      {label}
    </button>
  );
}

function SectionTitle({ icon, title }: { icon: ReactNode; title: string }) {
  return (
    <div className="flex items-center gap-2 text-white">
      <span className="text-felt">{icon}</span>
      <h2 className="text-sm font-extrabold">{title}</h2>
    </div>
  );
}

function SignalCard({ icon, title, detail }: { icon: ReactNode; title: string; detail: string }) {
  return (
    <div className="min-h-[58px] rounded-lg border border-felt/15 bg-[#081b18]/78 p-2 backdrop-blur">
      <div className="text-felt">{icon}</div>
      <p className="mt-1 text-xs font-extrabold leading-4 text-white">{title}</p>
      <p className="text-[11px] font-semibold leading-3 text-slate-400">{detail}</p>
    </div>
  );
}

function ProgressStep({ amount, current, completed, next }: { amount: number; current: boolean; completed: boolean; next: boolean }) {
  return (
    <div className="flex min-w-0 flex-col items-center gap-1.5">
      <span
        className={[
          "grid h-7 w-full min-w-0 place-items-center rounded-full border px-1 text-[10px] font-extrabold",
          current
            ? "border-felt bg-felt/16 text-[#b8ffe6] shadow-[0_0_16px_rgba(15,191,143,.28)]"
            : next
              ? "border-dashed border-white/20 bg-white/[0.03] text-slate-400"
              : "border-white/10 bg-white/[0.055] text-slate-300"
        ].join(" ")}
      >
        {amount}€
      </span>
      <Check className={`h-3.5 w-3.5 ${completed || current ? "text-felt" : next ? "text-slate-500" : "text-white/15"}`} />
    </div>
  );
}

function StepCard({ icon, number, label }: { icon: ReactNode; number: string; label: string }) {
  return (
    <div className="flex items-center gap-2.5 rounded-lg bg-white/[0.035] p-2.5 sm:block sm:text-center">
      <span className="relative grid h-10 w-10 shrink-0 place-items-center rounded-full border border-white/15 bg-[#0f1b25] text-slate-200 sm:mx-auto">
        {icon}
        <span className="absolute -right-1 -top-1 grid h-5 w-5 place-items-center rounded-full bg-slate-700 text-[10px] font-black text-white">
          {number}
        </span>
      </span>
      <p className="text-xs font-semibold leading-4 text-slate-300 sm:mt-2">{label}</p>
    </div>
  );
}

function MetricCard({ icon, label, value, tone }: { icon: ReactNode; label: string; value: string; tone: string }) {
  return (
    <div className="flex min-h-[62px] items-center gap-2.5 rounded-lg border border-white/10 bg-[#09131b] p-2.5 shadow-panel">
      <span className={tone}>{icon}</span>
      <div className="min-w-0">
        <p className="truncate text-xs font-semibold text-slate-400">{label}</p>
        <p className={`truncate text-sm font-black ${tone}`}>{value}</p>
      </div>
    </div>
  );
}

function conditions(snapshot: PresenceSnapshot | null) {
  return [
    "Se connecter chaque jour.",
    `Avoir placé au moins ${formatCompactEuro(Number(snapshot?.rules.activeWagerRequirement ?? 10))} de paris sur les 7 derniers jours.`,
    "Réclamer le gain avant le prochain tirage."
  ];
}

function formatEuro(value: number) {
  if (!Number.isFinite(value)) return "--";
  return `${Math.round(value)}€`;
}

function formatCompactEuro(value: number) {
  if (!Number.isFinite(value)) return "0€";
  return `${new Intl.NumberFormat("fr-FR", { maximumFractionDigits: value % 1 ? 2 : 0 }).format(value)}€`;
}
