import { useState, type ReactNode } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useServerFn } from "@tanstack/react-start";
import { topUpCredits } from "@/lib/billing.functions";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Check, Zap, Smartphone, CreditCard } from "lucide-react";
import { cn } from "@/lib/utils";

const PACKS = [
  { id: "starter", sms: 1000, price: 35000, label: "Starter" },
  { id: "growth", sms: 5000, price: 125000, label: "Growth", popular: true },
  { id: "scale", sms: 15000, price: 330000, label: "Scale" },
  { id: "enterprise", sms: 50000, price: 950000, label: "Enterprise" },
];

const METHODS = [
  { id: "mpesa", label: "M-Pesa", icon: Smartphone },
  { id: "mtn", label: "MTN MoMo", icon: Smartphone },
  { id: "airtel", label: "Airtel Money", icon: Smartphone },
  { id: "card", label: "Card", icon: CreditCard },
];

export function TopUpDialog({ trigger }: { trigger: ReactNode }) {
  const qc = useQueryClient();
  const topUp = useServerFn(topUpCredits);
  const [open, setOpen] = useState(false);
  const [pack, setPack] = useState("growth");
  const [method, setMethod] = useState("mpesa");
  const [phone, setPhone] = useState("");
  const [loading, setLoading] = useState(false);

  const selected = PACKS.find((p) => p.id === pack)!;

  const confirm = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      await topUp({ data: {
        pack: pack as "starter" | "growth" | "scale" | "enterprise",
        method: method as "mpesa" | "mtn" | "airtel" | "card",
      } });
      toast.success(`Payment confirmed — ${selected.sms.toLocaleString()} SMS added`);
      setOpen(false);
      qc.invalidateQueries({ queryKey: ["profile"] });
      qc.invalidateQueries({ queryKey: ["dashboard-stats"] });
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Top-up failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{trigger}</DialogTrigger>
      <DialogContent className="sm:max-w-xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2"><Zap className="h-5 w-5 text-accent" /> Top up SMS credits</DialogTitle>
          <DialogDescription>Choose a package and payment method. Credits are added instantly on confirmation.</DialogDescription>
        </DialogHeader>
        <form onSubmit={confirm} className="space-y-5">
          <div>
            <Label className="mb-2 block text-xs uppercase tracking-wider text-muted-foreground">Package</Label>
            <div className="grid grid-cols-2 gap-2">
              {PACKS.map((p) => (
                <button
                  type="button"
                  key={p.id}
                  onClick={() => setPack(p.id)}
                  className={cn(
                    "relative rounded-xl border p-3 text-left transition",
                    pack === p.id ? "border-primary bg-primary/5 ring-2 ring-primary/30" : "border-border hover:border-primary/50"
                  )}
                >
                  {p.popular && <span className="absolute right-2 top-2 rounded-full bg-accent px-2 py-0.5 text-[10px] font-medium text-accent-foreground">Popular</span>}
                  <div className="text-sm font-semibold">{p.label}</div>
                  <div className="font-display text-lg font-bold">{p.sms.toLocaleString()} SMS</div>
                  <div className="text-xs text-muted-foreground">UGX {p.price.toLocaleString()}</div>
                </button>
              ))}
            </div>
          </div>

          <div>
            <Label className="mb-2 block text-xs uppercase tracking-wider text-muted-foreground">Payment method</Label>
            <div className="grid grid-cols-4 gap-2">
              {METHODS.map((m) => (
                <button
                  type="button"
                  key={m.id}
                  onClick={() => setMethod(m.id)}
                  className={cn(
                    "flex flex-col items-center gap-1 rounded-xl border p-3 text-xs transition",
                    method === m.id ? "border-primary bg-primary/5" : "border-border hover:border-primary/50"
                  )}
                >
                  <m.icon className="h-4 w-4" />
                  {m.label}
                </button>
              ))}
            </div>
          </div>

          {method !== "card" ? (
            <div>
              <Label htmlFor="phone">Mobile money number</Label>
              <Input id="phone" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+256 7XX XXX XXX" required />
              <p className="mt-1 text-xs text-muted-foreground">You'll receive a prompt on your phone to confirm UGX {selected.price.toLocaleString()}.</p>
            </div>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2">
              <div className="sm:col-span-2"><Label>Card number</Label><Input placeholder="4242 4242 4242 4242" required /></div>
              <div><Label>Expiry</Label><Input placeholder="MM/YY" required /></div>
              <div><Label>CVC</Label><Input placeholder="123" required /></div>
            </div>
          )}

          <div className="flex items-center justify-between rounded-xl bg-muted/50 p-3">
            <div className="text-sm">
              <div className="text-muted-foreground">Total</div>
              <div className="font-display text-xl font-bold">UGX {selected.price.toLocaleString()}</div>
            </div>
            <Button type="submit" disabled={loading} className="bg-gradient-brand text-primary-foreground">
              <Check className="mr-2 h-4 w-4" /> {loading ? "Processing..." : "Confirm payment"}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
