'use client';
import { useMemo, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { useSnackbar } from 'notistack';
import { Box, Chip, Paper, Stack, TextField, Typography } from '@mui/material';
import { AppButton, AppIcon, AppLoading, DocumentUpload, StepperHeader } from '@/components';
import type { UploadedDocInfo } from '@/components';
import { ROUTES } from '@/constants';
import {
  useSubmitCredentials,
  useUploadVerificationDocument,
  useVerificationStatus,
} from '@/services/verification';
import { SPECIALTY_PRESETS } from '@/services/verification/types';
import type { VerificationStep } from '@/services/verification/types';
import { stepDescriptionKey, stepLabelKey } from '../verificationSteps';

const MANUAL_CREDENTIAL_CODES = ['moh_competency_license', 'ino_membership', 'criminal_record'];

/**
 * B5 — professional credentials. Renders a `DocumentUpload` for **each manual credential step in the
 * status** (data-driven — a new manual step renders without a code change); each upload moves its step to
 * `in_review` (manual admin review — copy never claims an automated authority check). Collects the INO
 * number + specialty chips + optional registry fields, persisted on submit. Lands on B6 (under review).
 */
export default function CredentialsSubmitPage() {
  const t = useTranslations('verification');
  const locale = useLocale();
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();

  const { data: status, isLoading } = useVerificationStatus();
  const uploadDocument = useUploadVerificationDocument();
  const submitCredentials = useSubmitCredentials();

  const [inoNumber, setInoNumber] = useState('');
  const [inoError, setInoError] = useState(false);
  const [specialties, setSpecialties] = useState<string[]>([]);
  const [customSpecialty, setCustomSpecialty] = useState('');
  const [issuingAuthority, setIssuingAuthority] = useState('');
  const [issuedAt, setIssuedAt] = useState('');
  const [expiresAt, setExpiresAt] = useState('');
  const [uploadedSteps, setUploadedSteps] = useState<Record<number, boolean>>({});

  const manualSteps = useMemo(
    () => (status?.steps ?? []).filter((step) => MANUAL_CREDENTIAL_CODES.includes(step.code)),
    [status],
  );

  const toggleSpecialty = (value: string) =>
    setSpecialties((prev) => (prev.includes(value) ? prev.filter((item) => item !== value) : [...prev, value]));

  const addCustomSpecialty = () => {
    const value = customSpecialty.trim();
    if (value && !specialties.includes(value)) setSpecialties((prev) => [...prev, value]);
    setCustomSpecialty('');
  };

  const uploadToStep = (step: VerificationStep) => async (file: File, onProgress: (percent: number) => void) => {
    const doc = await uploadDocument.mutateAsync({ stepId: step.id, file, onProgress });
    return { name: doc.originalFileName ?? file.name, sizeBytes: doc.fileSizeBytes } satisfies UploadedDocInfo;
  };

  const handleSubmit = () => {
    const inoValid = inoNumber.trim().length > 0;
    setInoError(!inoValid);
    if (!inoValid) return;

    submitCredentials.mutate(
      {
        inoNumber: inoNumber.trim(),
        specialties,
        issuingAuthority: issuingAuthority.trim() || undefined,
        issuedAt: issuedAt || undefined,
        expiresAt: expiresAt || undefined,
      },
      {
        onSuccess: () => {
          enqueueSnackbar(t('credentials_submitted'), { variant: 'success' });
          router.push(`/${locale}${ROUTES.NURSE_VERIFICATION_REVIEW}`);
        },
        onError: () => enqueueSnackbar(t('credentials_error'), { variant: 'error' }),
      },
    );
  };

  if (isLoading) return <AppLoading />;

  if (!status || manualSteps.length === 0) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, maxWidth: 560 }}>
        <Typography variant="h5" component="h1">
          {t('credentials_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('credentials_needs_start')}
        </Typography>
        <AppButton color="primary" variant="contained" to={`/${locale}${ROUTES.NURSE_VERIFICATION}`} sx={{ alignSelf: 'flex-start' }}>
          {t('back_to_checklist')}
        </AppButton>
      </Box>
    );
  }

  const anyUploaded = Object.values(uploadedSteps).some(Boolean);

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

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

      <TextField
        label={t('ino_number_label')}
        value={inoNumber}
        onChange={(event) => {
          setInoNumber(event.target.value);
          if (inoError) setInoError(false);
        }}
        error={inoError}
        helperText={inoError ? t('ino_number_required') : t('ino_number_hint')}
        slotProps={{ htmlInput: { dir: 'ltr', style: { textAlign: 'start' } } }}
        fullWidth
      />

      {/* One uploader per manual credential step — data-driven from the status. */}
      <Stack sx={{ gap: 2 }}>
        {manualSteps.map((step) => (
          <DocumentUpload
            key={step.code}
            label={t.has(stepLabelKey(step.code)) ? t(stepLabelKey(step.code)) : step.displayName}
            hint={t.has(stepDescriptionKey(step.code)) ? t(stepDescriptionKey(step.code)) : undefined}
            onUpload={uploadToStep(step)}
            onUploaded={() => setUploadedSteps((prev) => ({ ...prev, [step.id]: true }))}
            rejected={step.status === 'failed'}
            rejectionReason={step.failureReason ?? undefined}
            existingDoc={step.status === 'in_review' ? { name: t('doc_uploaded') } : null}
          />
        ))}
      </Stack>

      {/* Supplementary education certificate — a local attachment (no dedicated step). */}
      <DocumentUpload label={t('education_label')} hint={t('education_hint')} onUpload={async (file) => ({ name: file.name })} />

      <Stack sx={{ gap: 1 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('specialties_label')}
        </Typography>
        <Typography variant="caption" sx={{ color: 'text.secondary' }}>
          {t('specialties_hint')}
        </Typography>
        <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
          {SPECIALTY_PRESETS.map((preset) => {
            const selected = specialties.includes(preset);
            return (
              <Chip
                key={preset}
                label={t.has(`specialty_${preset}`) ? t(`specialty_${preset}`) : preset}
                onClick={() => toggleSpecialty(preset)}
                sx={{
                  fontWeight: 500,
                  backgroundColor: selected ? 'var(--bal-primary)' : 'var(--bal-primary-soft)',
                  color: selected ? 'var(--bal-primary-contrast)' : 'var(--bal-primary)',
                }}
              />
            );
          })}
          {specialties
            .filter((value) => !SPECIALTY_PRESETS.includes(value))
            .map((value) => (
              <Chip
                key={value}
                label={value}
                onDelete={() => toggleSpecialty(value)}
                sx={{ fontWeight: 500, backgroundColor: 'var(--bal-primary)', color: 'var(--bal-primary-contrast)' }}
              />
            ))}
        </Stack>
        <Stack direction="row" sx={{ gap: 1, alignItems: 'flex-start' }}>
          <TextField
            size="small"
            placeholder={t('specialty_add_placeholder')}
            value={customSpecialty}
            onChange={(event) => setCustomSpecialty(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') {
                event.preventDefault();
                addCustomSpecialty();
              }
            }}
          />
          <AppButton variant="outlined" color="primary" startIcon="add" onClick={addCustomSpecialty}>
            {t('specialty_add')}
          </AppButton>
        </Stack>
      </Stack>

      {/* Optional registry details the admin cross-checks — issue/expiry are stored UTC (Shamsi shown elsewhere). */}
      <Stack sx={{ gap: 1.5 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('registry_details_label')}
        </Typography>
        <TextField
          label={t('issuing_authority_label')}
          value={issuingAuthority}
          onChange={(event) => setIssuingAuthority(event.target.value)}
          fullWidth
        />
        <Stack direction="row" sx={{ gap: 1.5, flexWrap: 'wrap' }}>
          <TextField
            label={t('issued_at_label')}
            type="date"
            value={issuedAt}
            onChange={(event) => setIssuedAt(event.target.value)}
            slotProps={{ inputLabel: { shrink: true } }}
            sx={{ flex: 1, minWidth: 160 }}
          />
          <TextField
            label={t('expires_at_label')}
            type="date"
            value={expiresAt}
            onChange={(event) => setExpiresAt(event.target.value)}
            slotProps={{ inputLabel: { shrink: true } }}
            sx={{ flex: 1, minWidth: 160 }}
          />
        </Stack>
      </Stack>

      <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('manual_review_note')}
        </Typography>
      </Paper>

      <Stack direction="row" sx={{ gap: 1 }}>
        <AppButton
          color="primary"
          variant="contained"
          startIcon="license"
          onClick={handleSubmit}
          disabled={submitCredentials.isPending || !anyUploaded}
        >
          {submitCredentials.isPending ? t('credentials_submitting') : t('credentials_submit')}
        </AppButton>
        <AppButton variant="text" color="primary" to={`/${locale}${ROUTES.NURSE_VERIFICATION}`}>
          {t('back_to_checklist')}
        </AppButton>
      </Stack>
    </Box>
  );
}
