'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, StatusChip, SurfaceCard } from '@/components';
import type { VerificationStatus, VerificationStep } from '@/services/verification/types';
import {
  groupLabelKey,
  groupRoute,
  groupStatus,
  groupedDisplaySteps,
  stepDescriptionKey,
  stepLabelKey,
  stepStatusChip,
  type StepGroupKey,
} from './verificationSteps';

interface VerificationChecklistProps {
  status: VerificationStatus;
}

const GROUP_ICON: Record<StepGroupKey, string> = { identity: 'identity', credentials: 'license', bank: 'bank' };

/**
 * The B3 journey body (ui-phase-8 §3.2) — ONE vertical spine of grouped step cards (هویت / مدارک
 * حرفه‌ای / بانک), replacing the old flat "X از Y" + 7-row list. Each card folds the data-driven
 * steps `verificationSteps.ts` already catalogs (regrouped presentation only — the catalog/synthetic
 * mobile-step architecture is unchanged) and links to the one screen that owns that group's submission.
 */
const VerificationChecklist: FunctionComponent<VerificationChecklistProps> = ({ status }) => {
  const groups = groupedDisplaySteps(status);
  return (
    <Stack sx={{ gap: 2 }}>
      {groups.map(({ group, steps }) => (
        <GroupCard key={group} group={group} steps={steps} />
      ))}
    </Stack>
  );
};

const GroupCard: FunctionComponent<{ group: StepGroupKey; steps: VerificationStep[] }> = ({ group, steps }) => {
  const t = useTranslations('verification');
  const locale = useLocale();
  const aggregate = groupStatus(steps);
  const chip = stepStatusChip(aggregate);
  const route = groupRoute(group);
  const actionable = aggregate !== 'passed' && aggregate !== 'in_review';

  return (
    <SurfaceCard
      padding="md"
      data-journey-group={group}
      data-journey-group-status={aggregate}
      sx={{
        borderInlineStart: '4px solid',
        borderInlineStartColor:
          aggregate === 'failed' ? 'var(--bal-error)' : aggregate === 'passed' ? 'var(--bal-success)' : 'divider',
      }}
    >
      <Stack sx={{ gap: 1.5 }}>
        <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center', justifyContent: 'space-between' }}>
          <Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
            <AppIcon icon={GROUP_ICON[group]} size={22} color="var(--bal-text-secondary)" />
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {t(groupLabelKey(group))}
            </Typography>
          </Stack>
          <StatusChip status={chip.kind} label={t(chip.labelKey)} sx={{ flexShrink: 0 }} />
        </Stack>

        <Stack sx={{ gap: 1 }}>
          {steps.map((step) => (
            <StepLine key={step.code} step={step} />
          ))}
        </Stack>

        {actionable ? (
          <AppButton
            variant="text"
            color="primary"
            endIcon="edit"
            to={`/${locale}${route}`}
            sx={{ alignSelf: 'flex-start' }}
          >
            {aggregate === 'failed' ? t('row_fix') : t('row_go')}
          </AppButton>
        ) : null}
      </Stack>
    </SurfaceCard>
  );
};

const StepLine: FunctionComponent<{ step: VerificationStep }> = ({ step }) => {
  const t = useTranslations('verification');
  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 = step.status !== 'passed' && t.has(descKey) ? t(descKey) : null;
  const reason = step.failureReason
    ? t.has(`reason_${step.failureReason}`)
      ? t(`reason_${step.failureReason}`)
      : step.failureReason
    : null;
  const showReason = (step.status === 'failed' || step.status === 'expired') && reason;
  // Only the genuinely automated checks may advertise "استعلام خودکار" — the honesty constraint.
  const showAutoNote = step.isAutomated && step.status === 'not_started';

  return (
    <Stack sx={{ gap: 0.25 }} data-step-code={step.code}>
      <Stack direction="row" sx={{ gap: 1, alignItems: 'center', justifyContent: 'space-between' }}>
        <Typography variant="body2">{label}</Typography>
        <StatusChip status={chip.kind} label={t(chip.labelKey)} size="small" sx={{ flexShrink: 0 }} />
      </Stack>
      {description ? (
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {description}
        </Typography>
      ) : null}
      {showReason ? (
        <Typography variant="caption" sx={{ color: 'var(--bal-error)' }}>
          {reason}
        </Typography>
      ) : null}
      {showAutoNote ? (
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {t('auto_query_note')}
        </Typography>
      ) : null}
    </Stack>
  );
};

export default VerificationChecklist;
