'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { useForm, FormProvider, useWatch } from 'react-hook-form';
import { useSnackbar } from 'notistack';
import { Box, Paper, Stack, Typography } from '@mui/material';
import { AppAlert, AppButton, AppIcon, DocumentUpload, FormSection, RhfTextField } from '@/components';
import { CONTENT_MAX_WIDTH } from '@/components/config';
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';
import VerificationJourneyHeader from '../VerificationJourneyHeader';

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

interface IdentityFormValues {
  nationalId: string;
  cardCaptured: boolean;
  selfieCaptured: boolean;
}

/**
 * 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.
 *
 * Structured as three named steps rather than one column of controls: the screen asks for a number, a
 * card photo and a selfie, and the old layout gave no clue that the selfie was the only *required* one
 * of the three — the submit button simply stayed dead with the reason buried in a caption near the
 * bottom. Each capture's completion is a real form field, so the requirement is declared where it
 * applies instead of re-derived in the submit handler.
 */
export default function IdentitySubmitPage() {
  const t = useTranslations('verification');
  const locale = useLocale();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();
  const submitIdentity = useSubmitIdentity();

  const [submitError, setSubmitError] = useState<SubmitError>(null);

  const form = useForm<IdentityFormValues>({
    mode: 'onTouched',
    defaultValues: { nationalId: '', cardCaptured: false, selfieCaptured: false },
  });
  const { control, handleSubmit, setValue } = form;
  const cardCaptured = useWatch({ control, name: 'cardCaptured' });
  const selfieCaptured = useWatch({ control, name: 'selfieCaptured' });

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

  const submit = (values: IdentityFormValues) => {
    setSubmitError(null);
    submitIdentity.mutate(
      { nationalId: values.nationalId, livenessCaptured: values.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 (
    <FormProvider {...form}>
      <Box
        component="form"
        noValidate
        onSubmit={handleSubmit(submit)}
        sx={{ display: 'flex', flexDirection: 'column', gap: 2.5, maxWidth: CONTENT_MAX_WIDTH, mx: 'auto', width: '100%' }}
      >
        <VerificationJourneyHeader group="identity" />

        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('identity_subtitle')}
        </Typography>

        <FormSection title={t('identity_step_number_title')} description={t('national_id_hint')} icon="identity">
          <RhfTextField<IdentityFormValues>
            name="nationalId"
            label={t('national_id_label')}
            transform={(raw) => toEnglishDigits(raw).replace(/\D/g, '').slice(0, NATIONAL_ID_LENGTH)}
            rules={{ validate: (value) => isValidNationalId(String(value ?? '')) || t('national_id_invalid') }}
            slotProps={{ htmlInput: { dir: 'ltr', inputMode: 'numeric', style: { textAlign: 'start', letterSpacing: 2 } } }}
            fullWidth
          />
        </FormSection>

        <FormSection
          title={t('card_label')}
          description={t('card_hint')}
          icon="camera"
          optional
          optionalLabel={t('card_recommended_short')}
          status={cardCaptured ? <CapturedMark label={t('capture_done')} /> : undefined}
        >
          <CaptureGuideFrame variant="card" />
          <DocumentUpload
            label={t('card_label')}
            hint={t('capture_hint_card')}
            accept={ACCEPTED_IMAGE_TYPES}
            capture="environment"
            onUpload={captureLocally}
            onUploaded={() => setValue('cardCaptured', true, { shouldValidate: true })}
          />
        </FormSection>

        <FormSection
          title={t('selfie_label')}
          description={t('selfie_hint')}
          icon="account"
          status={selfieCaptured ? <CapturedMark label={t('capture_done')} /> : <RequiredMark label={t('required_badge')} />}
        >
          <CaptureGuideFrame variant="selfie" />
          <DocumentUpload
            label={t('selfie_label')}
            hint={t('capture_hint_selfie')}
            accept={ACCEPTED_IMAGE_TYPES}
            capture="user"
            onUpload={captureLocally}
            onUploaded={() => setValue('selfieCaptured', true, { shouldValidate: true })}
          />
        </FormSection>

        <Paper
          elevation={0}
          sx={{ p: 1.5, borderRadius: 'var(--bal-radius-md)', 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}

        {/* The one thing that still gates submit is the selfie, so it says so here rather than leaving
            a dead button to be explained by a caption three sections up. */}
        {!selfieCaptured ? (
          <Typography variant="caption" sx={{ color: 'text.secondary' }}>
            {t('identity_needs_selfie')}
          </Typography>
        ) : null}

        <Stack direction="row" sx={{ gap: 1 }}>
          <AppButton
            type="submit"
            color="primary"
            variant="contained"
            startIcon="identity"
            disabled={!selfieCaptured || submitIdentity.isPending}
          >
            {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>
    </FormProvider>
  );
}

/** A section's "done" marker — the completion cue a wall of uploaders otherwise never gives. */
function CapturedMark({ label }: { label: string }) {
  return (
    <Stack direction="row" sx={{ gap: 0.5, alignItems: 'center', flexShrink: 0 }}>
      <AppIcon icon="verified" size={16} color="var(--bal-success)" />
      <Typography variant="caption" sx={{ color: 'var(--bal-success)' }}>
        {label}
      </Typography>
    </Stack>
  );
}

function RequiredMark({ label }: { label: string }) {
  return (
    <Typography variant="caption" sx={{ color: 'var(--bal-warning)', flexShrink: 0 }}>
      {label}
    </Typography>
  );
}

const CORNER_SIZE = 18;
/** The four viewfinder-style corner brackets on the card guide (no-op for the round selfie guide). */
const CORNER_POSITIONS = [
  { insetBlockStart: -1, insetInlineStart: -1, borderBlockStart: '3px solid', borderInlineStart: '3px solid' },
  { insetBlockStart: -1, insetInlineEnd: -1, borderBlockStart: '3px solid', borderInlineEnd: '3px solid' },
  { insetBlockEnd: -1, insetInlineStart: -1, borderBlockEnd: '3px solid', borderInlineStart: '3px solid' },
  { insetBlockEnd: -1, insetInlineEnd: -1, borderBlockEnd: '3px solid', borderInlineEnd: '3px solid' },
] as const;

/**
 * A cheap, dependency-free capture guide — a dashed frame (viewfinder corners for the card, an oval
 * for the selfie), shown above the corresponding `DocumentUpload`. There is no live camera preview to
 * overlay (the native camera app owns capture via the file input's `capture` attribute), so this
 * illustrates *how to frame the shot* rather than tracking the actual photo. The hint line that used
 * to sit under it now rides on the uploader itself, where the tap target is.
 */
function CaptureGuideFrame({ variant }: { variant: 'card' | 'selfie' }) {
  const isCard = variant === 'card';
  return (
    <Box
      aria-hidden
      sx={{
        alignSelf: 'center',
        position: 'relative',
        width: isCard ? 180 : 112,
        height: isCard ? 112 : 140,
        borderRadius: isCard ? 2 : '50%',
        border: '2px dashed var(--bal-divider)',
      }}
    >
      {isCard
        ? CORNER_POSITIONS.map((pos, index) => (
            <Box
              key={index}
              sx={{ position: 'absolute', width: CORNER_SIZE, height: CORNER_SIZE, borderColor: 'var(--bal-primary)', ...pos }}
            />
          ))
        : null}
    </Box>
  );
}
