import { useNavigate } from 'react-router-dom';
import {
  ActionIcon,
  Badge,
  Box,
  Button,
  Card,
  Divider,
  Group,
  Text,
  Tooltip,
} from '@mantine/core';
import { IconDownload, IconRefresh } from '@tabler/icons-react';
import {
  extractErrorMessage,
  localized,
  useCreateApplicationMutation,
  type IssuedLicense,
} from '@ema-platform/api';
import { notify } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';

/**
 * Renewal reuses the ordinary application wizard — a renewal is an
 * application of kind RENEWAL, asking for that licence type's renewal
 * document set. `previousLicenseId` is what ties it to the certificate being
 * replaced, and what the API requires.
 *
 * Shared by the dashboard and My Applications so both offer the same renew
 * action instead of drifting.
 */
export function useRenewLicense() {
  const navigate = useNavigate();
  const [createApplication, { isLoading: isRenewing }] =
    useCreateApplicationMutation();

  async function renewLicense(license: IssuedLicense) {
    const typeKey = license.licenseType?.key;
    if (!typeKey) return;
    try {
      const application = await createApplication({
        licenseType: typeKey,
        kind: 'RENEWAL',
        previousLicenseId: license.id,
      }).unwrap();
      navigate(`/licensing/${typeKey}/applications/${application.id}`);
    } catch (err) {
      notify.error(extractErrorMessage(err), 'Could not start the renewal');
    }
  }

  return { renewLicense, isRenewing };
}

function daysUntil(date: string): number {
  const ms = new Date(date).getTime() - Date.now();
  return Math.ceil(ms / 86_400_000);
}

export function LicenseCard({
  license,
  isDownloading,
  isRenewing,
  onDownload,
  onRenew,
}: {
  license: IssuedLicense;
  isDownloading: boolean;
  isRenewing: boolean;
  onDownload: () => void;
  onRenew: () => void;
}) {
  // The API computes both in the authority's timezone; the local fallbacks are
  // only for a cached response from before those fields existed.
  const days = license.daysUntilExpiry ?? daysUntil(license.expiryDate);
  const expired = license.status === 'EXPIRED' || days < 0;
  const renewable = license.renewable ?? false;
  const showDate = useDateDisplayer();

  return (
    <Card withBorder radius="md" padding="md" className="ema-hover-lift">
      <Group justify="space-between" align="flex-start" wrap="nowrap">
        <Box>
          <Text size="sm" fw={600}>
            {localized(license.licenseType?.name) || 'Licence'}
          </Text>
          <Text size="xs" c="dimmed" mt={2}>
            {license.certificateNumber}
          </Text>
        </Box>
        <Badge
          size="sm"
          variant="light"
          color={expired ? 'red' : license.status === 'ACTIVE' ? 'teal' : 'gray'}
        >
          {expired ? 'Expired' : license.status}
        </Badge>
      </Group>

      <Divider my="sm" />

      <Group justify="space-between" align="center">
        <Box>
          <Text size="xs" c="dimmed">
            {expired ? 'Expired on' : 'Valid until'}
          </Text>
          <Text size="sm" fw={500}>
            {showDate(license.expiryDate)}
          </Text>
        </Box>
        <Tooltip label="Download certificate">
          <ActionIcon
            variant="light"
            radius="md"
            size="lg"
            loading={isDownloading}
            onClick={onDownload}
          >
            <IconDownload size={16} />
          </ActionIcon>
        </Tooltip>
      </Group>

      {/* Renewal opens inside the licence type's window and stays open after
          expiry, so a lapsed licence is renewed rather than applied for afresh. */}
      {renewable && (
        <Button
          fullWidth
          mt="sm"
          size="xs"
          variant={expired ? 'filled' : 'light'}
          color={expired ? 'orange' : undefined}
          loading={isRenewing}
          leftSection={<IconRefresh size={14} />}
          onClick={onRenew}
        >
          {expired
            ? 'Renew — this licence has expired'
            : `Renew — expires in ${days} day${days === 1 ? '' : 's'}`}
        </Button>
      )}
    </Card>
  );
}

export default LicenseCard;
