import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import {
  ArrowLeft,
  Building2,
  Check,
  CreditCard,
  Loader2,
  ShieldCheck,
  Smartphone,
} from "lucide-react";
import { z } from "zod";
import { useBusiness } from "@/lib/business-context";
import { Card, PartnerShell, inputClass } from "@/components/partner/PartnerShell";
import { changePlan } from "@/lib/partner.functions";
import { PLANS } from "@/lib/partner-catalog";

const searchSchema = z.object({
  plan: z.string().optional(),
  mode: z.enum(["upgrade", "renew"]).optional(),
});

export const Route = createFileRoute("/_partner/partner/billing_/checkout")({
  validateSearch: (search) => searchSchema.parse(search),
  head: () => ({
    meta: [
      { title: "Confirm & pay — Airfis Partner" },
      {
        name: "description",
        content: "Confirm your Airfis plan and pay securely with UPI, cards or net banking.",
      },
      { property: "og:title", content: "Confirm & pay — Airfis Partner" },
      { property: "og:description", content: "Review your plan and complete payment." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: CheckoutPage,
});

const METHODS = [
  {
    id: "upi",
    label: "UPI / GPay / PhonePe",
    blurb: "Pay instantly from any UPI app",
    icon: Smartphone,
  },
  {
    id: "card",
    label: "Credit / Debit card",
    blurb: "Visa, Mastercard, RuPay, Amex",
    icon: CreditCard,
  },
  { id: "netbanking", label: "Net banking", blurb: "All major Indian banks", icon: Building2 },
] as const;

function CheckoutPage() {
  const { plan: planParam, mode = "upgrade" } = Route.useSearch();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { activeId } = useBusiness();
  const switchPlan = useServerFn(changePlan);

  const plan =
    PLANS.find((p) => p.name.toLowerCase() === (planParam ?? "").toLowerCase()) ?? PLANS[1];
  const [method, setMethod] = useState<string>("upi");
  const [upi, setUpi] = useState("");
  const [card, setCard] = useState({ number: "", name: "", expiry: "", cvv: "" });
  const [bank, setBank] = useState("HDFC Bank");
  const [paying, setPaying] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const gst = Math.round(plan.price * 0.18);
  const total = plan.price + gst;
  const newExpiry = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toLocaleDateString("en-IN", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });

  async function payNow() {
    setPaying(true);
    setError(null);
    try {
      await new Promise((r) => setTimeout(r, 1200));
      await switchPlan({
        data: {
          businessId: activeId,
          planName: plan.name,
          price: plan.price,
          features: plan.features,
          limits: plan.limits,
        },
      });
      await qc.invalidateQueries({ queryKey: ["partner"] });
      setDone(true);
      setTimeout(() => void navigate({ to: "/partner/billing" }), 1400);
    } catch {
      setError("We could not complete the payment. Please check your details and try again.");
    } finally {
      setPaying(false);
    }
  }

  return (
    <PartnerShell
      title={mode === "renew" ? "Renew your plan" : "Confirm & pay"}
      description="Review your plan and complete the payment"
    >
      <button
        type="button"
        onClick={() => void navigate({ to: "/partner/billing" })}
        className="mb-4 inline-flex items-center gap-1.5 text-sm font-semibold text-ink-2 hover:text-ink"
      >
        <ArrowLeft className="h-4 w-4" /> Back to subscription
      </button>

      {done ? (
        <Card className="border-0 py-16 text-center">
          <span className="mx-auto inline-flex h-14 w-14 items-center justify-center rounded-full bg-[#ffebe3] text-[#FF4308]">
            <Check className="h-7 w-7" />
          </span>
          <h3 className="mt-4 text-lg font-bold text-ink">
            {mode === "renew" ? "Plan renewed" : "Payment successful"}
          </h3>
          <p className="mt-1 text-sm text-ink-2">
            {mode === "renew"
              ? `Your ${plan.name} plan has been renewed until ${newExpiry}. Taking you back to your subscription…`
              : `Your ${plan.name} plan is active for the next 30 days. Taking you back to your subscription…`}
          </p>
        </Card>
      ) : (
        <div className="grid gap-6 lg:grid-cols-[1.4fr_1fr]">
          <Card className="border-0">
            <h3 className="font-bold text-ink">Payment method</h3>
            <div className="mt-4 space-y-2">
              {METHODS.map((m) => {
                const active = method === m.id;
                return (
                  <button
                    key={m.id}
                    type="button"
                    onClick={() => setMethod(m.id)}
                    className={`flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left transition-colors ${
                      active
                        ? "bg-[#ffebe3] text-[#FF4308]"
                        : "bg-surface text-ink hover:bg-[#f0f0f1]"
                    }`}
                  >
                    <span
                      className={`inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${active ? "bg-white/70" : "bg-white"}`}
                    >
                      <m.icon className="h-[18px] w-[18px]" />
                    </span>
                    <span className="min-w-0">
                      <span className="block text-sm font-semibold">{m.label}</span>
                      <span
                        className={`block text-xs ${active ? "text-[#FF4308]/80" : "text-ink-2"}`}
                      >
                        {m.blurb}
                      </span>
                    </span>
                    <span className="ml-auto">{active && <Check className="h-4 w-4" />}</span>
                  </button>
                );
              })}
            </div>

            <div className="mt-5">
              {method === "upi" && (
                <Field label="UPI ID">
                  <input
                    value={upi}
                    onChange={(e) => setUpi(e.target.value)}
                    placeholder="yourname@okicici"
                    className={inputClass}
                  />
                  <p className="mt-2 text-xs text-ink-2">
                    You will get a collect request in GPay, PhonePe or Paytm.
                  </p>
                </Field>
              )}
              {method === "card" && (
                <div className="grid gap-3 sm:grid-cols-2">
                  <Field label="Card number" className="sm:col-span-2">
                    <input
                      value={card.number}
                      onChange={(e) => setCard({ ...card, number: e.target.value })}
                      placeholder="1234 5678 9012 3456"
                      inputMode="numeric"
                      className={inputClass}
                    />
                  </Field>
                  <Field label="Name on card" className="sm:col-span-2">
                    <input
                      value={card.name}
                      onChange={(e) => setCard({ ...card, name: e.target.value })}
                      placeholder="Full name"
                      className={inputClass}
                    />
                  </Field>
                  <Field label="Expiry">
                    <input
                      value={card.expiry}
                      onChange={(e) => setCard({ ...card, expiry: e.target.value })}
                      placeholder="MM/YY"
                      className={inputClass}
                    />
                  </Field>
                  <Field label="CVV">
                    <input
                      value={card.cvv}
                      onChange={(e) => setCard({ ...card, cvv: e.target.value })}
                      placeholder="123"
                      className={inputClass}
                    />
                  </Field>
                </div>
              )}
              {method === "netbanking" && (
                <Field label="Select your bank">
                  <select
                    value={bank}
                    onChange={(e) => setBank(e.target.value)}
                    className={inputClass}
                  >
                    {[
                      "HDFC Bank",
                      "ICICI Bank",
                      "State Bank of India",
                      "Axis Bank",
                      "Kotak Mahindra Bank",
                      "Yes Bank",
                    ].map((b) => (
                      <option key={b}>{b}</option>
                    ))}
                  </select>
                </Field>
              )}

              <div className="mt-5 rounded-2xl border border-hairline bg-surface p-4 text-xs text-ink-2 flex items-start gap-3">
                <ShieldCheck className="h-4 w-4 text-[#FF4308] shrink-0 mt-0.5" />
                <span>
                  After selecting your payment method, click <strong>Pay now</strong> to securely connect to <strong>Razorpay</strong> to complete your transaction.
                </span>
              </div>
            </div>
          </Card>

          <Card className="border-0">
            <h3 className="font-bold text-ink">Order summary</h3>
            <p className="mt-3 text-sm text-ink-2">
              {mode === "renew" ? "Confirm renewal of" : "Switching to"}
            </p>
            <p className="text-lg font-bold capitalize text-ink">{plan.name} plan</p>
            <ul className="mt-3 space-y-2">
              {plan.features.map((f) => (
                <li key={f} className="flex items-start gap-2 text-sm text-ink-2">
                  <Check className="mt-0.5 h-4 w-4 shrink-0 text-[#FF4308]" /> {f}
                </li>
              ))}
            </ul>
            <div className="mt-5 space-y-2 text-sm">
              {mode === "renew" && <Row label="Renewal period" value="30 days" />}
              {mode === "renew" && <Row label="New expiry date" value={newExpiry} />}
              <Row label={`Plan (30 days)`} value={`₹${plan.price.toLocaleString("en-IN")}`} />
              <Row label="GST 18%" value={`₹${gst.toLocaleString("en-IN")}`} />
              <div className="h-px bg-line" />
              <div className="flex items-center justify-between pt-1">
                <span className="font-semibold text-ink">Total payable</span>
                <span className="text-lg font-bold text-ink">₹{total.toLocaleString("en-IN")}</span>
              </div>
            </div>
            <button
              type="button"
              onClick={() => void payNow()}
              disabled={paying}
              className="btn-brand mt-5 w-full flex items-center justify-center gap-2"
            >
              {paying ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Connecting to Razorpay…
                </>
              ) : total > 0 ? (
                `Pay now ₹${total.toLocaleString("en-IN")}`
              ) : (
                "Confirm plan"
              )}
            </button>
            {error && (
              <p className="mt-3 rounded-xl bg-[#ffebe3] px-3 py-2 text-xs font-semibold text-[#FF4308]">
                {error}
              </p>
            )}
            <p className="mt-3 flex items-center justify-center gap-1.5 text-xs text-ink-2">
              <ShieldCheck className="h-3.5 w-3.5 text-emerald-600" /> Powered by Razorpay · 256-bit secure encryption
            </p>
          </Card>
        </div>
      )}
    </PartnerShell>
  );
}

function Field({
  label,
  children,
  className = "",
}: {
  label: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <label className={`block ${className}`}>
      <span className="text-sm font-semibold text-ink">{label}</span>
      <div className="mt-1.5">{children}</div>
    </label>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-ink-2">{label}</span>
      <span className="font-semibold text-ink">{value}</span>
    </div>
  );
}
