import Link from "next/link";
import { UI, SITE, type Lang } from "@/lib/config";
import { stripe } from "@/lib/stripe";
import PricingClient from "./PricingClient";
import JsonLd from "@/components/JsonLd";
import type { Metadata } from "next";
import type { SerializableStripeProduct, TierId } from "@/lib/types/pricing";
import type { StripeProduct } from "@/lib/types/stripe";
import { pricingTranslations as pricingEn } from "@/lib/config/translations/modules/pages/pricing.en";
import { pricingTranslations as pricingAr } from "@/lib/config/translations/modules/pages/pricing.ar";

// ISR - revalidate every hour
export const revalidate = 3600;

export async function generateMetadata({
  params,
}: {
  params: { lang: Lang };
}): Promise<Metadata> {
  const t = params.lang === "ar" ? pricingAr : pricingEn;
  return {
    title: t.pricingTitle || "Pricing - Mawidi",
    description:
      t.pricingDescription || "Choose the perfect plan for your business needs",
  };
}

async function fetchStripeProducts(): Promise<Map<string, StripeProduct>> {
  try {
    // Fetch all products with their prices (increase limit to get all products)
    const [products, prices] = await Promise.all([
      stripe.products.list({
        active: true,
        limit: 100,
        expand: ["data.default_price"],
      }),
      stripe.prices.list({
        active: true,
        limit: 100,
        expand: ["data.product"],
      }),
    ]);

    // Organize products by tier, excluding setup_fee products
    const tierProducts = new Map<string, StripeProduct>();

    products.data.forEach((product) => {
      const tierId = product.metadata?.tier_id;
      const productType = product.metadata?.type;

      // Only include products with tier_id AND without type="setup_fee"
      if (tierId && productType !== "setup_fee") {
        tierProducts.set(tierId, {
          ...product,
          prices: prices.data.filter(
            (price) =>
              typeof price.product === "object" &&
              price.product.id === product.id,
          ),
        } as unknown as StripeProduct);
      }
    });

    return tierProducts;
  } catch (error) {
    console.error("Error fetching Stripe products:", error);
    return new Map();
  }
}

export default async function PricingPage({
  params,
}: {
  params: { lang: Lang };
}) {
  // Defensive: fallback to default lang if params.lang not in UI
  const safeLang = params.lang in UI ? params.lang : SITE.defaultLang;
  const dict = UI[safeLang];
  const isAr = safeLang === "ar";

  // Fetch Stripe products server-side
  const stripeProducts = await fetchStripeProducts();

  // Convert to serializable format and enforce correct tier order
  const productsData: SerializableStripeProduct[] = Array.from(
    stripeProducts.entries(),
  )
    .map(([tierId, product]) => ({
      tierId: tierId as TierId,
      stripeProductId: product.id,
      name: product.name,
      description: product.description,
      features: product.metadata?.features
        ? JSON.parse(product.metadata.features)
        : [],
      prices: product.prices.map((price) => {
        // Handle both Stripe API naming (unit_amount) and our StripePrice type (unitAmount)
        const stripePrice = price as unknown as {
          id: string;
          currency: string;
          unit_amount: number | null;
          unitAmount?: number | null;
          recurring?: { interval: string; interval_count: number } | null;
        };
        return {
          id: stripePrice.id,
          currency: stripePrice.currency,
          unitAmount: stripePrice.unit_amount ?? stripePrice.unitAmount ?? null,
          interval:
            (stripePrice.recurring?.interval as "month" | "year") || null,
          intervalCount: stripePrice.recurring?.interval_count || null,
        };
      }),
    }))
    // Explicit tier ordering: tier1 → tier2 → tier3 → tier4 → tier5
    .sort((a, b) => {
      const tierOrder: TierId[] = ["tier1", "tier2", "tier3", "tier4", "tier5"];
      return tierOrder.indexOf(a.tierId) - tierOrder.indexOf(b.tierId);
    });

  // FAQ Schema data for pricing page
  const pricingFaqs = [
    {
      "@type": "Question" as const,
      name: isAr ? "هل يمكنني الإلغاء في أي وقت؟" : "Can I cancel anytime?",
      acceptedAnswer: {
        "@type": "Answer" as const,
        text: isAr
          ? "نعم. بدون رسوم مخفية. بدون غرامات. ألغِ متى شئت."
          : "Yes. No hidden fees. No penalties. Cancel whenever you want.",
      },
    },
    {
      "@type": "Question" as const,
      name: isAr
        ? "هل التجربة المجانية 14 يوم مجانية فعلاً؟"
        : "Is the 14-day trial really free?",
      acceptedAnswer: {
        "@type": "Answer" as const,
        text: isAr
          ? "بالتأكيد. وصول كامل لجميع المزايا. بدون بطاقة ائتمان."
          : "Absolutely. Full access to all features. No credit card required.",
      },
    },
    {
      "@type": "Question" as const,
      name: isAr
        ? "هل يمكنني الترقية أو التخفيض لاحقاً؟"
        : "Can I upgrade or downgrade later?",
      acceptedAnswer: {
        "@type": "Answer" as const,
        text: isAr
          ? "نعم. التغييرات تسري فوراً. فوترة تناسبية."
          : "Yes. Changes take effect immediately. Prorated billing.",
      },
    },
    {
      "@type": "Question" as const,
      name: isAr
        ? "ما طرق الدفع المقبولة؟"
        : "What payment methods do you accept?",
      acceptedAnswer: {
        "@type": "Answer" as const,
        text: isAr
          ? "جميع البطاقات الرئيسية، التحويلات البنكية، والمحافظ الرقمية."
          : "All major cards, bank transfers, and digital wallets.",
      },
    },
  ];

  return (
    <>
      <PricingClient
        lang={safeLang}
        dict={dict}
        stripeProducts={productsData}
      />
      {/* ROI Calculator CTA */}
      <div className="bg-gradient-to-br from-brand-green/5 to-emerald-500/5 py-12 text-center dark:from-brand-green/10 dark:to-emerald-500/10">
        <div className="mx-auto max-w-3xl px-6">
          <h2 className="text-2xl font-bold text-slate-900 dark:text-white md:text-3xl">
            {isAr
              ? "هل تريد معرفة كم ستوفر بالضبط؟"
              : "Want to Know Exactly How Much You'll Save?"}
          </h2>
          <p className="mt-3 text-slate-600 dark:text-slate-400">
            {isAr
              ? "استخدم حاسبة العائد المجانية لحساب تكلفة عدم الحضور والتوفير المتوقع"
              : "Use our free ROI calculator to estimate your no-show costs and projected savings"}
          </p>
          <Link
            href={`/${safeLang}/tools/roi-calculator`}
            className="mt-6 inline-flex items-center justify-center rounded-lg bg-brand-green px-8 py-4 text-lg font-semibold text-white transition-colors hover:bg-brand-greenHover"
          >
            {isAr ? "احسب توفيرك الآن" : "Calculate Your Savings"}
          </Link>
        </div>
      </div>
      {/* FAQ Schema for SEO */}
      <JsonLd type="FAQPage" data={{ mainEntity: pricingFaqs }} />
    </>
  );
}
