import type { Metadata } from "next";
import { requireAuth } from "@/lib/auth/guards";
import { getEffectivePlan, getActiveSubscription } from "@/lib/billing/subscription";
import { isStripeConfigured } from "@/lib/billing/stripe";
import { isPaypalConfigured } from "@/lib/billing/paypal";
import { PageHeader } from "@/components/app/page-header";
import { BillingClient } from "@/components/app/billing-client";

export const metadata: Metadata = { title: "Billing" };

export default async function BillingPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  const session = await requireAuth();
  const { status } = await searchParams;
  const { key: currentPlan } = await getEffectivePlan(
    session.user.id,
    session.session.activeOrganizationId
  );
  const sub = await getActiveSubscription(session.user.id);

  return (
    <>
      <PageHeader title="Billing" description="Manage your plan and payment method." />

      {status === "success" && (
        <div className="mb-6 rounded-2xl border border-success/30 bg-success/10 px-4 py-3 text-sm font-medium text-success">
          Payment received — your plan will update momentarily once the provider confirms.
        </div>
      )}
      {status === "cancel" && (
        <div className="mb-6 rounded-2xl border border-warning/30 bg-warning/10 px-4 py-3 text-sm font-medium text-warning">
          Checkout canceled. No changes were made.
        </div>
      )}

      <BillingClient
        currentPlan={currentPlan}
        subscription={
          sub
            ? {
                provider: sub.provider,
                status: sub.status,
                cancelAtPeriodEnd: sub.cancelAtPeriodEnd,
                periodEnd: sub.periodEnd ? sub.periodEnd.toISOString() : null,
              }
            : null
        }
        stripeConfigured={isStripeConfigured()}
        paypalConfigured={isPaypalConfigured()}
      />
    </>
  );
}
