import { StatusBadge } from '@ema-platform/ui';
import { type StatusTone } from '@ema-platform/shared';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  Badge,
  Button,
  Card,
  Group,
  Loader,
  Paper,
  Progress,
  Stack,
  Table,
  Text,
  Title,
  Tooltip,
} from '@mantine/core';
import {
  IconArrowRight,
  IconArrowsExchange,
  IconShip,
} from '@tabler/icons-react';
import {
  STATUS_COLORS,
  STATUS_LABELS,
  STATUS_PROGRESS,
  TERMINAL_STATUSES,
  useGetMyApplicationsQuery,
  useGetMyVesselsQuery,
} from '@ema-platform/api';

const TRANSFER_TYPE_KEY = 'VESSEL_OWNERSHIP_TRANSFER';

const VESSEL_STATUS_TONES: Record<string, StatusTone> = {
  REGISTERED: 'success',
  SUSPENDED: 'pending',
  DEREGISTERED: 'neutral',
};

/**
 * The vessel owner's ownership-transfer home: transfers in flight, and the
 * registered vessels eligible to start one. Same config-driven wizard as
 * registration underneath (VESSEL_OWNERSHIP_TRANSFER) — this page mirrors
 * VesselRegistrationPage, just a different entry point and no
 * certificate/renewal/incident actions, which don't apply here.
 */
export function VesselTransferPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { data: vessels, isLoading: loadingVessels } = useGetMyVesselsQuery();
  const { data: applications, isLoading: loadingApplications } =
    useGetMyApplicationsQuery();

  const categoryLabels: Record<string, string> = {
    INLAND_WATERWAY: t('vesselTransfer.table.categories.INLAND_WATERWAY'),
    SEA_GOING: t('vesselTransfer.table.categories.SEA_GOING'),
  };

  const inFlight = (applications?.items ?? []).filter(
    (app) =>
      app.licenseType?.key === TRANSFER_TYPE_KEY &&
      !TERMINAL_STATUSES.includes(app.status),
  );

  // A transfer moves ownership of a vessel already on the register — nothing
  // to transfer without at least one REGISTERED vessel.
  const hasTransferableVessel = (vessels ?? []).some(
    (v) => v.status === 'REGISTERED',
  );

  if (loadingVessels || loadingApplications) {
    return (
      <Group justify="center" py="xl">
        <Loader />
      </Group>
    );
  }

  return (
    <Stack>
      <Group justify="space-between">
        <Title order={2}>{t('vesselTransfer.title')}</Title>
        <Tooltip
          label={t('vesselTransfer.startTransferDisabledTooltip')}
          disabled={hasTransferableVessel}
        >
          <Button
            leftSection={<IconArrowsExchange size={16} />}
            disabled={!hasTransferableVessel}
            onClick={() => navigate(`/licensing/${TRANSFER_TYPE_KEY}/apply`)}
          >
            {t('vesselTransfer.startTransfer')}
          </Button>
        </Tooltip>
      </Group>

      {/* ----------------------------------------------------- in-flight */}
      {inFlight.length > 0 && (
        <Stack gap="sm">
          <Title order={4}>{t('vesselTransfer.inFlight.title')}</Title>
          {inFlight.map((app) => {
            const isDraft = app.status === 'DRAFT';
            const needsAction = app.status === 'RESUBMIT_REQUIRED';
            return (
              <Card key={app.id} withBorder radius="md" p="md">
                <Group justify="space-between" wrap="nowrap">
                  <div>
                    <Text fw={600}>{app.applicationNumber}</Text>
                    <Progress
                      value={STATUS_PROGRESS[app.status]}
                      mt="xs"
                      w={260}
                    />
                  </div>
                  <Group wrap="nowrap">
                    <Badge color={STATUS_COLORS[app.status]}>
                      {STATUS_LABELS[app.status]}
                    </Badge>
                    <Button
                      size="compact-sm"
                      variant={needsAction ? 'filled' : 'light'}
                      color={needsAction ? 'orange' : undefined}
                      rightSection={<IconArrowRight size={14} />}
                      onClick={() =>
                        navigate(
                          `/licensing/${TRANSFER_TYPE_KEY}/applications/${app.id}`,
                        )
                      }
                    >
                      {isDraft
                        ? t('common.continue')
                        : needsAction
                          ? t('vesselTransfer.inFlight.fix')
                          : t('vesselTransfer.inFlight.view')}
                    </Button>
                  </Group>
                </Group>
              </Card>
            );
          })}
        </Stack>
      )}

      {/* ------------------------------------------------------- vessels */}
      <Stack gap="sm">
        <Title order={4}>{t('vesselTransfer.myVessels.title')}</Title>
        {(vessels ?? []).length === 0 ? (
          <Paper withBorder radius="md" p="xl">
            <Stack align="center" gap="sm">
              <IconShip size={40} color="var(--mantine-color-blue-5)" />
              <Text fw={600}>{t('vesselTransfer.myVessels.empty.title')}</Text>
              <Text size="sm" c="dimmed" ta="center" maw={420}>
                {t('vesselTransfer.myVessels.empty.body')}
              </Text>
              <Button
                mt="xs"
                variant="light"
                onClick={() => navigate('/vessel-registration')}
              >
                {t('vesselTransfer.myVessels.empty.cta')}
              </Button>
            </Stack>
          </Paper>
        ) : (
          <Table.ScrollContainer minWidth={640}>
            <Table striped highlightOnHover>
              <Table.Thead>
                <Table.Tr>
                  <Table.Th>{t('vesselTransfer.table.registrationNumber')}</Table.Th>
                  <Table.Th>{t('vesselTransfer.table.vessel')}</Table.Th>
                  <Table.Th>{t('vesselTransfer.table.category')}</Table.Th>
                  <Table.Th>{t('common.status')}</Table.Th>
                  <Table.Th />
                </Table.Tr>
              </Table.Thead>
              <Table.Tbody>
                {(vessels ?? []).map((vessel) => {
                  const canTransfer = vessel.status === 'REGISTERED';
                  return (
                  <Table.Tr key={vessel.id}>
                    <Table.Td>
                      <Text ff="monospace" size="sm" fw={600}>
                        {vessel.registrationNumber}
                      </Text>
                    </Table.Td>
                    <Table.Td>
                      <Text size="sm" fw={500}>
                        {vessel.name}
                      </Text>
                      <Text size="xs" c="dimmed">
                        {vessel.vesselType ?? '—'}
                      </Text>
                    </Table.Td>
                    <Table.Td>
                      {categoryLabels[vessel.category] ?? vessel.category}
                    </Table.Td>
                    <Table.Td>
                      <StatusBadge
                        tone={VESSEL_STATUS_TONES[vessel.status]}
                        label={vessel.status}
                        size="sm"
                      />
                    </Table.Td>
                    <Table.Td>
                      <Group justify="flex-end">
                        {canTransfer ? (
                          <Tooltip label={t('vesselTransfer.table.transferTooltip')}>
                            <Button
                              size="compact-xs"
                              variant="light"
                              leftSection={<IconArrowsExchange size={14} />}
                              onClick={() =>
                                navigate(`/licensing/${TRANSFER_TYPE_KEY}/apply`)
                              }
                            >
                              {t('vesselTransfer.table.transfer')}
                            </Button>
                          </Tooltip>
                        ) : (
                          <Text size="xs" c="dimmed">
                            {t('vesselTransfer.table.notTransferable')}
                          </Text>
                        )}
                      </Group>
                    </Table.Td>
                  </Table.Tr>
                  );
                })}
              </Table.Tbody>
            </Table>
          </Table.ScrollContainer>
        )}
      </Stack>
    </Stack>
  );
}

export default VesselTransferPage;
