import {
  Alert,
  Badge,
  Card,
  CopyButton,
  Group,
  Loader,
  Paper,
  SimpleGrid,
  Stack,
  Text,
  ThemeIcon,
  Title,
  Tooltip,
  UnstyledButton,
} from '@mantine/core';
import {
  IconCheck,
  IconCopy,
  IconFingerprint,
  IconIdBadge2,
  IconInfoCircle,
  IconScan,
} from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { useCurrentProfile } from '@ema-platform/auth';
import { useGetMyBiometricEnrollmentsQuery } from '@ema-platform/api';

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

/**
 * View-only: the seafarer's BSID and what is enrolled against it. 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();
  // The BSID lives on the profile, stamped by staff once a capture is
  // confirmed — it is not a property of any one enrollment, so it is read
  // from the profile rather than from the rows below.
  const { profile, isLoading: profileLoading } = useCurrentProfile();
  const bsid = profile?.bsid ?? null;

  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">
        <Group gap="sm" mb={rows.length || isLoading ? 'lg' : 0} align="flex-start">
          <ThemeIcon size={40} radius="md" color="indigo" variant="light">
            <IconIdBadge2 size={20} />
          </ThemeIcon>
          <div style={{ flex: 1 }}>
            <Text fz="xs" c="dimmed" tt="uppercase" fw={600}>
              {t('biometrics.bsidLabel', 'Biometric Subject ID')}
            </Text>
            {profileLoading ? (
              <Loader size="xs" mt={6} />
            ) : bsid ? (
              <CopyButton value={bsid} timeout={1500}>
                {({ copied, copy }) => (
                  <Tooltip
                    label={copied ? t('biometrics.copied', 'Copied') : t('biometrics.copy', 'Copy')}
                    withArrow
                  >
                    <UnstyledButton onClick={copy}>
                      <Group gap={6} align="center">
                        <Text ff="monospace" fw={700} fz="lg">
                          {bsid}
                        </Text>
                        {copied ? <IconCheck size={15} /> : <IconCopy size={15} />}
                      </Group>
                    </UnstyledButton>
                  </Tooltip>
                )}
              </CopyButton>
            ) : (
              <Text fz="sm" c="dimmed" mt={2}>
                {t(
                  'biometrics.bsidPending',
                  'Not issued yet. Your BSID is generated once your enrolment is confirmed at the counter.',
                )}
              </Text>
            )}
          </div>
        </Group>

        {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>
          </Stack>
        )}
      </Paper>
    </Stack>
  );
}
