import { createFileRoute, Link } from "@tanstack/react-router";
import { useCallback, useEffect, useRef, useState } from "react";
import { ChevronLeft, Headphones, Volume2, VolumeX, RefreshCw, Wallet, Gamepad2 } from "lucide-react";
import { GameLoader, Logo } from "@/components/lotus/Loader";
import { wingoColors, wingoSize } from "@/lib/games";
import { setBalance, useBalance, fmt } from "@/lib/wallet";
import { apiCall, getUserToken } from "@/lib/api";
import timerBg from "@/assets/wingo/wingo-timer-bg.webp";
import ball0 from "@/assets/wingo/wingo-ball-0.png";
import ball1 from "@/assets/wingo/wingo-ball-1.png";
import ball2 from "@/assets/wingo/wingo-ball-2.png";
import ball3 from "@/assets/wingo/wingo-ball-3.png";
import ball4 from "@/assets/wingo/wingo-ball-4.png";
import ball5 from "@/assets/wingo/wingo-ball-5.png";
import ball6 from "@/assets/wingo/wingo-ball-6.png";
import ball7 from "@/assets/wingo/wingo-ball-7.png";
import ball8 from "@/assets/wingo/wingo-ball-8.png";
import ball9 from "@/assets/wingo/wingo-ball-9.png";

const BALLS = [ball0, ball1, ball2, ball3, ball4, ball5, ball6, ball7, ball8, ball9];

export const Route = createFileRoute("/wingo")({
  head: () => ({
    meta: [
      { title: "Wingo 1 Min – Lotus365" },
      { name: "description", content: "Pick a colour, number, big or small and win every minute." },
    ],
  }),
  component: () => <GameLoader><Wingo /></GameLoader>,
});

type Pick = { kind: "color"; v: "green" | "violet" | "red" } | { kind: "num"; v: number } | { kind: "size"; v: "Big" | "Small" };
type BetRow = { id?: number; period_id: string; bet_type: string; bet_value: string; amount: number; status: string; win_amount: number };
const label = (p: Pick) => (p.kind === "num" ? String(p.v) : p.kind === "color" ? p.v.charAt(0).toUpperCase() + p.v.slice(1) : p.v);
const headCls = (p: Pick) => (p.kind === "color" ? `bg-wg-${p.v}` : p.kind === "size" ? (p.v === "Big" ? "bg-wg-big" : "bg-wg-small") : wingoColors(p.v)[0] === "red" ? "bg-wg-red" : "bg-wg-green");

const periodOf = (ms: number) => {
  const d = new Date(ms);
  const p = (x: number) => String(x).padStart(2, "0");
  return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}1${String(d.getHours() * 60 + d.getMinutes()).padStart(4, "0")}`;
};

function Wingo() {
  const balance = useBalance();
  const [now, setNow] = useState(() => Date.now());
  const [serverPeriod, setServerPeriod] = useState(() => periodOf(Date.now()));
  const [history, setHistory] = useState<{ period_id: string; result_number: number }[]>([]);
  const [bets, setBets] = useState<BetRow[]>([]);
  const [sheet, setSheet] = useState<Pick | null>(null);
  const [base, setBase] = useState(10);
  const [qty, setQty] = useState(1);
  const [tab, setTab] = useState<"game" | "mine">("game");
  const [flash, setFlash] = useState<string>("");
  const [soundOn, setSoundOn] = useState(true);
  const lastPeriodRef = useRef<string>("");
  const audio = useRef<AudioContext | null>(null);

  const tone = useCallback((frequency = 520, duration = 0.06, force = false) => {
    if ((!soundOn && !force) || typeof AudioContext === "undefined") return;
    const ctx = audio.current ?? new AudioContext();
    audio.current = ctx;
    void ctx.resume();
    const oscillator = ctx.createOscillator();
    const gain = ctx.createGain();
    oscillator.type = "sine";
    oscillator.frequency.value = frequency;
    gain.gain.setValueAtTime(0.06, ctx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + duration);
    oscillator.connect(gain);
    gain.connect(ctx.destination);
    oscillator.start();
    oscillator.stop(ctx.currentTime + duration);
  }, [soundOn]);

  const toggleSound = () => {
    const next = !soundOn;
    setSoundOn(next);
    window.localStorage.setItem("wingo-sound", next ? "on" : "off");
    if (next) tone(660, 0.08, true);
  };

  const syncServer = useCallback(async () => {
    try {
      const res = await apiCall("wingo_state", {}, "GET");
      if (res.ok) {
        setServerPeriod(res.period_id);
        if (Array.isArray(res.history) && res.history.length > 0) {
          setHistory(res.history);
          const latest = res.history[0];
          if (lastPeriodRef.current && lastPeriodRef.current !== latest.period_id) {
            setFlash(`Result: ${latest.result_number} · ${wingoSize(Number(latest.result_number))}`);
            tone(760, 0.12);
            setTimeout(() => setFlash(""), 3000);
          }
          lastPeriodRef.current = latest.period_id;
        }
        if (Array.isArray(res.my_bets)) setBets(res.my_bets);
      }
      if (getUserToken()) {
        const prof = await apiCall("profile", {}, "GET");
        if (prof.ok && prof.user) setBalance(Number(prof.user.wallet_balance));
      }
    } catch {
      // ignore transient network errors
    }
  }, [tone]);

  useEffect(() => {
    if (window.localStorage.getItem("wingo-sound") === "off") setSoundOn(false);
    void syncServer();
    const poll = setInterval(() => void syncServer(), 2000);
    return () => clearInterval(poll);
  }, [syncServer]);

  const period = serverPeriod || periodOf(now);
  const left = 60 - Math.floor((now / 1000) % 60);

  useEffect(() => { const t = setInterval(() => setNow(Date.now()), 250); return () => clearInterval(t); }, []);
  useEffect(() => {
    if (left <= 5) tone(350 + (5 - left) * 60, 0.045);
  }, [left, tone]);

  const confirm = async () => {
    if (!sheet) return;
    const total = base * qty;
    const betType = sheet.kind === "num" ? "number" : sheet.kind;
    const betValue = String(sheet.v);
    try {
      const res = await apiCall("wingo_bet", { bet_type: betType, bet_value: betValue, amount: total });
      if (res.ok) {
        setBalance(Number(res.wallet_balance));
        setTab("mine");
        tone(720, 0.1);
        setFlash(`Bet placed: ${label(sheet)} (₹${total})`);
        setTimeout(() => setFlash(""), 2000);
        void syncServer();
      } else {
        tone(170, 0.12);
        setFlash(res.error || "Bet failed");
        setTimeout(() => setFlash(""), 2500);
      }
    } catch {
      setFlash("Please login first to place bet");
      setTimeout(() => setFlash(""), 2500);
    }
    setSheet(null);
    setQty(1);
  };

  const locked = left <= 5;
  const open = (p: Pick) => { if (!locked) { tone(); setSheet(p); } };

  return (
    <div className="app-frame bg-wg-bg pb-10">
      <div className="flex h-14 items-center justify-between bg-wg-bg px-3.5">
        <Link to="/" aria-label="Back" className="grid size-9 place-items-center rounded-full bg-foreground/5"><ChevronLeft className="size-6" /></Link>
        <Logo className="text-[22px]" />
        <div className="flex gap-2">
          <button aria-label="Support" className="grid size-8 place-items-center rounded-full bg-foreground/10"><Headphones className="size-5" /></button>
          <button aria-label={soundOn ? "Mute sound" : "Enable sound"} aria-pressed={soundOn} onClick={toggleSound} className="grid size-8 place-items-center rounded-full bg-foreground/10">
            {soundOn ? <Volume2 className="size-5 text-gold" /> : <VolumeX className="size-5 text-muted-foreground" />}
          </button>
        </div>
      </div>

      <div className="relative mx-3.5 mt-3.5 rounded-2xl bg-wingo-wallet p-4 text-center shadow-lg">
        <p className="text-lg font-bold">₹ {fmt(balance)}</p>
        <button onClick={() => void syncServer()} aria-label="Refresh balance" className="absolute right-4 top-4"><RefreshCw className="size-4 opacity-80" /></button>
        <p className="mt-0.5 flex items-center justify-center gap-1 text-xs opacity-90"><Wallet className="size-3.5" /> Wallet balance</p>
        <div className="mt-4 grid grid-cols-2 gap-3.5 text-sm font-bold"><Link to="/withdraw" className="wingo-raised rounded-full bg-wingo-withdraw py-3 text-center">Withdraw</Link><Link to="/deposit" className="wingo-raised rounded-full bg-wingo-deposit py-3 text-center">Deposit</Link></div>
      </div>

      <div className="mx-3.5 mt-2.5 flex h-12 items-center gap-2 overflow-hidden rounded-lg border border-foreground/10 bg-wg-card px-3 text-xs">
        <Volume2 className="size-4 shrink-0 text-pill-blue" />
        <div className="flex-1 overflow-hidden whitespace-nowrap"><p className="animate-marquee">Thanks to all new and old members, because of your support we keep growing!</p></div>
        <span className="wingo-raised shrink-0 rounded-full bg-wg-red px-3.5 py-1.5 font-bold">Detail</span>
      </div>

      <div className="mx-3.5 mt-2.5 grid min-h-[126px] grid-cols-2 rounded-[14px] bg-cover p-4" style={{ backgroundImage: `linear-gradient(90deg, var(--wg-timer-shade), transparent 68%), url(${timerBg})`, backgroundSize: "100% 100%" }}>
        <div className="pr-3">
          <span className="inline-flex items-center gap-1 rounded-full border border-foreground/30 bg-foreground/10 px-2.5 py-1 text-[10px]"><Gamepad2 className="size-3.5" /> How to play</span>
          <p className="mt-2 text-sm font-bold">Win Go 1 Min</p>
          <div className="mt-1.5 flex gap-1">{history.slice(0, 5).map((h) => <img key={h.period_id} src={BALLS[Number(h.result_number)]} alt={String(h.result_number)} className="size-6" />)}</div>
        </div>
        <div className="pl-3 text-right">
          <p className="text-sm font-bold">Time remaining</p>
          <div className="mt-1.5 flex items-center justify-end gap-1 font-black text-ink">
            {["0", String(Math.floor(left / 60)), ":", String(Math.floor((left % 60) / 10)), String(left % 10)].map((d, i) => d === ":" ? <span key={i} className="px-0.5 text-xl text-foreground">:</span> : <span key={i} className="grid size-8 place-items-center rounded-md bg-foreground text-lg">{d}</span>)}
          </div>
          <p className="mt-2 text-xs font-bold">{period}</p>
        </div>
      </div>

      <div className="relative mx-3.5 mt-2.5 rounded-[14px] border border-foreground/10 bg-wg-card p-3.5">
        <div className="grid grid-cols-3 gap-3 text-sm font-semibold">
          {(["green", "violet", "red"] as const).map((c) => <button key={c} onClick={() => open({ kind: "color", v: c })} className={`wingo-raised h-11 rounded-lg capitalize transition active:scale-95 bg-wg-choice-${c}`}>{c}</button>)}
        </div>
        <div className="mt-3 grid grid-cols-5 gap-x-6 gap-y-3">
          {Array.from({ length: 10 }, (_, n) => (
            <button key={n} aria-label={`Select number ${n}`} onClick={() => open({ kind: "num", v: n })} className="aspect-square w-full rounded-full transition active:scale-90">
              <img src={BALLS[n]} alt={String(n)} className="h-full w-full" />
            </button>
          ))}
        </div>
        <div className="mt-6 grid h-10 grid-cols-2 overflow-hidden rounded-full border border-foreground/20 text-sm">
          <button onClick={() => open({ kind: "size", v: "Big" })} className="bg-wg-size-big">Big</button>
          <button onClick={() => open({ kind: "size", v: "Small" })} className="bg-wg-size-small">Small</button>
        </div>
        {locked && (
          <div className="absolute inset-0 flex flex-col items-center justify-center rounded-[14px] bg-ink/80">
            <p key={left} className="animate-pop text-8xl font-black tracking-[0.2em] text-wg-green">0{left - 1 < 0 ? 0 : left - 1}</p>
            <p className="font-bold">Period: {period}</p>
          </div>
        )}
      </div>
      {flash && <p className="mx-3.5 mt-2 animate-pop rounded-lg bg-wg-card py-2 text-center text-xs font-bold text-gold">{flash}</p>}

      <div className="mx-3.5 mt-3.5 overflow-hidden rounded-t-[14px] border border-foreground/10 bg-wg-deep">
        <div className="grid h-12 grid-cols-2 text-sm font-bold">
          <button onClick={() => setTab("game")} className={tab === "game" ? "bg-wingo-tab" : "text-muted-foreground"}>Game History</button>
          <button onClick={() => setTab("mine")} className={tab === "mine" ? "bg-wingo-tab" : "text-muted-foreground"}>My History</button>
        </div>
        {tab === "game" ? (
          <table className="w-full text-center text-xs">
            <thead className="bg-wg-deep text-[10px] uppercase text-muted-foreground"><tr><th className="py-3">Period</th><th>Number</th><th>Big Small</th><th>Color</th></tr></thead>
            <tbody>{history.map((h) => {
              const num = Number(h.result_number);
              return (
                <tr key={h.period_id} className="border-t border-foreground/5">
                  <td className="py-3">{h.period_id}</td>
                  <td className={`text-base font-bold ${wingoColors(num)[0] === "red" ? "text-wg-red" : "text-wg-green"}`}>{num}</td>
                  <td>{wingoSize(num)}</td>
                  <td>{wingoColors(num).map((c) => <span key={c} className={`mx-0.5 inline-block size-2.5 rounded-full bg-wg-${c}`} />)}</td>
                </tr>
              );
            })}</tbody>
          </table>
        ) : bets.length === 0 ? <p className="py-6 text-center text-xs text-muted-foreground">No bets yet</p> : (
          <table className="w-full text-center text-xs">
            <thead className="bg-wg-deep text-[10px] uppercase text-muted-foreground"><tr><th className="py-3">Period</th><th>Select</th><th>Amount</th><th>Status</th><th>Win</th></tr></thead>
            <tbody>{bets.map((b, i) => (
              <tr key={b.id ?? i} className="border-t border-foreground/5">
                <td className="py-2.5">{b.period_id.slice(-5)}</td>
                <td className="capitalize">{b.bet_value}</td>
                <td>₹{Number(b.amount).toFixed(0)}</td>
                <td className="capitalize">{b.status}</td>
                <td className={b.status === "won" ? "font-bold text-wg-green" : b.status === "lost" ? "text-wg-red" : ""}>
                  {b.status === "pending" ? "Pending" : b.status === "won" ? `+₹${Number(b.win_amount).toFixed(2)}` : "Lose"}
                </td>
              </tr>
            ))}</tbody>
          </table>
        )}
      </div>

      {sheet && (
        <div className="fixed inset-0 z-40 flex items-end justify-center bg-ink/60" onClick={() => setSheet(null)}>
          <div className="w-full max-w-[430px] animate-in slide-in-from-bottom bg-wg-bg" onClick={(e) => e.stopPropagation()}>
            <div className={`${headCls(sheet)} rounded-t-3xl py-3 text-center`}>
              <p className="font-bold">Win Go</p>
              <span className="mt-1 inline-block rounded-full bg-foreground/90 px-4 py-0.5 text-sm font-bold text-ink">Select {label(sheet).toUpperCase()}</span>
            </div>
            <div className="space-y-3 p-3 text-sm">
              <div className="flex items-center justify-between"><span className="text-muted-foreground">Amount</span>
                <div className="flex gap-2">{[10, 50, 500, 5000].map((v) => <button key={v} onClick={() => setBase(v)} className={`rounded px-3 py-1.5 font-bold ${base === v ? "bg-wg-green" : "bg-wg-card"}`}>{v === 5000 ? "5k" : v}</button>)}</div>
              </div>
              <div className="flex items-center justify-between"><span className="text-muted-foreground">Quantity</span>
                <div className="flex items-center gap-2 font-bold">
                  <button onClick={() => setQty(Math.max(1, qty - 1))} className="size-8 rounded bg-wg-red">-</button>
                  <span className="w-10 rounded bg-wg-card py-1 text-center">{qty}</span>
                  <button onClick={() => setQty(qty + 1)} className="size-8 rounded bg-wg-red">+</button>
                </div>
              </div>
            </div>
            <div className="grid grid-cols-[1fr_2fr] font-bold">
              <button onClick={() => setSheet(null)} className="bg-wg-card py-3.5">Cancel</button>
              <button onClick={() => void confirm()} className="bg-wg-green py-3.5">Total ₹{(base * qty).toFixed(2)}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
