import { useState } from 'react';
import {
  Alert,
  Badge,
  Button,
  Card,
  Group,
  Loader,
  Paper,
  SimpleGrid,
  Stack,
  Text,
  ThemeIcon,
  Title,
} from '@mantine/core';
import { notifications } from '@mantine/notifications';
import {
  IconDownload,
  IconFingerprint,
  IconInfoCircle,
  IconScan,
} from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { authStorage } from '@ema-platform/auth';
import { useGetMyBiometricEnrollmentsQuery } from '@ema-platform/api';
import { PdfPreviewModal } from '@ema-platform/ui';

const API_BASE =
  (import.meta as { env?: Record<string, string> }).env?.['VITE_BASE_API_URL'] ??
  'http://localhost:3000/api';

async function fetchCertificate(): Promise<Blob> {
  const token = authStorage.getToken();
  if (!token) throw new Error('No auth token found');
  const res = await fetch(`${API_BASE}/biometric-enrollments/mine/certificate`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error(`Failed to fetch certificate (${res.status})`);
  return res.blob();
}

function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

const MODALITY_LABEL: Record<string, string> = {
  FINGERPRINT: 'Fingerprint',
  FACE: 'Face',
};

/**
 * View-only: what's enrolled, plus a printable slip. Capture stays
 * counter-side with a scanner — there is no self-enrollment flow here.
 */
export function BiometricsPage() {
  const { t } = useTranslation();
  const { data: enrollments, isLoading } = useGetMyBiometricEnrollmentsQuery();
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const openPreview = async () => {
    setBusy(true);
    try {
      setPreviewUrl(URL.createObjectURL(await fetchCertificate()));
    } catch (err) {
      notifications.show({
        color: 'red',
        title: 'Error',
        message: err instanceof Error ? err.message : 'Could not load certificate',
      });
    } finally {
      setBusy(false);
    }
  };

  const handleDownload = async () => {
    setBusy(true);
    try {
      downloadBlob(await fetchCertificate(), 'biometric-enrollment-certificate.pdf');
    } catch (err) {
      notifications.show({
        color: 'red',
        title: 'Error',
        message: err instanceof Error ? err.message : 'Could not download certificate',
      });
    } finally {
      setBusy(false);
    }
  };

  const rows = enrollments ?? [];

  return (
    <Stack>
      <Group gap="xs">
        <IconFingerprint size={22} />
        <Title order={2}>{t('biometrics.title', 'Biometrics')}</Title>
      </Group>
      <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
        {t(
          'biometrics.pageIntro',
          'Fingerprint and face enrollment happen in person at an EMA counter. This page shows what is on file for you.',
        )}
      </Alert>

      <Paper withBorder radius="lg" p="xl">
        {isLoading ? (
          <Group justify="center" py="lg">
            <Loader size="sm" />
          </Group>
        ) : rows.length === 0 ? (
          <Alert variant="light" color="gray" icon={<IconInfoCircle size={15} />}>
            {t('biometrics.empty', 'No biometric enrollment on file yet.')}
          </Alert>
        ) : (
          <Stack>
            <SimpleGrid cols={{ base: 1, sm: 2 }} spacing="md">
              {rows.map((e) => (
                <Card key={e.id} withBorder radius="md" p="md">
                  <Group justify="space-between">
                    <Group gap="sm">
                      <ThemeIcon size={36} radius="md" color="blue" variant="light">
                        <IconScan size={18} />
                      </ThemeIcon>
                      <div>
                        <Text fw={700} fz="sm">
                          {MODALITY_LABEL[e.modality] ?? e.modality}
                        </Text>
                        <Text fz="xs" c="dimmed">
                          Enrolled {new Date(e.enrolledAt).toLocaleDateString('en-GB', {
                            day: '2-digit',
                            month: 'short',
                            year: 'numeric',
                          })}
                        </Text>
                      </div>
                    </Group>
                    <Badge color="teal" variant="light">
                      {e.status}
                    </Badge>
                  </Group>
                </Card>
              ))}
            </SimpleGrid>
            <Group>
              <Button
                variant="light"
                leftSection={busy ? <Loader size={12} /> : <IconInfoCircle size={12} />}
                onClick={openPreview}
                disabled={busy}
              >
                {t('biometrics.view', 'View certificate')}
              </Button>
              <Button
                variant="default"
                leftSection={<IconDownload size={12} />}
                onClick={handleDownload}
                disabled={busy}
              >
                {t('biometrics.download', 'Download')}
              </Button>
            </Group>
          </Stack>
        )}
      </Paper>

      <PdfPreviewModal
        opened={!!previewUrl}
        onClose={() => setPreviewUrl(null)}
        url={previewUrl ?? ''}
        title={t('biometrics.title', 'Biometrics')}
      />
    </Stack>
  );
}
