import { getLocale, getTranslations } from "next-intl/server";
import { headers } from "next/headers";

import { CancelScheduledBanner } from "@/components/billing/cancel-scheduled-banner";
import { CurrentPlanBanner } from "@/components/billing/current-plan-banner";
import { PastDueBanner } from "@/components/billing/past-due-banner";
import { PortalButton } from "@/components/billing/portal-button";
import { PricingTable } from "@/components/billing/pricing-table";
import { requireOrgMember } from "@/lib/auth-guards";
import { detectCurrencyFromHeaders, type Currency } from "@/lib/billing/currency";
import { getCurrencyCookie } from "@/lib/billing/currency-cookie";
import { ensureOrgSubscription } from "@/lib/billing/ensure-subscription";

export default async function BillingSettingsPage() {
  const { activeOrganizationId } = await requireOrgMember({ minRole: "owner" });
  const t = await getTranslations("Settings.billing");
  const locale = await getLocale();
  const requestHeaders = await headers();
  const cookieCurrency = await getCurrencyCookie();
  const currency: Currency = cookieCurrency ?? detectCurrencyFromHeaders(requestHeaders);

  const sub = await ensureOrgSubscription(activeOrganizationId);

  const isPaying = sub.plan !== "free";
  const isPastDue = sub.status === "past_due";

  return (
    <section className="flex flex-col gap-6">
      <div className="flex flex-col gap-1">
        <h2 className="text-xl font-semibold">{t("title")}</h2>
        <p className="text-sm text-muted-foreground">{t("description")}</p>
      </div>

      {isPastDue && <PastDueBanner />}
      {sub.cancelAtPeriodEnd && sub.currentPeriodEnd && (
        <CancelScheduledBanner plan={sub.plan} endsAt={sub.currentPeriodEnd} />
      )}

      <CurrentPlanBanner
        plan={sub.plan}
        interval={sub.interval}
        currentPeriodEnd={sub.currentPeriodEnd}
        cancelAtPeriodEnd={sub.cancelAtPeriodEnd}
      />

      <PricingTable initialCurrency={currency} locale={locale} currentPlan={sub.plan} />

      {isPaying && (
        <div className="flex flex-col gap-2 rounded-lg border p-4">
          <h3 className="text-sm font-semibold">{t("managePortal")}</h3>
          <p className="text-xs text-muted-foreground">{t("managePortalDescription")}</p>
          <PortalButton />
        </div>
      )}
    </section>
  );
}
