'use client';
import { FunctionComponent, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Checkbox, FormControlLabel, Paper, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppIcon, Money, PhoneNumberField } from '@/components';
import { digitsOnly } from '@/utils';
import { useCheckEligibility } from '@/services/bnpl';
import { NATIONAL_ID_LENGTH, NATIONAL_ID_PATTERN } from '@/services/bnpl/constants';
import type { BnplEligibilityResult, ProviderCode } from '@/services/bnpl/types';

interface EligibilityStepProps {
  bookingRequestId: number;
  providerCode: ProviderCode;
  /** Mobile prefilled from the session (may be empty if unknown). */
  sessionMobile: string;
  /** A prior approval to re-show on back-navigation from D4 (so the approved panel survives, not the form). */
  initialResult?: BnplEligibilityResult | null;
  onApproved: (result: BnplEligibilityResult) => void;
  onPayWithCard: () => void;
}

/**
 * D3 · اعتبارسنجی — the provider credit check. کد ملی (client-side format only — the real check is the
 * provider's), موبایل (prefilled from the session, read-only), and a consent checkbox that **gates** the
 * submit. On approval → the credit ceiling + «تایید و ادامه» → D4. On decline / ceiling-exceeded → the
 * declined panel + a card fall-back (never a dead end). The verdict is surfaced, never pre-judged.
 */
const EligibilityStep: FunctionComponent<EligibilityStepProps> = ({
  bookingRequestId,
  providerCode,
  sessionMobile,
  initialResult,
  onApproved,
  onPayWithCard,
}) => {
  const t = useTranslations('bnpl');
  const tc = useTranslations('common');

  const [nationalId, setNationalId] = useState('');
  const [consent, setConsent] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const check = useCheckEligibility();
  // A fresh check wins; otherwise re-show a prior approval carried back from D4.
  const result = check.data ?? initialResult ?? undefined;

  const nationalIdValid = NATIONAL_ID_PATTERN.test(nationalId);
  const nationalIdError = submitted && !nationalIdValid;
  const providerName = t(`provider_${providerCode}`);

  const handleSubmit = () => {
    setSubmitted(true);
    if (!nationalIdValid || !consent) return;
    check.mutate({ bookingRequestId, providerCode, nationalId, mobile: sessionMobile, consent });
  };

  // Approved — show the ceiling + advance.
  if (result?.isEligible) {
    return (
      <Stack sx={{ gap: 2 }}>
        <Paper
          elevation={0}
          sx={{
            p: 2.5,
            borderRadius: 2,
            border: '1px solid',
            borderColor: 'var(--bal-success)',
            backgroundColor: 'var(--bal-primary-soft)',
            textAlign: 'center',
          }}
        >
          <Stack sx={{ gap: 0.5, alignItems: 'center' }}>
            <AppIcon icon="verified" size={36} color="var(--bal-success)" />
            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: 'var(--bal-success)' }}>
              {t('approved_title')}
            </Typography>
            {result.creditCeilingIrr ? (
              <>
                <Typography variant="caption" sx={{ color: 'text.secondary', mt: 0.5 }}>
                  {t('credit_ceiling_label')}
                </Typography>
                <Money amountIrr={result.creditCeilingIrr} tone="emphasis" size="lg" />
              </>
            ) : null}
          </Stack>
        </Paper>
        <AppButton color="secondary" variant="contained" size="large" onClick={() => onApproved(result)}>
          {t('approve_continue')}
        </AppButton>
      </Stack>
    );
  }

  // Declined (not_eligible / ceiling_exceeded) — a clear panel + the card fall-back.
  if (result && !result.isEligible) {
    const ceiling = result.eligibilityStatus === 'ceiling_exceeded';
    return (
      <DeclinedPanel
        title={ceiling ? t('declined_ceiling_title') : t('declined_not_eligible_title')}
        body={ceiling ? t('declined_ceiling_body') : t('declined_not_eligible_body')}
        cardLabel={t('pay_with_card')}
        onPayWithCard={onPayWithCard}
      />
    );
  }

  // Error / timeout — retry or fall back to card.
  if (check.isError) {
    return (
      <DeclinedPanel
        title={t('eligibility_title')}
        body={t('eligibility_error')}
        cardLabel={t('pay_with_card')}
        onPayWithCard={onPayWithCard}
        onRetry={handleSubmit}
        retryLabel={tc('retry')}
      />
    );
  }

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

      <TextField
        label={t('national_id_label')}
        placeholder={t('national_id_placeholder')}
        value={nationalId}
        onChange={(e) => setNationalId(digitsOnly(e.target.value).slice(0, NATIONAL_ID_LENGTH))}
        error={nationalIdError}
        helperText={nationalIdError ? t('national_id_invalid') : undefined}
        slotProps={{ htmlInput: { dir: 'ltr', inputMode: 'numeric', maxLength: NATIONAL_ID_LENGTH, style: { textAlign: 'start' } } }}
        fullWidth
      />

      <PhoneNumberField
        label={t('mobile_label')}
        value={sessionMobile}
        onChange={() => undefined}
        disabled
        fullWidth
      />

      <FormControlLabel
        control={<Checkbox checked={consent} onChange={(e) => setConsent(e.target.checked)} color="secondary" />}
        label={
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('consent_label', { provider: providerName })}
          </Typography>
        }
        sx={{ alignItems: 'flex-start', m: 0 }}
      />

      <Stack sx={{ gap: 1 }}>
        <AppButton
          color="secondary"
          variant="contained"
          size="large"
          disabled={!consent || check.isPending}
          onClick={handleSubmit}
        >
          {t('check_eligibility')}
        </AppButton>
        <AppButton variant="text" color="primary" onClick={onPayWithCard}>
          {t('pay_with_card')}
        </AppButton>
      </Stack>
    </Stack>
  );
};

function DeclinedPanel({
  title,
  body,
  cardLabel,
  onPayWithCard,
  onRetry,
  retryLabel,
}: {
  title: string;
  body: string;
  cardLabel: string;
  onPayWithCard: () => void;
  onRetry?: () => void;
  retryLabel?: string;
}) {
  return (
    <Stack sx={{ gap: 2 }}>
      <Paper
        elevation={0}
        sx={{ p: 3, borderRadius: 2, border: '1px solid', borderColor: 'var(--bal-error)', textAlign: 'center' }}
      >
        <Stack sx={{ gap: 0.5, alignItems: 'center' }}>
          <AppIcon icon="rejected" size={36} color="var(--bal-error)" />
          <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
            {title}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {body}
          </Typography>
        </Stack>
      </Paper>
      <Stack sx={{ gap: 1 }}>
        {onRetry && retryLabel ? (
          <AppButton variant="outlined" color="secondary" onClick={onRetry}>
            {retryLabel}
          </AppButton>
        ) : null}
        <AppButton color="primary" variant="contained" size="large" onClick={onPayWithCard}>
          {cardLabel}
        </AppButton>
      </Stack>
    </Stack>
  );
}

export default EligibilityStep;
