"use client";

import { useCallback, useEffect, useState } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { getApiErrorMessage } from "@/lib/api-error";
import ClientWorkspaceLayout from "@/features/client/client-workspace-layout";
import { tenantHref } from "@/lib/tenant-routing";
import {
  activateFreePlan,
  cancelSubscription,
  fetchBillingCatalog,
  fetchBillingOverview,
  formatMoney,
  openBillingPortal,
  startCheckout,
  type BillingOverview,
  type CatalogProduct,
} from "@/platform/api/billing-api";

export default function BillingCenter() {
  return (
    <ClientWorkspaceLayout title="Billing">
      {(ctx) => (
        <BillingCenterPanel
          orgKey={
            ctx.tenantApiKey === "me" ? ctx.tenantClientId || "" : ctx.effectiveClientKey
          }
        />
      )}
    </ClientWorkspaceLayout>
  );
}

function BillingCenterPanel({ orgKey }: { orgKey: string }) {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const [overview, setOverview] = useState<BillingOverview | null>(null);
  const [catalog, setCatalog] = useState<CatalogProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!orgKey) return;
    setLoading(true);
    try {
      const [ov, cat] = await Promise.all([
        fetchBillingOverview(orgKey),
        fetchBillingCatalog(orgKey),
      ]);
      setOverview(ov);
      setCatalog(cat);
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Failed to load billing"));
    } finally {
      setLoading(false);
    }
  }, [orgKey]);

  useEffect(() => {
    load();
  }, [load]);

  useEffect(() => {
    const checkout = searchParams.get("checkout");
    if (checkout === "success") {
      toast.success("Subscription updated — refreshing billing status…");
      load();
      window.dispatchEvent(new CustomEvent("nizamify:modules-changed"));
    } else if (checkout === "cancel") {
      toast.message("Checkout canceled");
    }
  }, [searchParams, load]);

  const billingReturnUrl = () => {
    const path = tenantHref(pathname || "", "/billing", "client");
    const origin = typeof window !== "undefined" ? window.location.origin : "";
    return `${origin}${path}`;
  };

  const onPortal = async () => {
    try {
      setBusy("portal");
      const { url } = await openBillingPortal(orgKey, billingReturnUrl());
      window.location.href = url;
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Could not open billing portal"));
    } finally {
      setBusy(null);
    }
  };

  const onSubscribe = async (product: CatalogProduct, planId: string, priceId: string) => {
    try {
      setBusy(`${product.moduleId}-${planId}`);
      const plan = product.plans.find((p) => p._id === planId);
      if (plan?.billingMode === "free") {
        await activateFreePlan(orgKey, planId, product.moduleId || "");
        toast.success("Free plan activated");
        await load();
        window.dispatchEvent(new CustomEvent("nizamify:modules-changed"));
        return;
      }
      const base = billingReturnUrl();
      const { url } = await startCheckout(
        orgKey,
        planId,
        priceId,
        `${base}?checkout=success`,
        `${base}?checkout=cancel`,
      );
      window.location.href = url;
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Could not start checkout"));
    } finally {
      setBusy(null);
    }
  };

  const onCancel = async (subscriptionId: string) => {
    try {
      setBusy(`cancel-${subscriptionId}`);
      await cancelSubscription(orgKey, subscriptionId);
      toast.success("Subscription will cancel at period end");
      await load();
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Could not cancel subscription"));
    } finally {
      setBusy(null);
    }
  };

  if (loading) {
    return <p className="text-center text-gray-500 py-8">Loading billing…</p>;
  }

  return (
    <div className="space-y-8">
      <section className="rounded-lg border bg-white p-6 space-y-4">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 className="text-lg font-semibold">Overview</h2>
            <p className="text-sm text-muted-foreground">
              {overview?.stripeConfigured
                ? "Stripe billing is connected."
                : "Stripe is not configured — paid checkout is unavailable until STRIPE_SECRET_KEY is set."}
            </p>
          </div>
          {overview?.stripeConfigured && overview.stripeCustomerId && (
            <Button variant="outline" disabled={busy === "portal"} onClick={onPortal}>
              Manage payment methods & invoices
            </Button>
          )}
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="rounded-md border p-4">
            <p className="text-sm text-muted-foreground">Active subscriptions</p>
            <p className="text-2xl font-semibold">{overview?.subscriptions?.length || 0}</p>
          </div>
          <div className="rounded-md border p-4">
            <p className="text-sm text-muted-foreground">Credit balance</p>
            <p className="text-2xl font-semibold">{overview?.wallet?.balance ?? 0}</p>
          </div>
        </div>

        {overview?.subscriptions?.length ? (
          <div className="space-y-2">
            <h3 className="font-medium text-sm">Current subscriptions</h3>
            <ul className="divide-y rounded-md border">
              {overview.subscriptions.map((sub) => (
                <li key={sub._id} className="flex flex-wrap items-center justify-between gap-2 p-3 text-sm">
                  <div>
                    <p className="font-medium">
                      {sub.planId?.productId?.name || sub.moduleId || "Module"}
                    </p>
                    <p className="text-muted-foreground">
                      {sub.planId?.name} · {sub.status}
                      {sub.cancelAtPeriodEnd ? " · cancels at period end" : ""}
                    </p>
                  </div>
                  {sub.status === "active" && !sub.cancelAtPeriodEnd && (
                    <Button
                      size="sm"
                      variant="ghost"
                      disabled={busy === `cancel-${sub._id}`}
                      onClick={() => onCancel(sub._id)}
                    >
                      Cancel at period end
                    </Button>
                  )}
                </li>
              ))}
            </ul>
          </div>
        ) : null}

        {overview?.recentInvoices?.length ? (
          <div className="space-y-2">
            <h3 className="font-medium text-sm">Recent invoices</h3>
            <ul className="divide-y rounded-md border text-sm">
              {overview.recentInvoices.map((inv) => (
                <li key={inv.id} className="flex items-center justify-between p-3">
                  <span>
                    {inv.number || inv.id} · {inv.status}
                  </span>
                  <span>
                    {inv.amountDue != null ? formatMoney(inv.amountDue, inv.currency || "usd") : "—"}
                    {inv.hostedInvoiceUrl ? (
                      <a
                        href={inv.hostedInvoiceUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="ml-3 text-primary underline"
                      >
                        View
                      </a>
                    ) : null}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </section>

      <section className="space-y-4">
        <h2 className="text-lg font-semibold">Plans by module</h2>
        {catalog.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            No billing catalog yet. Run{" "}
            <code className="text-xs bg-gray-100 px-1 rounded">npm run migrate:platform-phase4</code>{" "}
            on the backend.
          </p>
        ) : (
          <div className="grid gap-4 lg:grid-cols-2">
            {catalog.map((product) => (
              <article key={product._id} className="rounded-lg border bg-white p-5 space-y-3">
                <div>
                  <h3 className="font-semibold">{product.moduleName || product.name}</h3>
                  {product.currentSubscription ? (
                    <p className="text-xs text-muted-foreground">
                      Current: {product.currentSubscription.status}
                      {product.currentSubscription.cancelAtPeriodEnd
                        ? " (canceling)"
                        : ""}
                    </p>
                  ) : (
                    <p className="text-xs text-muted-foreground">No active subscription</p>
                  )}
                </div>
                <ul className="space-y-2">
                  {product.plans.map((plan) => (
                    <li key={plan._id} className="rounded border p-3 text-sm">
                      <p className="font-medium">{plan.name}</p>
                      <p className="text-muted-foreground capitalize">{plan.billingMode}</p>
                      <div className="mt-2 flex flex-wrap gap-2">
                        {plan.billingMode === "free" ? (
                          <Button
                            size="sm"
                            disabled={busy === `${product.moduleId}-${plan._id}`}
                            onClick={() => onSubscribe(product, plan._id, "")}
                          >
                            Activate free
                          </Button>
                        ) : (
                          plan.prices.map((price) => (
                            <Button
                              key={price._id}
                              size="sm"
                              disabled={
                                !overview?.stripeConfigured ||
                                busy === `${product.moduleId}-${plan._id}`
                              }
                              onClick={() => onSubscribe(product, plan._id, price._id)}
                            >
                              {formatMoney(price.amount, price.currency)} / {price.interval}
                            </Button>
                          ))
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              </article>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}
