/**
 * Billing Management Page - Complete Implementation
 * Shows current plan, upgrade/downgrade options, and invoices
 * Uses new billing APIs: /api/billing/current, /api/billing/plans, /api/billing/invoices
 */

import { redirect } from "next/navigation";
import Link from "next/link";
import { auth } from "@/lib/auth";
import { checkDashboardAccess } from "@/lib/dashboard-access";
import { SITE, type Lang } from "@/lib/config";
import BillingManagementClient from "./BillingManagementClient";

// Force dynamic rendering
export const dynamic = "force-dynamic";
export const revalidate = 0;

export const metadata = {
  title: "Billing & Subscription | Mawidi",
  description: "Manage your subscription, view invoices, and upgrade your plan",
};

export default async function BillingManagementPage({
  params,
}: {
  params: { lang: Lang };
}) {
  const { lang } = params;
  const isAr = lang === "ar";

  // Server-side authentication check
  const session = await auth();

  if (!session?.user?.id) {
    redirect(`/${lang}/login`);
  }

  // Check dashboard access
  const accessStatus = await checkDashboardAccess(session.user.id);

  if (!accessStatus.hasAccess) {
    const redirectUrl =
      accessStatus.redirectUrl?.replace("/en/", `/${lang}/`) ||
      `/${lang}/signup`;
    redirect(redirectUrl);
  }

  return (
    <main className="min-h-screen bg-slate-50" dir={isAr ? "rtl" : "ltr"}>
      {/* Top App Bar */}
      <header className="border-b border-slate-200 bg-white/90 backdrop-blur-sm sticky top-0 z-10 shadow-sm">
        <div className="mx-auto flex max-w-7xl items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
          <div className="flex items-center gap-4">
            <Link
              href={`/${lang}/dashboard`}
              className="flex items-center gap-2 text-slate-600 hover:text-brand-green transition-colors"
            >
              <span className="text-lg">{isAr ? "←" : "→"}</span>
              <span className="font-medium">
                {isAr ? "لوحة التحكم" : "Dashboard"}
              </span>
            </Link>
          </div>
          <div className="flex items-center gap-2">
            <Link href={`/${lang}`}>
              <img src="/mawidi-icon.svg" alt="Mawidi" className="h-10 w-auto" width={40} height={40} />
            </Link>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
        {/* Page Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold text-slate-900">
            {isAr
              ? "إدارة الفوترة والاشتراك"
              : "Billing & Subscription Management"}
          </h1>
          <p className="mt-3 text-base text-slate-600">
            {isAr
              ? "عرض خطتك الحالية، ترقية أو تخفيض الباقة، وإدارة الفواتير - كل شيء في مكان واحد."
              : "View your current plan, upgrade or downgrade, and manage invoices - all in one place."}
          </p>
        </div>

        {/* Client-side Components */}
        <BillingManagementClient lang={lang} />

        {/* Help Section */}
        <section className="mt-12 rounded-xl bg-gradient-to-br from-slate-900 to-slate-800 p-8 text-white shadow-lg">
          <div className="max-w-3xl">
            <h3 className="text-2xl font-bold mb-3">
              {isAr ? "💬 هل تحتاج مساعدة؟" : "💬 Need Help?"}
            </h3>
            <p className="text-slate-300 mb-6">
              {isAr
                ? "فريقنا جاهز لمساعدتك في أي أسئلة حول الفواتير، الاشتراكات، أو الترقيات. نحن هنا لضمان تجربتك السلسة."
                : "Our team is ready to help with any questions about billing, subscriptions, or upgrades. We are here to ensure your smooth experience."}
            </p>
            <div className="flex flex-wrap gap-4">
              <Link
                href={`/${lang}/contact`}
                className="rounded-lg bg-white px-6 py-3 text-sm font-semibold text-slate-900 hover:bg-slate-100 transition-colors"
              >
                {isAr ? "📧 اتصل بالدعم" : "📧 Contact Support"}
              </Link>
              <Link
                href={`/${lang}/pricing`}
                className="rounded-lg border border-white/30 px-6 py-3 text-sm font-medium text-white hover:bg-white/10 transition-colors"
              >
                {isAr ? "📊 مقارنة جميع الخطط" : "📊 Compare All Plans"}
              </Link>
              <a
                href="https://docs.stripe.com/billing"
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-lg border border-white/30 px-6 py-3 text-sm font-medium text-white hover:bg-white/10 transition-colors"
              >
                {isAr ? "📚 دليل الفوترة" : "📚 Billing Guide"}
              </a>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
