import { useNavigate, useSearchParams } from 'react-router-dom';
import {
  Button,
  Card,
  Container,
  Group,
  Stack,
  Text,
  ThemeIcon,
  Title,
} from '@mantine/core';
import { IconAlertTriangle } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { useGetApplicationPaymentQuery, useGetDocumentPaymentQuery } from '@ema-platform/api';

/** Shown when Telebirr reported the payment as failed or cancelled. */
export function PaymentFailurePage() {
  const { t } = useTranslation();
  const [params] = useSearchParams();
  const navigate = useNavigate();
  const applicationId = params.get('applicationId') ?? '';
  // Seaman Book / BTC fees come back with `documentId` instead.
  const documentId = params.get('documentId') ?? '';
  const applicationPayment = useGetApplicationPaymentQuery(applicationId, {
    skip: !applicationId,
  });
  const documentPayment = useGetDocumentPaymentQuery(documentId, { skip: !documentId });
  const { data } = documentId ? documentPayment : applicationPayment;
  const backTo = documentId ? '/seaman-book' : '/licensing/applications';

  return (
    <Container size="sm" py="xl">
      <Card withBorder padding="xl" radius="md">
        <Stack align="center" gap="sm">
          <ThemeIcon size={56} radius="xl" color="red" variant="light">
            <IconAlertTriangle size={30} />
          </ThemeIcon>
          <Title order={3}>{t('payments.failure.title')}</Title>
          <Text size="sm" c="dimmed" ta="center">
            {data?.failureReason ? data.failureReason : t('payments.failure.defaultReason')}
          </Text>
          <Text size="xs" c="dimmed" ta="center">
            {t('payments.failure.unchanged')}
          </Text>
          <Group mt="md">
            <Button variant="default" onClick={() => navigate(backTo)}>
              {t('payments.myApplications')}
            </Button>
          </Group>
        </Stack>
      </Card>
    </Container>
  );
}

export default PaymentFailurePage;
