import { type StatusTone } from '@ema-platform/shared';
import { Button, Text, Tooltip } from '@mantine/core';
import { IconShieldCog } from '@tabler/icons-react';
import type { AdvancedColumn } from '@ema-platform/ui';
import { StatusBadge } from '@ema-platform/ui';
import type { Vessel } from '@ema-platform/api';
import { LICENSE_PERMISSIONS, RequirePermission } from '@ema-platform/auth';

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

export const CATEGORY_LABELS: Record<string, string> = {
  INLAND_WATERWAY: 'Inland Waterway',
  SEA_GOING: 'Sea-going',
};

export function vesselRegistrationQueueColumns(
  showDate: (value: string | number | Date | null | undefined) => string,
  handlers: {
    onStatus: (vessel: Vessel) => void;
  },
): AdvancedColumn<Vessel>[] {
  return [
    {
      header: 'Registration №',
      cell: ({ row }) => (
        <Text size="sm" ff="monospace" fw={600}>
          {row.original.registrationNumber}
        </Text>
      ),
    },
    {
      header: 'Vessel',
      cell: ({ row }) => (
        <>
          <Text size="sm" fw={500}>
            {row.original.name}
          </Text>
          <Text size="xs" c="dimmed">
            {row.original.vesselType ?? '—'}
            {row.original.imoNumber ? ` · IMO ${row.original.imoNumber}` : ''}
          </Text>
        </>
      ),
    },
    {
      header: 'Category',
      cell: ({ row }) => CATEGORY_LABELS[row.original.category] ?? row.original.category,
    },
    {
      header: 'Owner',
      cell: ({ row }) => <Text size="sm">{row.original.ownerName ?? '—'}</Text>,
    },
    {
      header: 'Registered',
      cell: ({ row }) => (
        <Text size="sm" c="dimmed">
          {showDate(row.original.registeredAt)}
        </Text>
      ),
    },
    {
      header: 'Status',
      cell: ({ row }) => (
        <StatusBadge
          tone={VESSEL_STATUS_TONES[row.original.status]}
          label={row.original.status}
          size="sm"
          variant="light"
        />
      ),
    },
    {
      header: '',
      label: 'Actions',
      align: 'right',
      cell: ({ row }) => (
        <RequirePermission
          anyOf={[LICENSE_PERMISSIONS.MANAGE_VESSEL_STATUS]}
          hideOnly
        >
          <Tooltip label="Suspend / deregister / reinstate">
            <Button
              size="compact-xs"
              variant="subtle"
              leftSection={<IconShieldCog size={14} />}
              onClick={(e) => {
                e.stopPropagation();
                handlers.onStatus(row.original);
              }}
            >
              Status
            </Button>
          </Tooltip>
        </RequirePermission>
      ),
    },
  ];
}
