import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import {
  Button,
  Card,
  Center,
  Container,
  Group,
  Loader,
  Stack,
  Text,
  ThemeIcon,
  Title,
} from '@mantine/core';
import {
  IconAlertTriangle,
  IconCircleCheck,
  IconClockHour4,
} from '@tabler/icons-react';
import { useGetApplicationPaymentQuery } 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 [params] = useSearchParams();
  const navigate = useNavigate();
  const applicationId = params.get('applicationId') ?? '';
  const [attempts, setAttempts] = useState(0);

  const { data, refetch, isLoading } = useGetApplicationPaymentQuery(
    applicationId,
    { skip: !applicationId },
  );

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

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

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

  if (!applicationId) {
    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}>We could not identify this payment</Title>
            <Text size="sm" c="dimmed" ta="center">
              Open the application from your list to check its payment status.
            </Text>
            <Button onClick={() => navigate('/licensing/applications')}>
              My applications
            </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}>Still confirming your payment</Title>
              <Text size="sm" c="dimmed" ta="center">
                Telebirr has not confirmed this payment yet. If the money has
                left your account it will be applied automatically — there is no
                need to pay again.
              </Text>
              <Group>
                <Button variant="default" onClick={() => { setAttempts(0); refetch(); }}>
                  Check again
                </Button>
                <Button onClick={() => navigate('/licensing/applications')}>
                  My applications
                </Button>
              </Group>
            </>
          ) : (
            <>
              {isLoading || !settled ? <Loader /> : (
                <ThemeIcon size={48} radius="xl" color="teal" variant="light">
                  <IconCircleCheck size={24} />
                </ThemeIcon>
              )}
              <Title order={4}>Confirming your payment…</Title>
              <Text size="sm" c="dimmed" ta="center">
                This usually takes a few seconds. Please do not close this page.
              </Text>
            </>
          )}
        </Stack>
      </Card>
    </Container>
  );
}

export default PaymentCheckPage;
