import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { toast } from "sonner";
import { useAuthStore } from "@/store/auth";
import { LariMark, WGCMark, formatGEL, formatWGC, toWGC, WGC_PER_GEL } from "@/lib/currency";
import { ArrowLeftRight, CreditCard, Landmark, Smartphone, Wallet } from "lucide-react";

const GEL_PACKAGES = [10, 25, 50, 100, 250, 500];
const WGC_PACKAGES = [
  { wgc: 500,   gel: 45,   bonus: 0 },
  { wgc: 1200,  gel: 100,  bonus: 200 },
  { wgc: 3000,  gel: 240,  bonus: 600 },
  { wgc: 7000,  gel: 500,  bonus: 2000 },
];
const METHODS = [
  { id: "card",   label: "Card (Visa / MC)", icon: CreditCard },
  { id: "bog",    label: "Bank of Georgia",  icon: Landmark },
  { id: "tbc",    label: "TBC Bank",         icon: Landmark },
  { id: "apple",  label: "Apple Pay",        icon: Smartphone },
];

const RECENT = [
  { id: "tx1", when: "Today · 14:22", kind: "Top-up",   amount: "+50.00 ₾", meta: "Card ****4242",  ok: true  },
  { id: "tx2", when: "Yesterday",     kind: "WGC pack", amount: "+1,200 WGC", meta: "TBC Bank",     ok: true  },
  { id: "tx3", when: "Aug 12",        kind: "Purchase", amount: "-25.00 ₾", meta: "VIP · 30 days", ok: true  },
  { id: "tx4", when: "Aug 5",         kind: "Refund",   amount: "+9.99 ₾",  meta: "Order #4218",   ok: true  },
  { id: "tx5", when: "Jul 30",        kind: "Convert",  amount: "-100 WGC", meta: "→ 10.00 ₾",     ok: true  },
];

export const Route = createFileRoute("/_public/account/balance")({
  head: () => ({ meta: [{ title: "Balance & wallet — Purple Zone" }] }),
  component: BalancePage,
});

function BalancePage() {
  const user = useAuthStore((s) => s.user);
  const topUp = useAuthStore((s) => s.topUpBalance);
  const addCoins = useAuthStore((s) => s.addCoins);
  const [amount, setAmount] = useState(50);
  const [method, setMethod] = useState("card");
  const [convertGEL, setConvertGEL] = useState(10);

  function submitTopUp() {
    if (amount < 1) { toast.error("Minimum 1 ₾"); return; }
    topUp(amount);
    toast.success(`Topped up ${formatGEL(amount)} via ${METHODS.find((m) => m.id === method)?.label}`);
  }
  function buyPack(p: typeof WGC_PACKAGES[number]) {
    addCoins(p.wgc + p.bonus);
    toast.success(`+${(p.wgc + p.bonus).toLocaleString()} WGC added`);
  }
  function convertToWGC() {
    if (!user || user.balance < convertGEL) { toast.error("Insufficient GEL"); return; }
    topUp(-convertGEL);
    addCoins(toWGC(convertGEL));
    toast.success(`Converted ${formatGEL(convertGEL)} → ${formatWGC(toWGC(convertGEL))}`);
  }

  return (
    <div className="space-y-6">
      <div className="rounded-xl border border-border bg-card p-6">
        <div className="grid gap-4 md:grid-cols-2">
          <div className="rounded-lg border border-border/60 bg-surface p-5">
            <div className="flex items-center gap-2 text-xs uppercase tracking-wider text-muted-foreground">
              <Wallet className="h-3.5 w-3.5" /> Fiat balance
            </div>
            <div className="mt-2 flex items-baseline gap-1.5 font-display text-4xl font-bold">
              <LariMark className="h-7 w-7 text-secondary" />
              {user ? formatGEL(user.balance, { withSymbol: false }) : "0.00"}
              <span className="ml-1 text-sm font-normal text-muted-foreground">GEL</span>
            </div>
            <div className="mt-1 text-xs text-muted-foreground">Georgian Lari — used for all real-money purchases.</div>
          </div>
          <div className="rounded-lg border border-primary/40 bg-primary/10 p-5">
            <div className="flex items-center gap-2 text-xs uppercase tracking-wider text-secondary">
              <WGCMark className="h-3.5 w-3.5" /> Platform coins
            </div>
            <div className="mt-2 flex items-baseline gap-1.5 font-display text-4xl font-bold">
              {user ? user.coins.toLocaleString() : "0"}
              <span className="ml-1 text-sm font-normal text-muted-foreground">WGC</span>
            </div>
            <div className="mt-1 text-xs text-muted-foreground">Wild Georgia Coin — earned in-server, spent on cosmetics & boosts.</div>
          </div>
        </div>
      </div>

      <Tabs defaultValue="topup" className="space-y-4">
        <TabsList>
          <TabsTrigger value="topup">Top up ₾</TabsTrigger>
          <TabsTrigger value="wgc">Buy WGC</TabsTrigger>
          <TabsTrigger value="convert">Convert</TabsTrigger>
          <TabsTrigger value="history">History</TabsTrigger>
        </TabsList>

        <TabsContent value="topup">
          <div className="grid gap-6 rounded-xl border border-border bg-card p-6 md:grid-cols-[1fr_320px]">
            <div>
              <Label className="text-xs uppercase text-muted-foreground">Quick amounts (₾)</Label>
              <div className="mt-2 grid grid-cols-3 gap-2 sm:grid-cols-6">
                {GEL_PACKAGES.map((v) => (
                  <button
                    key={v}
                    onClick={() => setAmount(v)}
                    className={`rounded-md border px-3 py-2 text-sm font-medium transition-colors ${amount === v ? "border-primary bg-primary/15 text-secondary" : "border-border bg-surface hover:border-primary/40"}`}
                  >
                    {v} ₾
                  </button>
                ))}
              </div>
              <div className="mt-4">
                <Label>Custom amount</Label>
                <div className="mt-1 flex items-center gap-2">
                  <Input
                    type="number"
                    min={1}
                    value={amount}
                    onChange={(e) => setAmount(Math.max(0, +e.target.value || 0))}
                    className="max-w-[160px]"
                  />
                  <span className="text-sm text-muted-foreground">₾</span>
                </div>
              </div>
              <div className="mt-4">
                <Label className="text-xs uppercase text-muted-foreground">Payment method</Label>
                <div className="mt-2 grid gap-2 sm:grid-cols-2">
                  {METHODS.map((m) => (
                    <button
                      key={m.id}
                      onClick={() => setMethod(m.id)}
                      className={`flex items-center gap-2 rounded-md border px-3 py-2 text-sm transition-colors ${method === m.id ? "border-primary bg-primary/10" : "border-border bg-surface hover:border-primary/40"}`}
                    >
                      <m.icon className="h-4 w-4 text-secondary" /> {m.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
            <aside className="rounded-lg border border-border/60 bg-surface p-4">
              <div className="text-xs uppercase text-muted-foreground">Summary</div>
              <div className="mt-2 flex items-baseline justify-between">
                <span>Amount</span>
                <span className="font-mono">{formatGEL(amount)}</span>
              </div>
              <div className="mt-1 flex items-baseline justify-between text-xs text-muted-foreground">
                <span>≈</span>
                <span>{formatWGC(toWGC(amount))}</span>
              </div>
              <div className="mt-1 flex items-baseline justify-between text-xs text-muted-foreground">
                <span>Fee</span>
                <span>0.00 ₾</span>
              </div>
              <div className="my-3 h-px bg-border" />
              <div className="flex items-baseline justify-between font-semibold">
                <span>Total</span>
                <span className="font-mono">{formatGEL(amount)}</span>
              </div>
              <Button onClick={submitTopUp} className="mt-4 w-full gradient-primary text-primary-foreground shadow-glow hover:opacity-95">
                Top up now
              </Button>
              <p className="mt-2 text-[11px] text-muted-foreground">Secure Georgian payment gateways · PCI-DSS · SSL</p>
            </aside>
          </div>
        </TabsContent>

        <TabsContent value="wgc">
          <div className="grid gap-4 rounded-xl border border-border bg-card p-6 sm:grid-cols-2 lg:grid-cols-4">
            {WGC_PACKAGES.map((p) => (
              <div key={p.wgc} className="flex flex-col rounded-lg border border-border/60 bg-surface p-4">
                <div className="flex items-center justify-between">
                  <WGCMark className="h-6 w-6" />
                  {p.bonus > 0 && <Badge className="gradient-primary text-primary-foreground">+{p.bonus} bonus</Badge>}
                </div>
                <div className="mt-3 font-display text-2xl font-bold">{(p.wgc + p.bonus).toLocaleString()} WGC</div>
                <div className="text-xs text-muted-foreground">Base {p.wgc.toLocaleString()} · {formatGEL(p.gel)}</div>
                <Button onClick={() => buyPack(p)} className="mt-4 gradient-primary text-primary-foreground shadow-glow hover:opacity-95">
                  Buy for {formatGEL(p.gel)}
                </Button>
              </div>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="convert">
          <div className="rounded-xl border border-border bg-card p-6">
            <div className="max-w-md">
              <div className="text-sm text-muted-foreground">Convert GEL → WGC at a fixed rate of 1 ₾ = {WGC_PER_GEL} WGC.</div>
              <div className="mt-4 flex items-end gap-3">
                <div>
                  <Label>From</Label>
                  <div className="mt-1 flex items-center gap-2">
                    <Input type="number" min={1} value={convertGEL} onChange={(e) => setConvertGEL(Math.max(0, +e.target.value || 0))} className="w-32" />
                    <span className="text-sm text-muted-foreground">₾</span>
                  </div>
                </div>
                <ArrowLeftRight className="mb-2.5 h-4 w-4 text-muted-foreground" />
                <div>
                  <Label>To</Label>
                  <div className="mt-1 rounded-md border border-border bg-surface px-3 py-2 font-mono text-sm">
                    {toWGC(convertGEL).toLocaleString()} WGC
                  </div>
                </div>
              </div>
              <Button onClick={convertToWGC} className="mt-4 gradient-primary text-primary-foreground shadow-glow hover:opacity-95">
                Convert
              </Button>
            </div>
          </div>
        </TabsContent>

        <TabsContent value="history">
          <div className="overflow-hidden rounded-xl border border-border bg-card">
            <table className="w-full text-sm">
              <thead className="bg-surface text-left text-xs uppercase text-muted-foreground">
                <tr><th className="px-3 py-2.5">When</th><th className="px-3 py-2.5">Type</th><th className="px-3 py-2.5">Amount</th><th className="px-3 py-2.5">Details</th></tr>
              </thead>
              <tbody>
                {RECENT.map((r) => (
                  <tr key={r.id} className="border-t border-border/60">
                    <td className="px-3 py-2.5 text-muted-foreground">{r.when}</td>
                    <td className="px-3 py-2.5">{r.kind}</td>
                    <td className="px-3 py-2.5 font-mono font-semibold">{r.amount}</td>
                    <td className="px-3 py-2.5 text-muted-foreground">{r.meta}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
