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

const POLL_INTERVAL_MS = 3000;
const MAX_ATTEMPTS = 10;

/**
 * Where Telebirr returns the applicant after paying.
 *
 * The redirect usually beats the webhook, so the payment is polled for a
 * short while. Running out of attempts means "not confirmed yet" — never
 * "failed": telling someone their payment failed when the money has left
 * their account is the worst possible outcome here.
 */
export function PaymentCheckPage() {
  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 [attempts, setAttempts] = useState(0);

  const applicationPayment = useGetApplicationPaymentQuery(applicationId, {
    skip: !applicationId,
  });
  const documentPayment = useGetDocumentPaymentQuery(documentId, { skip: !documentId });
  const { data, refetch, isLoading } = documentId ? documentPayment : applicationPayment;
  const subject = documentId ? `documentId=${documentId}` : `applicationId=${applicationId}`;
  const hasSubject = Boolean(applicationId || documentId);
  const backTo = documentId ? '/seaman-book' : '/licensing/applications';

  const status = data?.status ?? null;
  const settled = status === 'PAID' || status === 'FAILED' || status === 'CANCELLED';

  useEffect(() => {
    if (!hasSubject || settled || attempts >= MAX_ATTEMPTS) return;
    const timer = setTimeout(() => {
      refetch();
      setAttempts((n) => n + 1);
    }, POLL_INTERVAL_MS);
    return () => clearTimeout(timer);
  }, [hasSubject, settled, attempts, refetch]);

  useEffect(() => {
    if (status === 'PAID') navigate(`/payments/success?${subject}`);
    if (status === 'FAILED' || status === 'CANCELLED') {
      navigate(`/payments/failure?${subject}`);
    }
  }, [status, subject, navigate]);

  if (!hasSubject) {
    return (
      <Container size="sm" py="xl">
        <Card withBorder padding="xl">
          <Stack align="center" gap="sm">
            <ThemeIcon size={48} radius="xl" color="orange" variant="light">
              <IconAlertTriangle size={24} />
            </ThemeIcon>
            <Title order={4}>{t('payments.check.notFoundTitle')}</Title>
            <Text size="sm" c="dimmed" ta="center">
              {t('payments.check.notFoundBody')}
            </Text>
            <Button onClick={() => navigate(backTo)}>
              {t('payments.myApplications')}
            </Button>
          </Stack>
        </Card>
      </Container>
    );
  }

  const exhausted = attempts >= MAX_ATTEMPTS && !settled;

  return (
    <Container size="sm" py="xl">
      <Card withBorder padding="xl">
        <Stack align="center" gap="sm">
          {exhausted ? (
            <>
              <ThemeIcon size={48} radius="xl" color="yellow" variant="light">
                <IconClockHour4 size={24} />
              </ThemeIcon>
              <Title order={4}>{t('payments.check.stillConfirmingTitle')}</Title>
              <Text size="sm" c="dimmed" ta="center">
                {t('payments.check.stillConfirmingBody')}
              </Text>
              <Group>
                <Button variant="default" onClick={() => { setAttempts(0); refetch(); }}>
                  {t('payments.check.checkAgain')}
                </Button>
                <Button onClick={() => navigate(backTo)}>
                  {t('payments.myApplications')}
                </Button>
              </Group>
            </>
          ) : (
            <>
              {isLoading || !settled ? <Loader /> : (
                <ThemeIcon size={48} radius="xl" color="teal" variant="light">
                  <IconCircleCheck size={24} />
                </ThemeIcon>
              )}
              <Title order={4}>{t('payments.check.confirmingTitle')}</Title>
              <Text size="sm" c="dimmed" ta="center">
                {t('payments.check.confirmingBody')}
              </Text>
            </>
          )}
        </Stack>
      </Card>
    </Container>
  );
}

export default PaymentCheckPage;
