'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { useSnackbar } from 'notistack';
import { Box, Paper, Stack, TextField, Typography } from '@mui/material';
import { AppAlert, AppButton, AppIcon, DocumentUpload, StepperHeader } from '@/components';
import { ROUTES } from '@/constants';
import { toEnglishDigits } from '@/utils';
import { useSubmitIdentity } from '@/services/verification';
import { isValidNationalId } from '@/services/verification/validation';
import { ACCEPTED_IMAGE_TYPES, NATIONAL_ID_LENGTH } from '@/services/verification/constants';
import type { SubmitIdentityResult } from '@/services/verification/hooks/useSubmitIdentity';

type SubmitError = { key: 'national_id_mismatch' | 'shared_sim' | 'shahkar_mismatch' } | null;

/**
 * B4 — identity submission. Collects the national id (10-digit + checksum), a national-ID card image,
 * and a liveness selfie, then runs the automated civil-registry KYC + the chained Shahkar match. The
 * card/selfie are **local captures** feeding the automated check (identity stores no document server-side),
 * so `DocumentUpload` runs in local mode here. The auto-query note is honest — this check is performed.
 * The shared-SIM Shahkar failure surfaces as a clear, non-accusatory message; a national-ID mismatch on
 * its own step.
 */
export default function IdentitySubmitPage() {
  const t = useTranslations('verification');
  const locale = useLocale();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const submitIdentity = useSubmitIdentity();

  const [nationalId, setNationalId] = useState('');
  const [idError, setIdError] = useState(false);
  const [cardCaptured, setCardCaptured] = useState(false);
  const [selfieCaptured, setSelfieCaptured] = useState(false);
  const [submitError, setSubmitError] = useState<SubmitError>(null);

  // Local capture: the card/selfie feed the automated KYC (no stored document) — resolve immediately.
  const captureLocally = async (file: File) => ({ name: file.name });

  const canSubmit = isValidNationalId(nationalId) && selfieCaptured && !submitIdentity.isPending;

  const handleSubmit = () => {
    const idValid = isValidNationalId(nationalId);
    setIdError(!idValid);
    setSubmitError(null);
    if (!idValid || !selfieCaptured) return;

    submitIdentity.mutate(
      { nationalId, livenessCaptured: selfieCaptured },
      {
        onSuccess: (result: SubmitIdentityResult) => {
          if (result.identity.stepStatus === 'failed') {
            setSubmitError({ key: 'national_id_mismatch' });
            return;
          }
          if (result.shahkar?.stepStatus === 'failed') {
            setSubmitError({ key: result.shahkar.failureReason === 'shared_sim' ? 'shared_sim' : 'shahkar_mismatch' });
            return;
          }
          enqueueSnackbar(t('identity_submitted'), { variant: 'success' });
          router.push(`/${locale}${ROUTES.NURSE_VERIFICATION}`);
        },
      },
    );
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: 560 }}>
      <Box>
        <Typography variant="h5" component="h1">
          {t('identity_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('identity_subtitle')}
        </Typography>
      </Box>

      <Box sx={{ overflowX: 'auto' }}>
        <StepperHeader
          steps={[t('journey_identity'), t('journey_credentials'), t('journey_review')]}
          activeStep={0}
        />
      </Box>

      <TextField
        label={t('national_id_label')}
        value={nationalId}
        onChange={(event) => {
          setNationalId(toEnglishDigits(event.target.value).replace(/\D/g, '').slice(0, NATIONAL_ID_LENGTH));
          if (idError) setIdError(false);
        }}
        error={idError}
        helperText={idError ? t('national_id_invalid') : t('national_id_hint')}
        slotProps={{ htmlInput: { dir: 'ltr', inputMode: 'numeric', style: { textAlign: 'start', letterSpacing: 2 } } }}
        fullWidth
      />

      <DocumentUpload
        label={t('card_label')}
        hint={t('card_hint')}
        accept={ACCEPTED_IMAGE_TYPES}
        capture="environment"
        onUpload={captureLocally}
        onUploaded={() => setCardCaptured(true)}
      />

      <DocumentUpload
        label={t('selfie_label')}
        hint={t('selfie_hint')}
        accept={ACCEPTED_IMAGE_TYPES}
        capture="user"
        onUpload={captureLocally}
        onUploaded={() => setSelfieCaptured(true)}
      />

      <Paper
        elevation={0}
        sx={{ p: 1.5, borderRadius: 2, bgcolor: 'var(--bal-primary-soft)', display: 'flex', gap: 1, alignItems: 'center' }}
      >
        <AppIcon icon="info" size={18} color="var(--bal-primary)" />
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {t('auto_registry_note')}
        </Typography>
      </Paper>

      {submitError ? (
        <AppAlert severity={submitError.key === 'shared_sim' ? 'warning' : 'error'} variant="outlined">
          {t(`error_${submitError.key}`)}
        </AppAlert>
      ) : null}

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

      <Stack direction="row" sx={{ gap: 1 }}>
        <AppButton
          color="primary"
          variant="contained"
          startIcon="identity"
          onClick={handleSubmit}
          disabled={!canSubmit}
        >
          {submitIdentity.isPending ? t('identity_submitting') : t('identity_submit')}
        </AppButton>
        <AppButton variant="text" color="primary" to={`/${locale}${ROUTES.NURSE_VERIFICATION}`}>
          {t('back_to_checklist')}
        </AppButton>
      </Stack>
    </Box>
  );
}
