import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Plus, Pencil, Trash2, X, Wallet, Bitcoin } from "lucide-react";
import { toast } from "sonner";
import { AdminShell } from "@/components/admin/AdminShell";
import {
  listPaymentMethodsAdmin, upsertPaymentMethod, deletePaymentMethod,
} from "@/lib/payments.functions";

export const Route = createFileRoute("/admin/payments")({
  head: () => ({ meta: [{ title: "Payments · Admin" }] }),
  component: PaymentsPage,
});

type Form = {
  id?: string;
  label: string;
  type: "upi" | "crypto";
  address: string;
  qr_url: string;
  active: boolean;
};
const empty: Form = { label: "", type: "upi", address: "", qr_url: "", active: true };

function PaymentsPage() {
  const fetchAll = useServerFn(listPaymentMethodsAdmin);
  const upsert = useServerFn(upsertPaymentMethod);
  const del = useServerFn(deletePaymentMethod);
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: ["admin-payments"], queryFn: () => fetchAll() });
  const [editing, setEditing] = useState<Form | null>(null);

  const save = useMutation({
    mutationFn: (f: Form) => upsert({ data: { ...f, qr_url: f.qr_url || null } }),
    onSuccess: () => {
      toast.success("Saved");
      setEditing(null);
      qc.invalidateQueries({ queryKey: ["admin-payments"] });
    },
    onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
  });
  const remove = useMutation({
    mutationFn: (id: string) => del({ data: { id } }),
    onSuccess: () => { toast.success("Deleted"); qc.invalidateQueries({ queryKey: ["admin-payments"] }); },
  });

  return (
    <AdminShell title="Payment Methods" subtitle="UPI IDs and crypto wallets shown to users at checkout">
      <div className="flex justify-end mb-6">
        <button onClick={() => setEditing(empty)} className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold tracking-wide glow-hover">
          <Plus className="w-4 h-4" /> Add Method
        </button>
      </div>

      {isLoading ? (
        <p className="p-10 text-center text-sm text-muted-foreground">Loading…</p>
      ) : (data?.methods ?? []).length === 0 ? (
        <div className="glass-strong rounded-2xl border border-border p-10 text-center text-sm text-muted-foreground">
          No payment methods yet. Add UPI or a crypto wallet to receive orders.
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {data!.methods.map((m) => (
            <div key={m.id} className="glass-strong rounded-2xl border border-border p-5 relative">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary/30 to-accent/30 flex items-center justify-center">
                  {m.type === "upi" ? <Wallet className="w-5 h-5 text-primary" /> : <Bitcoin className="w-5 h-5 text-primary" />}
                </div>
                <div className="flex-1">
                  <div className="font-display font-bold">{m.label}</div>
                  <div className="text-[10px] uppercase tracking-widest text-muted-foreground">{m.type}</div>
                </div>
                <span className={`text-[10px] px-2 py-0.5 rounded-full font-bold ${m.active ? "bg-green-500/20 text-green-400" : "bg-muted text-muted-foreground"}`}>
                  {m.active ? "Active" : "Off"}
                </span>
              </div>
              <p className="text-xs text-muted-foreground break-all mb-4">{m.address}</p>
              <div className="flex gap-2">
                <button onClick={() => setEditing({ id: m.id, label: m.label, type: m.type, address: m.address, qr_url: m.qr_url ?? "", active: m.active })} className="flex-1 inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg glass border border-border text-xs font-semibold">
                  <Pencil className="w-3 h-3" /> Edit
                </button>
                <button onClick={() => confirm(`Delete ${m.label}?`) && remove.mutate(m.id)} className="px-3 py-1.5 rounded-lg glass border border-border text-xs text-destructive">
                  <Trash2 className="w-3 h-3" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {editing && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-background/80 backdrop-blur-md">
          <div className="glass-strong rounded-2xl p-6 border border-primary/30 w-full max-w-md">
            <div className="flex items-center justify-between mb-5">
              <h2 className="font-display text-xl font-bold">{editing.id ? "Edit" : "Add"} Method</h2>
              <button onClick={() => setEditing(null)} className="p-1 rounded-lg hover:bg-muted"><X className="w-4 h-4" /></button>
            </div>
            <form onSubmit={(e) => { e.preventDefault(); save.mutate(editing); }} className="space-y-4">
              <Field label="Label"><input required value={editing.label} onChange={(e) => setEditing({ ...editing, label: e.target.value })} className={inputCls} /></Field>
              <Field label="Type">
                <select value={editing.type} onChange={(e) => setEditing({ ...editing, type: e.target.value as "upi" | "crypto" })} className={inputCls}>
                  <option value="upi">UPI</option>
                  <option value="crypto">Crypto</option>
                </select>
              </Field>
              <Field label={editing.type === "upi" ? "UPI ID" : "Wallet address"}>
                <input required value={editing.address} onChange={(e) => setEditing({ ...editing, address: e.target.value })} className={inputCls} />
              </Field>
              <Field label="QR image URL (optional)">
                <input value={editing.qr_url} onChange={(e) => setEditing({ ...editing, qr_url: e.target.value })} placeholder="https://…" className={inputCls} />
              </Field>
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={editing.active} onChange={(e) => setEditing({ ...editing, active: e.target.checked })} />
                Active (visible at checkout)
              </label>
              <div className="flex justify-end gap-2 pt-2">
                <button type="button" onClick={() => setEditing(null)} className="px-4 py-2 rounded-xl glass border border-border text-sm">Cancel</button>
                <button disabled={save.isPending} className="px-5 py-2 rounded-xl bg-gradient-to-r from-primary to-accent text-primary-foreground font-bold disabled:opacity-50">{save.isPending ? "Saving…" : "Save"}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </AdminShell>
  );
}
const inputCls = "w-full px-3 py-2 rounded-lg glass border border-border focus:border-primary outline-none text-sm";
function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return <label className="block"><span className="block text-[11px] uppercase tracking-widest text-muted-foreground mb-1">{label}</span>{children}</label>;
}
