'use client';
import { FunctionComponent } from 'react';
import { useTranslations } from 'next-intl';
import { Paper, Stack, Typography } from '@mui/material';
import { AppButton, BnplPlanCard, EmptyState, Money } from '@/components';
import { parseIrr } from '@/utils';
import type { BnplPlanOption, ProviderCode } from '@/services/bnpl/types';

interface PlanStepProps {
  providerCode: ProviderCode;
  /** D1's payable gross — the interest-free baseline `BnplPlanCard`'s fee delta compares against. */
  orderAmountIrr: string;
  plans: BnplPlanOption[];
  selectedPlanId: string | null;
  onSelectPlan: (planId: string) => void;
  onContinue: () => void;
  onBack: () => void;
}

/** The same term/installment-count label `BnplPlanCard` shows — reused here to name the header's total. */
function termLabelFor(plan: BnplPlanOption, t: ReturnType<typeof useTranslations>): string {
  return plan.termMonths != null
    ? t('plan_term_months', { months: plan.termMonths })
    : t('plan_installments', { count: plan.installmentCount });
}

/**
 * D2 · انتخاب طرح اقساط — the plan selector for the chosen provider. Shows the total amount and the plan
 * options the contract returned (monthly amount + down-payment %) as a single-select terracotta card group.
 * Every amount comes through the money util from served IRR strings — the client computes nothing about
 * money. Empty plans → back to D1.
 */
const PlanStep: FunctionComponent<PlanStepProps> = ({
  providerCode,
  orderAmountIrr,
  plans,
  selectedPlanId,
  onSelectPlan,
  onContinue,
  onBack,
}) => {
  const t = useTranslations('bnpl');
  const tc = useTranslations('common');

  if (plans.length === 0) {
    return (
      <Stack sx={{ gap: 2 }}>
        <EmptyState title={t('no_plans_title')} body={t('no_plans_body')} />
        <AppButton variant="outlined" color="primary" onClick={onBack}>
          {t('back_to_providers')}
        </AppButton>
      </Stack>
    );
  }

  // The plan total is a per-plan served figure (interest-free plans = order gross; fee plans add the fee).
  // No default fallback to plans[0] — the header only shows a total once a plan is actually selected, so
  // it never silently morphs before the user has chosen anything.
  const shownPlan = plans.find((p) => p.planId === selectedPlanId) ?? null;
  const feeIrr = shownPlan ? (parseIrr(shownPlan.totalIrr) - parseIrr(orderAmountIrr)).toString() : null;
  const hasFee = shownPlan != null && shownPlan.feePercent > 0 && feeIrr != null && parseIrr(feeIrr) > BigInt(0);

  return (
    <Stack sx={{ gap: 2 }}>
      <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
        {t('plan_title', { provider: t(`provider_${providerCode}`) })}
      </Typography>

      {shownPlan ? (
        <Paper
          elevation={0}
          sx={{ p: 1.5, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}
        >
          <Stack sx={{ gap: 0.5 }}>
            <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center' }}>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {t('total_amount_named', { plan: termLabelFor(shownPlan, t) })}
              </Typography>
              <Money amountIrr={shownPlan.totalIrr} tone="emphasis" size="sm" />
            </Stack>
            {hasFee && feeIrr != null ? (
              <Stack direction="row" sx={{ gap: 0.25, alignItems: 'baseline', justifyContent: 'flex-end' }}>
                <Typography variant="caption" sx={{ color: 'var(--bal-money-emphasis)' }}>
                  +
                </Typography>
                <Money amountIrr={feeIrr} size="sm" sx={{ color: 'var(--bal-money-emphasis)' }} />
                <Typography variant="caption" sx={{ color: 'var(--bal-money-emphasis)' }}>
                  {t('plan_fee_amount_suffix')}
                </Typography>
              </Stack>
            ) : null}
          </Stack>
        </Paper>
      ) : null}

      <Stack sx={{ gap: 1 }}>
        {plans.map((plan) => (
          <BnplPlanCard
            key={plan.planId}
            plan={plan}
            orderAmountIrr={orderAmountIrr}
            selected={selectedPlanId === plan.planId}
            onSelect={onSelectPlan}
          />
        ))}
      </Stack>

      <Stack sx={{ gap: 1 }}>
        <AppButton
          color="secondary"
          variant="contained"
          size="large"
          disabled={selectedPlanId == null}
          onClick={onContinue}
        >
          {t('continue')}
        </AppButton>
        <AppButton variant="text" color="primary" onClick={onBack}>
          {tc('back')}
        </AppButton>
      </Stack>
    </Stack>
  );
};

export default PlanStep;
