'use client';

import { ActionLink } from '@/components/actions/ActionLink';
import { Icon } from '@/components/foundation/Icon';
import { DemoTrigger } from '@/components/integrations/DemoTrigger';
import { Container, Section, Stack } from '@/components/layout/LayoutPrimitives';
import { SectionHeader } from '@/components/marketing/SectionHeader';
import type { HomepageContent } from '@/content/homepage-model';
import {
  pricingCommercialConfig,
  type BillingPeriod,
  type FleetBandId,
  type PricingPlanId,
} from '@/content/pricing-config';
import { trackAnalytics } from '@/lib/analytics/client';
import type { AnalyticsContext } from '@/lib/analytics/events';
import { classNames } from '@/lib/components/classNames';
import { getDirection, type Locale } from '@/lib/localization/config';
import { useMemo, useState } from 'react';
import styles from './PricingSection.module.css';

interface PricingSectionProps {
  content: HomepageContent['pricing'];
  locale: Locale;
  homePath: string;
  demoSubmissionEnabled: boolean;
}

function analyticsContext(
  locale: Locale,
  fleetBand: FleetBandId,
  billingPeriod: BillingPeriod,
  plan?: PricingPlanId,
): AnalyticsContext {
  return {
    routeId: 'home',
    locale,
    direction: getDirection(locale),
    resolvedTheme: document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light',
    source: 'pricing',
    fleetBand,
    billingPeriod,
    ...(plan ? { plan } : {}),
  };
}

function monthlyEquivalent(monthlyPrice: number, billingPeriod: BillingPeriod): number {
  if (billingPeriod === 'monthly') return monthlyPrice;
  const discountPercent = pricingCommercialConfig.annualDiscountPercent ?? 0;
  return monthlyPrice * (1 - discountPercent / 100);
}

function formatPrice(value: number, locale: Locale): string {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: pricingCommercialConfig.currency,
    maximumFractionDigits: 0,
  }).format(value);
}

function formatDiscount(locale: Locale): string {
  const discountPercent = pricingCommercialConfig.annualDiscountPercent ?? 0;
  return new Intl.NumberFormat(locale, {
    style: 'percent',
    maximumFractionDigits: 0,
  }).format(discountPercent / 100);
}

export function PricingSection({
  content,
  locale,
  homePath,
  demoSubmissionEnabled,
}: PricingSectionProps) {
  const [fleetBand, setFleetBand] = useState<FleetBandId>('small');
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('monthly');
  const recommendedPlan = pricingCommercialConfig.recommendedPlanByFleetBand[fleetBand];

  const prices = useMemo(
    () =>
      Object.fromEntries(
        content.plans.map((plan) => {
          const configuredPrice = pricingCommercialConfig.monthlyPrices[plan.id][fleetBand];
          const publicPrice = pricingCommercialConfig.publicPricesApproved ? configuredPrice : null;
          return [
            plan.id,
            publicPrice === null ? null : monthlyEquivalent(publicPrice, billingPeriod),
          ];
        }),
      ) as Record<PricingPlanId, number | null>,
    [billingPeriod, content.plans, fleetBand],
  );

  return (
    <Section id="pricing" className={styles.section} aria-label={content.title}>
      <Container>
        <Stack gap="large">
          <SectionHeader
            className={styles.header ?? ''}
            eyebrow={content.eyebrow}
            title={content.title}
            body={content.body}
            alignment="center"
          />

          <div className={styles.controls}>
            <fieldset className={styles.controlGroup}>
              <legend>{content.fleetSelectorLabel}</legend>
              <div className={styles.optionGrid}>
                {content.fleetBands.map((band) => (
                  <div key={band.id} className={styles.option}>
                    <input
                      id={`pricing-fleet-${band.id}`}
                      type="radio"
                      name="pricing-fleet-band"
                      value={band.id}
                      checked={fleetBand === band.id}
                      onChange={() => {
                        setFleetBand(band.id);
                        trackAnalytics(
                          'pricing_fleet_band_selected',
                          analyticsContext(locale, band.id, billingPeriod),
                        );
                      }}
                    />
                    <label htmlFor={`pricing-fleet-${band.id}`}>{band.label}</label>
                  </div>
                ))}
              </div>
            </fieldset>

            <fieldset className={styles.controlGroup}>
              <legend>{content.billingLegend}</legend>
              <div className={classNames(styles.optionGrid, styles.billingOptions)}>
                {(['monthly', 'annual'] as const).map((period) => (
                  <div key={period} className={styles.option}>
                    <input
                      id={`pricing-billing-${period}`}
                      type="radio"
                      name="pricing-billing-period"
                      value={period}
                      checked={billingPeriod === period}
                      onChange={() => {
                        setBillingPeriod(period);
                        trackAnalytics(
                          'pricing_billing_period_changed',
                          analyticsContext(locale, fleetBand, period),
                        );
                      }}
                    />
                    <label htmlFor={`pricing-billing-${period}`}>
                      {period === 'monthly' ? content.billingMonthly : content.billingAnnual}
                      {period === 'annual' &&
                      pricingCommercialConfig.publicPricesApproved &&
                      pricingCommercialConfig.annualDiscountPercent ? (
                        <span className={styles.savings}>
                          {content.billingSavings} {formatDiscount(locale)}
                        </span>
                      ) : null}
                    </label>
                  </div>
                ))}
              </div>
            </fieldset>
          </div>

          <div className={styles.planGrid} aria-live="polite">
            {content.plans.map((plan) => {
              const recommended = plan.id === recommendedPlan;
              const price = prices[plan.id];
              const custom = plan.id === 'enterprise';

              return (
                <article
                  key={plan.id}
                  className={classNames(styles.planCard, recommended && styles.recommendedCard)}
                  data-plan={plan.id}
                  data-recommended={recommended || undefined}
                >
                  {recommended ? (
                    <span className={styles.recommendedBadge}>{content.recommended}</span>
                  ) : null}

                  <header className={styles.planHeader}>
                    <h3 className={styles.planName}>{plan.name}</h3>
                    <p className={styles.audience}>{plan.audience}</p>
                  </header>

                  <div className={styles.priceBlock}>
                    {custom ? (
                      <span className={styles.customPrice}>{content.customPrice}</span>
                    ) : price === null ? (
                      <span className={styles.pendingPrice}>{content.pricePending}</span>
                    ) : (
                      <>
                        <p className={styles.priceLabel}>{content.startingAt}</p>
                        <div className={styles.priceLine}>
                          <bdi className={styles.price} dir="ltr">
                            {formatPrice(price, locale)}
                          </bdi>
                          <span>{content.perMonth}</span>
                        </div>
                        {billingPeriod === 'annual' ? (
                          <p className={styles.priceMeta}>{content.annualEquivalent}</p>
                        ) : null}
                      </>
                    )}
                  </div>

                  <ul className={styles.featureList}>
                    {plan.features.map((feature) => (
                      <li key={feature}>
                        <Icon name="check" size="sm" />
                        <span>{feature}</span>
                      </li>
                    ))}
                  </ul>

                  <DemoTrigger
                    label={plan.cta}
                    source="pricing"
                    size="large"
                    fullWidth
                    className={styles.planAction}
                    disabledReason={
                      demoSubmissionEnabled ? undefined : content.actionDisabledReason
                    }
                    onActivate={() =>
                      trackAnalytics(
                        'pricing_plan_cta_clicked',
                        analyticsContext(locale, fleetBand, billingPeriod, plan.id),
                      )
                    }
                  />
                </article>
              );
            })}
          </div>

          <div className={styles.detailsGrid}>
            <section className={styles.detailCard} aria-labelledby="pricing-basis-title">
              <h3 id="pricing-basis-title">{content.basisTitle}</h3>
              <ul className={styles.basisList}>
                {content.basis.map((item) => (
                  <li key={item}>
                    <Icon name="check" size="sm" />
                    <span>{item}</span>
                  </li>
                ))}
              </ul>
            </section>

            <section className={styles.detailCard} aria-labelledby="pricing-modules-title">
              <h3 id="pricing-modules-title">{content.modulesTitle}</h3>
              <ul className={styles.moduleList}>
                {content.modules.map((module) => (
                  <li key={module}>{module}</li>
                ))}
              </ul>
            </section>
          </div>

          <div className={styles.assuranceRow}>
            <ul className={styles.assuranceList}>
              {content.assurances.map((assurance) => (
                <li key={assurance}>
                  <Icon name="check" size="sm" />
                  <span>{assurance}</span>
                </li>
              ))}
            </ul>
            <div className={styles.compareBlock}>
              <p>{content.notSure}</p>
              <ActionLink href={`${homePath}#modules`} variant="standalone" icon="arrow-forward">
                {content.compare}
              </ActionLink>
            </div>
          </div>

          {!pricingCommercialConfig.publicPricesApproved ? (
            <p className={styles.configurationNote}>{content.note}</p>
          ) : null}
        </Stack>
      </Container>
    </Section>
  );
}
