'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Stack, Typography } from '@mui/material';
import { formatIrrToToman, formatNumber, multiplyIrr } from '@/utils';
import type { PriceUnit } from '@/services/catalog/types';

export interface PriceDisplayProps {
  /** IRR Rials as a digit-string (wire shape). Rendered as grouped Toman via the money util. */
  price: string;
  /** Drives the unit label — an i18n key off the code, **never** a label hardcoded in the component. */
  priceUnit: PriceUnit;
  /** Duration/count. Required for the estimated total — a total is never derived from `price` alone. */
  sessionCount?: number | null;
  /** When true and a `sessionCount` is present, also render the unit-aware estimated total line. */
  showEstimate?: boolean;
  align?: 'start' | 'center';
}

/**
 * Renders a variant's price as `{Toman} {unit}` (e.g. «۲۸۰٬۰۰۰ تومان ساعتی») and, when asked, the
 * unit-aware estimated total. The bare price is a **unit rate**: the estimated total is only ever
 * `price` × `sessionCount`, computed integer-safe (BigInt) — never `price` alone. Money is formatted
 * only through the f0 money util; the unit label is an i18n key off `price_unit`.
 * @component PriceDisplay
 */
const PriceDisplay: FunctionComponent<PriceDisplayProps> = ({
  price,
  priceUnit,
  sessionCount,
  showEstimate = false,
  align = 'start',
}) => {
  const t = useTranslations('catalog');
  const tc = useTranslations('common');
  const locale = useLocale();

  const amount = formatIrrToToman(price, locale);
  const unitLabel = t(`unit_${priceUnit}`);
  const hasEstimate = Boolean(showEstimate && sessionCount && sessionCount > 0);
  const total = hasEstimate ? formatIrrToToman(multiplyIrr(price, sessionCount as number), locale) : null;
  const countLabel = hasEstimate ? formatNumber(sessionCount as number, locale) : '';

  return (
    <Stack sx={{ gap: 0.25, alignItems: align === 'center' ? 'center' : 'flex-start' }}>
      <Typography component="p" sx={{ fontWeight: 700 }}>
        {amount} {tc('currency_toman')}{' '}
        <Typography component="span" variant="body2" sx={{ color: 'text.secondary', fontWeight: 500 }}>
          {unitLabel}
        </Typography>
      </Typography>
      {hasEstimate ? (
        <Typography variant="caption" sx={{ color: 'var(--bal-primary)', fontWeight: 500 }}>
          {t('estimate_label')}: {total} {tc('currency_toman')} ·{' '}
          {t('estimate_for', { count: countLabel, unit: t(`count_${priceUnit}`) })}
        </Typography>
      ) : null}
    </Stack>
  );
};

export default PriceDisplay;
