"use client";

import { useEffect, useState } from "react";

// Minimal shape of the Razorpay Checkout global we use.
interface RazorpayOptions {
  key: string;
  subscription_id: string;
  name: string;
  description: string;
  image?: string; // brand logo shown in the checkout header
  handler: (resp: RazorpayResponse) => void;
  prefill?: { name?: string; email?: string; contact?: string };
  notes?: Record<string, string>;
  theme?: { color?: string };
  modal?: { ondismiss?: () => void };
}
interface RazorpayResponse {
  razorpay_payment_id: string;
  razorpay_subscription_id: string;
  razorpay_signature: string;
}
interface RazorpayInstance {
  open: () => void;
  on: (event: string, cb: (resp: unknown) => void) => void;
}
declare global {
  interface Window {
    Razorpay?: new (options: RazorpayOptions) => RazorpayInstance;
  }
}

const CHECKOUT_SRC = "https://checkout.razorpay.com/v1/checkout.js";

function loadCheckout(): Promise<boolean> {
  return new Promise((resolve) => {
    if (typeof window === "undefined") return resolve(false);
    if (window.Razorpay) return resolve(true);

    // Poll for window.Razorpay as a fallback — covers the case where a script
    // tag already exists but its load event already fired (listeners would
    // never run), and slow iOS PWA loads. Resolves as soon as the global
    // appears, or false after a timeout so the caller never hangs.
    let settled = false;
    const done = (ok: boolean) => { if (!settled) { settled = true; resolve(ok); } };

    const existing = document.querySelector(`script[src="${CHECKOUT_SRC}"]`);
    if (!existing) {
      const s = document.createElement("script");
      s.src = CHECKOUT_SRC;
      s.onload = () => done(!!window.Razorpay);
      s.onerror = () => done(false);
      document.body.appendChild(s);
    }

    const start = Date.now();
    const poll = setInterval(() => {
      if (window.Razorpay) { clearInterval(poll); done(true); }
      else if (Date.now() - start > 10000) { clearInterval(poll); done(false); }
    }, 150);
  });
}

export function UpgradeButton({
  email,
  className,
  label = "Upgrade to Premium — ₹199/month",
  onActivating,
}: {
  email?: string;
  className?: string;
  label?: string;
  onActivating?: () => void;
}) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [done, setDone] = useState(false);
  // Auto-prefill from the signed-in user's profile (editable in checkout).
  const [profile, setProfile] = useState<{ name?: string; email?: string; phone?: string }>({});

  // Warm the checkout script + load profile so the first click is instant.
  useEffect(() => {
    loadCheckout();
    fetch("/api/auth/profile", { credentials: "include" })
      .then((r) => r.json())
      .then((d) => {
        if (d.user) setProfile({ name: d.user.name, email: d.user.email, phone: d.user.phone || undefined });
      })
      .catch(() => {});
  }, []);

  const handleUpgrade = async () => {
    setLoading(true);
    setError(null);
    try {
      const ok = await loadCheckout();
      if (!ok || !window.Razorpay) throw new Error("Could not load payment checkout. Check your connection.");

      // 1. Create the subscription server-side.
      const createRes = await fetch("/api/subscriptions/create", { method: "POST" });
      const createData = await createRes.json();
      if (!createRes.ok) throw new Error(createData.error || "Could not start checkout.");

      const { subscriptionId, keyId } = createData as { subscriptionId: string; keyId: string };

      // Build prefill from the explicit prop (if any) + the loaded profile.
      // Razorpay shows these pre-filled but the user can still edit them.
      const prefill: { name?: string; email?: string; contact?: string } = {};
      const prefillEmail = email || profile.email;
      if (profile.name) prefill.name = profile.name;
      if (prefillEmail) prefill.email = prefillEmail;
      if (profile.phone) prefill.contact = profile.phone;

      // 2. Open Razorpay Checkout for the mandate.
      const rzp = new window.Razorpay({
        key: keyId, // id only — never the secret
        subscription_id: subscriptionId,
        name: "Tia",
        description: "Tia Premium — ₹199/month",
        image: `${window.location.origin}/icons/192.png`, // brand logo in checkout header
        prefill: Object.keys(prefill).length ? prefill : undefined,
        theme: { color: "#fb7185" }, // Tia rose (matches app theme-color)
        handler: async (resp) => {
          // 3. Verify for UX feedback only — entitlement comes via webhook.
          try {
            await fetch("/api/subscriptions/verify", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(resp),
            });
          } catch { /* non-fatal — webhook still grants */ }
          setDone(true);
          onActivating?.();
        },
        modal: { ondismiss: () => setLoading(false) },
      });
      rzp.open();
      // The modal is now open — stop showing "Opening checkout…" on the button.
      // (ondismiss already covers cancel; this covers the open state itself so
      // the button never gets stuck, e.g. in an iOS standalone PWA.)
      setLoading(false);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Something went wrong.");
      setLoading(false);
    }
  };

  if (done) {
    return (
      <div className="rounded-xl bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800/40 px-4 py-3 text-sm text-green-700 dark:text-green-300">
        🎉 Payment received! Your premium is activating — it’ll be live within a minute.
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <button
        onClick={handleUpgrade}
        disabled={loading}
        className={
          className ??
          "w-full bg-rose-500 hover:bg-rose-600 disabled:opacity-60 text-white font-semibold px-5 py-3 rounded-xl text-sm transition-colors active:scale-[0.98]"
        }
      >
        {loading ? "Opening checkout…" : label}
      </button>
      {error && <p className="text-xs text-red-500">{error}</p>}
    </div>
  );
}
