'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, LinearProgress, Paper, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, StatusChip } from '@/components';
import { formatNumber } from '@/utils';
import type { VerificationStatus, VerificationStep } from '@/services/verification/types';
import {
  displaySteps,
  progressCounts,
  routeForStep,
  stepDescriptionKey,
  stepLabelKey,
  stepStatusChip,
} from './verificationSteps';

interface VerificationChecklistProps {
  status: VerificationStatus;
}

/**
 * The B3 checklist body: the "X از Y" progress meter + the data-driven, ordered step rows (reusing the
 * shared `StatusChip`). Rows are rendered from `displaySteps(status)` — a new step type appears without a
 * code change. Failed/expired rows surface their reason and a re-submit path; the first actionable
 * automated/manual step gets an inline "go" link to its screen.
 */
const VerificationChecklist: FunctionComponent<VerificationChecklistProps> = ({ status }) => {
  const { passed, total } = progressCounts(status);
  const steps = displaySteps(status);
  const firstActionableId = steps.find(
    (step) => step.status !== 'passed' && step.status !== 'in_review' && routeForStep(step.code) !== null,
  )?.id;

  return (
    <Stack sx={{ gap: 2 }}>
      <ProgressMeter passed={passed} total={total} />
      <Stack sx={{ gap: 1 }}>
        {steps.map((step) => (
          <StepRow key={step.code} step={step} highlighted={step.id === firstActionableId} />
        ))}
      </Stack>
    </Stack>
  );
};

const ProgressMeter: FunctionComponent<{ passed: number; total: number }> = ({ passed, total }) => {
  const t = useTranslations('verification');
  const locale = useLocale();
  const percent = total === 0 ? 0 : (passed / total) * 100;
  const format = (value: number) => formatNumber(value, locale);
  return (
    <Paper elevation={0} sx={{ p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
      <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'baseline', mb: 1 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('progress_title')}
        </Typography>
        <Typography variant="subtitle2" sx={{ fontWeight: 700, color: 'var(--bal-primary)' }}>
          {t('progress_count', { passed: format(passed), total: format(total) })}
        </Typography>
      </Stack>
      <LinearProgress variant="determinate" value={percent} sx={{ height: 8, borderRadius: 1 }} />
    </Paper>
  );
};

const StepRow: FunctionComponent<{ step: VerificationStep; highlighted: boolean }> = ({ step, highlighted }) => {
  const t = useTranslations('verification');
  const locale = useLocale();
  const chip = stepStatusChip(step.status);
  const labelKey = stepLabelKey(step.code);
  const descKey = stepDescriptionKey(step.code);
  const label = t.has(labelKey) ? t(labelKey) : step.displayName;
  const description = t.has(descKey) ? t(descKey) : '';
  const route = routeForStep(step.code);
  const showReason = step.status === 'failed' || step.status === 'expired';
  const reason = step.failureReason
    ? t.has(`reason_${step.failureReason}`)
      ? t(`reason_${step.failureReason}`)
      : step.failureReason
    : null;
  // Only the genuinely automated checks may advertise "استعلام خودکار" — the honesty constraint.
  const showAutoNote = step.isAutomated && step.status === 'not_started';

  return (
    <Paper
      elevation={0}
      sx={{
        p: 2,
        borderRadius: 2,
        border: '1px solid',
        borderColor: highlighted ? 'var(--bal-primary)' : 'divider',
        display: 'flex',
        flexDirection: 'column',
        gap: 1,
      }}
    >
      <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center' }}>
        <AppIcon icon={step.isAutomated ? 'verified' : 'document'} size={22} color="var(--bal-text-secondary)" />
        <Stack sx={{ gap: 0.25, flexGrow: 1, minWidth: 0 }}>
          <Typography variant="body2" sx={{ fontWeight: 700 }}>
            {label}
          </Typography>
          {description ? (
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              {description}
            </Typography>
          ) : null}
        </Stack>
        <StatusChip status={chip.kind} label={t(chip.labelKey)} sx={{ flexShrink: 0 }} />
      </Stack>

      {showReason && reason ? (
        <Typography variant="body2" sx={{ color: 'var(--bal-error)' }}>
          {reason}
        </Typography>
      ) : null}

      {showAutoNote ? (
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {t('auto_query_note')}
        </Typography>
      ) : null}

      {route && (highlighted || step.status === 'failed' || step.status === 'expired') ? (
        <AppButton
          variant="text"
          color="primary"
          endIcon="edit"
          to={`/${locale}${route}`}
          sx={{ alignSelf: 'flex-start' }}
        >
          {step.status === 'failed' || step.status === 'expired' ? t('row_fix') : t('row_go')}
        </AppButton>
      ) : null}
    </Paper>
  );
};

export default VerificationChecklist;
