import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { toast } from "sonner";
import { Phone, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PinPromptDialog } from "@/components/PinPromptDialog";
import { buyAirtime } from "@/lib/husmodata.functions";
import { formatNaira } from "@/lib/format";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/app/airtime")({
  head: () => ({ meta: [{ title: "Buy Airtime — Billsline" }] }),
  component: AirtimePage,
});

const NETWORKS = [
  { id: "mtn",     label: "MTN",     grad: "from-yellow-500 to-amber-500" },
  { id: "glo",     label: "Glo",     grad: "from-emerald-500 to-green-600" },
  { id: "airtel",  label: "Airtel",  grad: "from-rose-500 to-red-600" },
  { id: "9mobile", label: "9mobile", grad: "from-teal-600 to-emerald-700" },
] as const;
type Net = (typeof NETWORKS)[number]["id"];

const QUICK = [100, 200, 500, 1000, 2000, 5000];

function AirtimePage() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const buy = useServerFn(buyAirtime);

  const [network, setNetwork] = useState<Net>("mtn");
  const [phone, setPhone] = useState("");
  const [amount, setAmount] = useState<number>(100);
  const [pinOpen, setPinOpen] = useState(false);

  const m = useMutation({
    mutationFn: (pin: string) => buy({ data: { network, phone, amount, pin } }),
    onSuccess: (r) => {
      qc.invalidateQueries();
      navigate({ to: "/app/tx/$ref", params: { ref: r.reference } });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const validPhone = /^0\d{10}$/.test(phone);
  const canPay = validPhone && amount >= 50 && amount <= 50000 && !m.isPending;

  return (
    <div className="space-y-4 p-4">
      <h1 className="text-lg font-bold text-foreground">Buy Airtime</h1>

      <div className="grid grid-cols-4 gap-2">
        {NETWORKS.map((n) => {
          const active = network === n.id;
          return (
            <button key={n.id} onClick={() => setNetwork(n.id)}
              className={cn(
                "relative rounded-2xl p-2.5 text-center text-[11px] font-bold uppercase transition shadow-sm",
                active ? `bg-gradient-to-br ${n.grad} text-white shadow-md` : "bg-card text-muted-foreground hover:text-foreground",
              )}>
              <Phone className="mx-auto mb-1 h-3.5 w-3.5" />
              {n.label}
              {active && <CheckCircle2 className="absolute right-1 top-1 h-3.5 w-3.5" />}
            </button>
          );
        })}
      </div>

      <div className="space-y-3 rounded-2xl bg-card p-4 shadow-card">
        <div>
          <Label htmlFor="phone" className="text-[10px] uppercase tracking-wider text-muted-foreground">Phone number</Label>
          <Input
            id="phone" inputMode="numeric" placeholder="0801 234 5678"
            value={phone}
            onChange={(e) => setPhone(e.target.value.replace(/\D/g, "").slice(0, 11))}
            className="mt-1 h-11 font-mono text-base tracking-wider"
          />
        </div>

        <div>
          <Label htmlFor="amount" className="text-[10px] uppercase tracking-wider text-muted-foreground">Amount</Label>
          <Input
            id="amount" type="number" min={50} max={50000} value={amount}
            onChange={(e) => setAmount(Number(e.target.value))}
            className="mt-1 h-11 text-base font-semibold"
          />
          <div className="mt-2 grid grid-cols-6 gap-1.5">
            {QUICK.map((a) => (
              <button key={a} type="button" onClick={() => setAmount(a)}
                className={cn(
                  "rounded-full py-1.5 text-[11px] font-semibold transition",
                  amount === a ? "bg-primary text-primary-foreground" : "bg-secondary text-secondary-foreground hover:bg-secondary/70",
                )}>₦{a >= 1000 ? `${a / 1000}k` : a}</button>
            ))}
          </div>
        </div>
      </div>

      <div className="sticky bottom-20 z-10 -mx-4 border-t border-border/50 bg-background/85 px-4 py-3 backdrop-blur">
        <Button className="h-11 w-full bg-gradient-primary text-sm font-semibold" disabled={!canPay} onClick={() => setPinOpen(true)}>
          {m.isPending ? "Processing…" : `Pay ${formatNaira(amount)}`}
        </Button>
      </div>

      <PinPromptDialog
        open={pinOpen}
        onOpenChange={setPinOpen}
        title="Confirm airtime purchase"
        description="Enter your 4-digit PIN to authorize this airtime purchase."
        amount={amount}
        summary={[
          { label: "Service", value: "Airtime top-up" },
          { label: "Network", value: network.toUpperCase() },
          { label: "Recipient mobile", value: phone || "—" },
          { label: "Paid from", value: "Billsline Wallet" },
        ]}
        onVerified={(pin) => m.mutate(pin)}
      />
    </div>
  );
}
