import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { LobbyShell, PageTitle, Steps, useToast, card } from "@/components/lotus/LobbyShell";
import { useBalance, fmt, trySpend } from "@/lib/wallet";

export const Route = createFileRoute("/withdraw")({
  head: () => ({
    meta: [
      { title: "Withdraw Funds – Lotus365 Demo" },
      { name: "description", content: "Request an instant payout of your Lotus365 demo balance by UPI or bank." },
      { property: "og:title", content: "Withdraw Funds – Lotus365" },
      { property: "og:description", content: "Request instant payout to account." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: WithdrawPage,
});

function WithdrawPage() {
  const balance = useBalance();
  const [amt, setAmt] = useState(200);
  const [method, setMethod] = useState<"UPI" | "BANK">("UPI");
  const [id, setId] = useState("");
  const [acc, setAcc] = useState("");
  const [ifsc, setIfsc] = useState("");
  const [holder, setHolder] = useState("");
  const toast = useToast();
  const submit = () => {
    if (amt < 200 || amt > 50000) return toast.show("Amount must be ₹200 – ₹50,000");
    if (method === "UPI" && !/^[\w.-]+@[\w]+$/.test(id.trim())) return toast.show("Enter a valid UPI ID");
    if (method === "BANK") {
      if (!/^\d{9,18}$/.test(acc)) return toast.show("Enter a valid account number");
      if (!/^[A-Z]{4}0[A-Z0-9]{6}$/.test(ifsc)) return toast.show("Enter a valid IFSC code");
      if (holder.trim().length < 3) return toast.show("Enter account holder name");
    }
    if (!trySpend(amt)) return toast.show("Insufficient withdrawable balance");
    toast.show(`Withdrawal of ₹${amt.toLocaleString("en-IN")} requested (demo)`);
  };
  return (
    <LobbyShell>
      {toast.node}
      <PageTitle a="WITHDRAW" b="FUNDS" sub="Request instant payout to account" right={
        <div className="text-right text-[10px] font-bold text-muted-foreground">WITHDRAWABLE BALANCE<p className="mt-1 text-base font-extrabold text-gold">₹{fmt(balance)}</p></div>
      } />
      <section className={`mx-3 mt-4 ${card} p-4`}>
        <p className="text-[11px] font-bold text-muted-foreground">ENTER WITHDRAWAL AMOUNT</p>
        <div className="mt-2 flex items-center justify-between">
          <label className="flex items-center gap-1 text-3xl font-extrabold"><span>₹</span>
            <input inputMode="numeric" aria-label="Withdrawal amount" value={amt || ""} onChange={(e) => setAmt(Number(e.target.value.replace(/\D/g, "").slice(0, 6)))} className="w-32 bg-transparent outline-none" />
          </label>
          <button onClick={() => setAmt(Math.min(50000, Math.floor(balance)))} className="rounded-md bg-gold px-4 py-2 text-xs font-extrabold text-gold-foreground">MAX</button>
        </div>
      </section>
      <p className="px-3 pt-5 text-[11px] font-bold text-muted-foreground">SELECT PAYOUT METHOD</p>
      <div className="mx-3 mt-3 grid grid-cols-2 gap-2 rounded-lg border border-border bg-lobby-deep p-1">
        {(["UPI", "BANK"] as const).map((m) => (
          <button key={m} onClick={() => setMethod(m)} className={`rounded-md py-2.5 text-xs font-extrabold ${method === m ? "bg-gold text-gold-foreground" : ""}`}>{m}</button>
        ))}
      </div>
      {method === "UPI" ? (
        <label className={`mx-3 mt-3 block ${card} p-3`}>
          <span className="text-[10px] font-bold text-muted-foreground">UPI ID</span>
          <input value={id} onChange={(e) => setId(e.target.value)} placeholder="example@upi / name@ybl" className="mt-1 block w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
        </label>
      ) : (
        <div className="mx-3 mt-3 animate-pop space-y-2.5 bg-lobby-deep/60 p-1.5">
          {([
            ["Bank Account Number", "Enter Account Number", acc, (v: string) => setAcc(v.replace(/\D/g, "").slice(0, 18)), "numeric"],
            ["IFSC Code", "E.G. SBIN0001234", ifsc, (v: string) => setIfsc(v.toUpperCase().replace(/[^A-Z0-9]/g, "").slice(0, 11)), "text"],
            ["Account Holder Name", "Enter Full Name", holder, (v: string) => setHolder(v.slice(0, 60)), "text"],
          ] as const).map(([label, ph, val, set, mode]) => (
            <label key={label} className={`block ${card} px-4 py-3`}>
              <span className="text-xs text-foreground/90">{label}</span>
              <input inputMode={mode} value={val} onChange={(e) => set(e.target.value)} placeholder={ph} className="mt-1 block w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" />
            </label>
          ))}
        </div>
      )}
      <button onClick={submit} className="mx-3 mt-4 w-[calc(100%-1.5rem)] rounded-lg bg-gold py-3.5 text-sm font-extrabold text-gold-foreground active:scale-[.98]">WITHDRAW NOW</button>
      <Steps title="WITHDRAWAL RULES"
        items={[<>You can only withdraw your <b className="text-foreground">Withdrawable Balance</b>.</>, <>Minimum withdrawal is <b className="text-foreground">₹200</b> and Maximum is <b className="text-foreground">₹50,000</b> per transaction.</>, <>Maximum <b className="text-foreground">10 withdrawal requests</b> allowed per day.</>, "Funds are credited directly to your bank account after verification."]}
        hiItems={["आप केवल अपना निकासी योग्य बैलेंस ही निकाल सकते हैं।", "न्यूनतम निकासी ₹200 और अधिकतम ₹50,000 प्रति लेनदेन है।", "प्रति दिन अधिकतम 10 निकासी अनुरोध।", "सत्यापन के बाद राशि सीधे आपके बैंक खाते में जमा होगी।"]} />
    </LobbyShell>
  );
}
