import { createResource, createSignal, Show, For } from "solid-js";
import { useNavigate } from "@solidjs/router";
import DashboardLayout from "~/components/DashboardLayout";
import { api } from "~/lib/api";

interface Package {
  id: string;
  name: string;
  tracecoins_amount: number;
  price_inr: number;
  description: string;
}

export default function BuyTracecoinsPage() {
  const navigate = useNavigate();
  const [selectedPackage, setSelectedPackage] = createSignal<Package | null>(null);
  const [loading, setLoading] = createSignal(false);
  const [error, setError] = createSignal("");
  const [success, setSuccess] = createSignal(false);

  const resolveRoleKey = () => {
    if (typeof window === "undefined") return "DEVELOPER";
    const fromUrl = new URLSearchParams(window.location.search).get("role");
    if (fromUrl && fromUrl.trim()) return fromUrl.trim().toUpperCase();
    const keys = ["nxtgauge_signup_profile_v1", "nxtgauge_auth_user", "nxtgauge_user"];
    for (const key of keys) {
      try {
        const raw = window.localStorage.getItem(key) || window.sessionStorage.getItem(key);
        if (!raw) continue;
        const parsed = JSON.parse(raw);
        const candidate = String(
          parsed?.selectedProfessionalRole || parsed?.active_role || parsed?.roleKey || parsed?.role || ""
        )
          .trim()
          .toUpperCase();
        if (candidate && candidate !== "PROFESSIONAL") return candidate;
      } catch {
        // ignore malformed storage payloads
      }
    }
    return "DEVELOPER";
  };

  const [packages] = createResource(async () => {
    const roleKey = resolveRoleKey();
    const res = await api.get(`/pricing/packages?role=${encodeURIComponent(roleKey)}&roleKey=${encodeURIComponent(roleKey)}`);
    return res.data?.packages || [];
  });

  const handlePurchase = async () => {
    const pkg = selectedPackage();
    if (!pkg) return;

    setLoading(true);
    setError("");

    try {
      // Step 1: Create order via Beeceptor
      const orderRes = await api.post("/payments/order", {
        package_id: pkg.id,
        amount: pkg.price_inr,
        currency: "INR",
      });

      const { order_id, amount, currency } = orderRes.data;

      // Step 2: Simulate Razorpay payment with Beeceptor
      const paymentRes = await fetch("https://nxtgauge.free.beeceptor.com/payment", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          order_id,
          amount,
          currency,
          status: "captured",
        }),
      });

      const paymentData = await paymentRes.json();

      if (paymentData.status !== "captured") {
        throw new Error("Payment failed");
      }

      // Step 3: Verify payment with our backend
      await api.post("/payments/verify", {
        order_id,
        payment_id: paymentData.payment_id || "pay_test_" + Date.now(),
        signature: "test_signature",
      });

      setSuccess(true);
      setTimeout(() => {
        navigate("/dashboard/wallet");
      }, 2000);
    } catch (e: any) {
      setError(e.message || "Payment failed. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const formatPrice = (paise: number) => {
    return `₹${(paise / 100).toLocaleString()}`;
  };

  return (
    <DashboardLayout>
      <div class="p-6 max-w-4xl mx-auto">
        <h1 class="text-2xl font-bold mb-2">Buy Tracecoins</h1>
        <p class="text-gray-600 mb-6">Purchase Tracecoins to send lead requests to customers</p>

        <Show when={success()}>
          <div class="bg-green-50 border border-green-200 rounded-xl p-6 mb-6 text-center">
            <div class="text-5xl mb-3">🎉</div>
            <h2 class="text-xl font-bold text-green-800 mb-2">Payment Successful!</h2>
            <p class="text-green-700">Tracecoins have been added to your wallet.</p>
          </div>
        </Show>

        <Show when={error()}>
          <div class="bg-red-50 border border-red-200 rounded-xl p-4 mb-6">
            <p class="text-red-700">{error()}</p>
          </div>
        </Show>

        <Show when={!success()}>
          <Show when={packages.loading}>
            <div class="text-center py-12">
              <div class="animate-spin w-8 h-8 border-2 border-orange-500 border-t-transparent rounded-full mx-auto mb-4" />
              <p class="text-gray-500">Loading packages...</p>
            </div>
          </Show>

          <Show when={!packages.loading}>
            <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
              <For each={packages() || []}>
                {(pkg: Package) => (
                  <div
                    onClick={() => setSelectedPackage(pkg)}
                    class={`border-2 rounded-xl p-6 cursor-pointer transition-all ${
                      selectedPackage()?.id === pkg.id
                        ? "border-orange-500 bg-orange-50"
                        : "border-gray-200 hover:border-orange-300"
                    }`}
                  >
                    <div class="flex justify-between items-start mb-4">
                      <h3 class="font-bold text-lg">{pkg.name}</h3>
                      <Show when={selectedPackage()?.id === pkg.id}>
                        <span class="text-orange-500">✓</span>
                      </Show>
                    </div>

                    <div class="mb-4">
                      <span class="text-3xl font-bold text-gray-900">{pkg.tracecoins_amount}</span>
                      <span class="text-gray-500 ml-1">TC</span>
                    </div>

                    <p class="text-2xl font-bold text-orange-600 mb-3">
                      {formatPrice(pkg.price_inr)}
                    </p>

                    <p class="text-sm text-gray-600">{pkg.description}</p>
                  </div>
                )}
              </For>
            </div>

            <Show when={selectedPackage()}>
              <div class="bg-gray-50 rounded-xl p-6 mb-6">
                <h3 class="font-semibold mb-4">Order Summary</h3>
                <div class="flex justify-between mb-2">
                  <span>{selectedPackage()?.name}</span>
                  <span>{formatPrice(selectedPackage()?.price_inr || 0)}</span>
                </div>
                <div class="border-t pt-2 mt-2">
                  <div class="flex justify-between font-bold text-lg">
                    <span>Total</span>
                    <span>{formatPrice(selectedPackage()?.price_inr || 0)}</span>
                  </div>
                </div>
              </div>

              <div class="flex gap-4">
                <button
                  onClick={() => navigate("/dashboard/wallet")}
                  class="flex-1 px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handlePurchase}
                  disabled={loading()}
                  class="flex-1 px-6 py-3 bg-orange-500 text-white rounded-lg hover:bg-orange-600 disabled:opacity-50"
                >
                  <Show when={loading()} fallback="Pay Now">
                    Processing...
                  </Show>
                </button>
              </div>
            </Show>
          </Show>
        </Show>
      </div>
    </DashboardLayout>
  );
}
