'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { useQueryClient } from '@tanstack/react-query';
import { Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppAlert, AppButton, AppIcon, EmptyState } from '@/components';
import { ROUTES } from '@/constants';
import { useStartVerification, useVerificationStatus } from '@/services/verification';
import { verificationKeys } from '@/services/verification/keys';
import { USE_VERIFICATION_MOCK } from '@/services/verification/constants';
import { __mockApproveAll, __mockRejectStep } from '@/services/verification/apis/mockApi';
import VerificationChecklist from './VerificationChecklist';
import { nextActionRoute, nextActionableIndex } from './verificationSteps';

/**
 * B3 — the verification status hub. The canonical view of the single cached `VerificationStatus` query
 * (B6 is a focused second view of the same data, never a separate fetch). Renders the loading skeleton,
 * error, the `not_started` start-CTA, the in-progress checklist + a single "continue" CTA that routes to
 * the next actionable step, and the terminal `approved` state (link to publish). The mock-only admin
 * simulation lets a human observe the verified flip while the b6 admin queue is deferred (f15).
 */
export default function NurseVerificationPage() {
  const t = useTranslations('verification');
  const locale = useLocale();
  const router = useRouter();
  const queryClient = useQueryClient();

  const { data: status, isLoading, isError, refetch } = useVerificationStatus();
  const startVerification = useStartVerification();

  const go = (route: string) => router.push(`/${locale}${route}`);

  const handleContinue = () => {
    if (!status || status.status === 'not_started') {
      startVerification.mutate(undefined, {
        onSuccess: () => go(ROUTES.NURSE_VERIFICATION_IDENTITY),
      });
      return;
    }
    const route = nextActionRoute(status);
    if (route) go(route);
  };

  const refreshStatus = () => queryClient.invalidateQueries({ queryKey: verificationKeys.status() });

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

      {isLoading ? (
        <Stack sx={{ gap: 1.5 }}>
          <Skeleton variant="rounded" height={72} sx={{ borderRadius: 2 }} />
          {[0, 1, 2, 3].map((key) => (
            <Skeleton key={key} variant="rounded" height={64} sx={{ borderRadius: 2 }} />
          ))}
        </Stack>
      ) : isError ? (
        <AppAlert
          severity="error"
          action={
            <AppButton variant="text" color="inherit" onClick={() => refetch()}>
              {t('retry')}
            </AppButton>
          }
        >
          {t('load_error')}
        </AppAlert>
      ) : !status || status.status === 'not_started' ? (
        <NotStarted onStart={handleContinue} pending={startVerification.isPending} />
      ) : status.status === 'approved' ? (
        <Approved onPublish={() => go(ROUTES.NURSE_SERVICES)} />
      ) : (
        <>
          <VerificationChecklist status={status} />
          <BlockingSummary hasBlocking={status.blockingSteps.length > 0} />
          <ContinueCta status={status} onContinue={handleContinue} />
        </>
      )}

      {/* Dev-only: stand in for the deferred (f15) admin review queue so a human can watch the flip. */}
      {USE_VERIFICATION_MOCK && status && status.status !== 'not_started' ? (
        <MockAdminControls
          onApprove={() => {
            __mockApproveAll();
            refreshStatus();
          }}
          onReject={() => {
            __mockRejectStep('moh_competency_license', 'blurry_scan');
            refreshStatus();
          }}
        />
      ) : null}
    </Box>
  );
}

function NotStarted({ onStart, pending }: { onStart: () => void; pending: boolean }) {
  const t = useTranslations('verification');
  return (
    <EmptyState
      icon="verification"
      title={t('start_title')}
      body={t('start_body')}
      action={
        <AppButton
          color="primary"
          variant="contained"
          startIcon="verification"
          onClick={onStart}
          disabled={pending}
          sx={{ mt: 1 }}
        >
          {pending ? t('starting') : t('start_cta')}
        </AppButton>
      }
    />
  );
}

function Approved({ onPublish }: { onPublish: () => void }) {
  const t = useTranslations('verification');
  return (
    <Paper
      elevation={0}
      sx={{
        p: 3,
        borderRadius: 2,
        border: '1px solid',
        borderColor: 'divider',
        borderInlineStartWidth: 4,
        borderInlineStartColor: 'var(--bal-success)',
        display: 'flex',
        flexDirection: 'column',
        gap: 1.5,
      }}
    >
      <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center' }}>
        <AppIcon icon="verified" size={28} color="var(--bal-success)" />
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('approved_title')}
        </Typography>
      </Stack>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {t('approved_body')}
      </Typography>
      <AppButton
        color="primary"
        variant="contained"
        startIcon="publish"
        onClick={onPublish}
        sx={{ alignSelf: 'flex-start' }}
      >
        {t('approved_cta')}
      </AppButton>
    </Paper>
  );
}

function BlockingSummary({ hasBlocking }: { hasBlocking: boolean }) {
  const t = useTranslations('verification');
  if (!hasBlocking) return null;
  return (
    <Typography variant="body2" sx={{ color: 'text.secondary' }}>
      {t('blocking_summary')}
    </Typography>
  );
}

function ContinueCta({
  status,
  onContinue,
}: {
  status: Parameters<typeof nextActionRoute>[0];
  onContinue: () => void;
}) {
  const t = useTranslations('verification');
  const index = nextActionableIndex(status);
  const route = nextActionRoute(status);
  if (route == null) return null;
  return (
    <AppButton color="primary" variant="contained" onClick={onContinue} sx={{ alignSelf: 'flex-start' }}>
      {index != null ? t('continue_step', { n: index }) : t('continue')}
    </AppButton>
  );
}

function MockAdminControls({ onApprove, onReject }: { onApprove: () => void; onReject: () => void }) {
  const t = useTranslations('verification');
  return (
    <EmptyState
      title={t('mock_admin_title')}
      action={
        <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap', justifyContent: 'center' }}>
          <AppButton variant="outlined" color="primary" onClick={onApprove}>
            {t('mock_admin_approve')}
          </AppButton>
          <AppButton variant="outlined" color="error" onClick={onReject}>
            {t('mock_admin_reject')}
          </AppButton>
        </Stack>
      }
    />
  );
}
