import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  Badge,
  Button,
  Card,
  Center,
  Container,
  Group,
  Loader,
  Stack,
  Table,
  Text,
  TextInput,
  Title,
} from '@mantine/core';
import {
  IconCircleCheck,
  IconCircleX,
  IconSearch,
  IconShieldCheck,
} from '@tabler/icons-react';
import { useVerifyCertificateQuery } from '@ema-platform/api';

/**
 * Public certificate verification (US-PORTAL-008) — the page every printed
 * QR code points at. Deliberately public and chrome-free: a bank clerk or
 * port official scanning a certificate has no portal account.
 */
export function VerifyCertificatePage() {
  const { code } = useParams();
  const navigate = useNavigate();
  const [manualCode, setManualCode] = useState('');
  const { data, isLoading, isError } = useVerifyCertificateQuery(code ?? '', {
    skip: !code,
  });

  const rows: [string, string | null | undefined][] = data?.valid
    ? [
        ['Certificate number', data.certificateNumber],
        ['Licence / registration', data.licenseType],
        ['Holder', data.companyName],
        ['Issued', data.issueDate],
        ['Expires', data.expiryDate],
      ]
    : [];

  return (
    <Container size="xs" py="xl">
      <Stack align="center" gap="lg">
        <Group gap="xs">
          <IconShieldCheck size={28} color="var(--mantine-color-blue-6)" />
          <Title order={3}>EMA Certificate Verification</Title>
        </Group>

        {!code && (
          <Card withBorder radius="md" p="lg" w="100%">
            <Stack>
              <Text size="sm" c="dimmed">
                Scan the QR code on a certificate, or enter its verification
                code below.
              </Text>
              <Group>
                <TextInput
                  flex={1}
                  placeholder="Verification code"
                  value={manualCode}
                  onChange={(e) => setManualCode(e.currentTarget.value)}
                />
                <Button
                  leftSection={<IconSearch size={16} />}
                  disabled={!manualCode.trim()}
                  onClick={() => navigate(`/verify/${manualCode.trim()}`)}
                >
                  Verify
                </Button>
              </Group>
            </Stack>
          </Card>
        )}

        {code && isLoading && (
          <Center py="xl">
            <Loader />
          </Center>
        )}

        {code && !isLoading && (isError || !data) && (
          <Card withBorder radius="md" p="lg" w="100%">
            <Text c="red" ta="center">
              Verification is temporarily unavailable. Please try again.
            </Text>
          </Card>
        )}

        {code && data && (
          <Card withBorder radius="md" p="lg" w="100%">
            <Stack>
              {data.valid ? (
                <Group>
                  <IconCircleCheck
                    size={40}
                    color="var(--mantine-color-green-6)"
                  />
                  <div>
                    <Text fw={700} size="lg" c="green">
                      Valid certificate
                    </Text>
                    <Text size="sm" c="dimmed">
                      Issued by the Ethiopian Maritime Authority.
                    </Text>
                  </div>
                </Group>
              ) : (
                <Group>
                  <IconCircleX size={40} color="var(--mantine-color-red-6)" />
                  <div>
                    <Group gap="xs">
                      <Text fw={700} size="lg" c="red">
                        Not valid
                      </Text>
                      {data.status && <Badge color="red">{data.status}</Badge>}
                    </Group>
                    <Text size="sm" c="dimmed">
                      {data.reason === 'not_found'
                        ? 'No certificate matches this code.'
                        : 'This certificate is no longer valid.'}
                    </Text>
                  </div>
                </Group>
              )}

              {rows.length > 0 && (
                <Table variant="vertical" layout="fixed">
                  <Table.Tbody>
                    {rows
                      .filter(([, value]) => value)
                      .map(([label, value]) => (
                        <Table.Tr key={label}>
                          <Table.Th w={170}>{label}</Table.Th>
                          <Table.Td>{value}</Table.Td>
                        </Table.Tr>
                      ))}
                  </Table.Tbody>
                </Table>
              )}

              <Button
                variant="subtle"
                size="compact-sm"
                onClick={() => {
                  setManualCode('');
                  navigate('/verify');
                }}
              >
                Verify another certificate
              </Button>
            </Stack>
          </Card>
        )}
      </Stack>
    </Container>
  );
}
