'use client';
import { FunctionComponent } from 'react';
import { useTranslations } from 'next-intl';
import { Box, ButtonBase, Paper, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, EmptyState, Money } from '@/components';
import type { BnplOptions, BnplProvider, ProviderCode } from '@/services/bnpl/types';

interface MethodStepProps {
  options: BnplOptions;
  selectedProvider: ProviderCode | null;
  onSelectProvider: (code: ProviderCode) => void;
  onContinue: () => void;
  onPayWithCard: () => void;
}

/** Two-letter provider glyph for the logo stand-in (real logos land with the provider assets). */
const PROVIDER_GLYPH: Record<ProviderCode, string> = {
  digipay: 'DG',
  snapppay: 'SP',
  balinyaar: 'ب',
  tara: 'TA',
  torobpay: 'TP',
};

/**
 * D1 · روش پرداخت — the branch off C6. Shows the payable amount, the full-card option (returns to the f9
 * card flow — never rebuilt here), and the installment providers loaded **from the contract/mock** (never
 * hardcoded). Primary action «ادامه با {provider}». Empty provider set → only the card option.
 */
const MethodStep: FunctionComponent<MethodStepProps> = ({
  options,
  selectedProvider,
  onSelectProvider,
  onContinue,
  onPayWithCard,
}) => {
  const t = useTranslations('bnpl');
  const hasProviders = options.providers.length > 0;

  return (
    <Stack sx={{ gap: 2 }}>
      <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
        {t('method_title')}
      </Typography>

      <Paper
        elevation={0}
        sx={{ p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider', textAlign: 'center' }}
      >
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {t('payable_amount')}
        </Typography>
        <Money amountIrr={options.orderAmountIrr} tone="emphasis" size="lg" sx={{ mt: 0.5 }} />
      </Paper>

      {/* Full-card option — selecting it continues the f9 card flow (C6), which this phase does not rebuild. */}
      <ButtonBase
        onClick={onPayWithCard}
        sx={{
          display: 'block',
          width: '100%',
          textAlign: 'start',
          borderRadius: 2,
          p: 1.75,
          border: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Stack direction="row" sx={{ alignItems: 'center', gap: 1.5 }}>
          <AppIcon icon="payment" size={24} color="var(--bal-primary)" />
          <Stack sx={{ flex: 1, gap: 0.25 }}>
            <Typography variant="body2" sx={{ fontWeight: 700 }}>
              {t('method_card')}
            </Typography>
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              {t('method_card_hint')}
            </Typography>
          </Stack>
        </Stack>
      </ButtonBase>

      {hasProviders ? (
        <>
          <Typography variant="subtitle2" sx={{ fontWeight: 700, color: 'var(--bal-secondary-dark)' }}>
            {t('installments_heading')}
          </Typography>
          {/* Ownership disclosure at the point of choice: the provider finances & owns the repayment. */}
          <Typography variant="caption" sx={{ color: 'text.secondary', lineHeight: 1.8 }}>
            {t('ownership_note')}
          </Typography>
          <Stack sx={{ gap: 1 }}>
            {options.providers.map((provider) => (
              <ProviderOption
                key={provider.providerCode}
                provider={provider}
                selected={selectedProvider === provider.providerCode}
                onSelect={() => onSelectProvider(provider.providerCode)}
              />
            ))}
          </Stack>
          <AppButton
            color="secondary"
            variant="contained"
            size="large"
            disabled={selectedProvider == null}
            onClick={onContinue}
          >
            {selectedProvider
              ? t('continue_with', { provider: t(`provider_${selectedProvider}`) })
              : t('continue')}
          </AppButton>
        </>
      ) : (
        <EmptyState title={t('no_providers_title')} body={t('no_providers_body')} />
      )}
    </Stack>
  );
};

function ProviderOption({
  provider,
  selected,
  onSelect,
}: {
  provider: BnplProvider;
  selected: boolean;
  onSelect: () => void;
}) {
  const t = useTranslations('bnpl');
  return (
    <ButtonBase
      data-provider={provider.providerCode}
      data-selected={selected}
      aria-pressed={selected}
      onClick={onSelect}
      sx={{
        display: 'block',
        width: '100%',
        textAlign: 'start',
        borderRadius: 2,
        p: 1.5,
        border: '1px solid',
        borderColor: selected ? 'var(--bal-secondary)' : 'divider',
        borderWidth: selected ? 2 : 1,
        backgroundColor: selected ? 'var(--bal-secondary-soft)' : 'transparent',
      }}
    >
      <Stack direction="row" sx={{ alignItems: 'center', gap: 1.5 }}>
        <Box
          sx={{
            width: 40,
            height: 28,
            borderRadius: 1,
            flex: 'none',
            display: 'grid',
            placeItems: 'center',
            fontWeight: 800,
            fontSize: 11,
            color: 'var(--bal-secondary-dark)',
            backgroundColor: 'var(--bal-secondary-soft)',
          }}
        >
          {PROVIDER_GLYPH[provider.providerCode]}
        </Box>
        <Stack sx={{ flex: 1, gap: 0.25 }}>
          <Typography variant="body2" sx={{ fontWeight: 700 }}>
            {t(`provider_${provider.providerCode}`)}
          </Typography>
          <Typography variant="caption" sx={{ color: 'text.secondary' }}>
            {t(`provider_tagline_${provider.providerCode}`)}
          </Typography>
        </Stack>
        {/* Decorative radio indicator — the whole card is the ButtonBase; a real <input> here would nest
            interactive content inside a <button> (invalid HTML) and warn on checked-without-onChange. */}
        <Box
          aria-hidden
          sx={{
            width: 18,
            height: 18,
            borderRadius: '50%',
            flex: 'none',
            border: '2px solid',
            borderColor: selected ? 'var(--bal-secondary)' : 'var(--bal-divider)',
            backgroundColor: selected ? 'var(--bal-secondary)' : 'transparent',
            boxShadow: selected ? 'inset 0 0 0 3px var(--bal-bg-paper)' : 'none',
          }}
        />
      </Stack>
    </ButtonBase>
  );
}

export default MethodStep;
