import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {Container, Select, Text, TextInput} from '@mantine/core';
import { IconSearch } from '@tabler/icons-react';
import { useDebouncedValue } from '@mantine/hooks';
import {
  SEAFARER_REGISTRATION_STATUS_TONES,
  SEAFARER_REGISTRATION_STATUS_LABELS,
  displaySeafarerAnswer,
  useGetActiveDepartmentsQuery,
  useListSeafarerRegistrationsQuery,
  useLocalized,
  type SeafarerRegistration,
  type SeafarerRegistrationStatus,
} from '@ema-platform/api';
import { AdvancedTable, PageHeader, StatusBadge, WaitingFor, type AdvancedColumn } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';

const PAGE_SIZE = 10;

const STATUS_FILTERS = (Object.keys(SEAFARER_REGISTRATION_STATUS_LABELS) as SeafarerRegistrationStatus[])
  .filter((s) => s !== 'DRAFT')
  .map((value) => ({ value, label: SEAFARER_REGISTRATION_STATUS_LABELS[value] }));

export function applicantName(r: Pick<SeafarerRegistration, 'firstName' | 'middleName' | 'lastName'>): string {
  return [r.firstName, r.middleName, r.lastName].filter(Boolean).join(' ') || '—';
}

/** Submitted seafarer registrations, newest first — click a row to review it. */
export function SeafarerRegistrationQueuePage() {
  const navigate = useNavigate();
  const showDate = useDateDisplayer();
  const localized = useLocalized();
  const [status, setStatus] = useState<SeafarerRegistrationStatus | null>(null);
  const [search, setSearch] = useState('');
  const [debouncedSearch] = useDebouncedValue(search, 300);
  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(PAGE_SIZE);

  const { data: departments } = useGetActiveDepartmentsQuery();
  const departmentOptions = departments?.map((d) => ({ value: d.code, label: localized(d.name) }));

  const { data, isLoading, isFetching, refetch } = useListSeafarerRegistrationsQuery({
    status: status ?? undefined,
    search: debouncedSearch || undefined,
    sortBy: 'submittedAt',
    sortDir: 'DESC',
    take: pageSize,
    skip: page * pageSize,
  });

  const columns: AdvancedColumn<SeafarerRegistration>[] = useMemo(
    () => [
      {
        header: 'Registration №',
        accessorKey: 'registrationNumber',
        cell: ({ row }) => (
          <Text size="sm" ff="monospace">
            {row.original.registrationNumber}
          </Text>
        ),
      },
      {
        header: 'Applicant',
        accessorKey: 'lastName',
        cell: ({ row }) => (
          <div>
            <Text size="sm" fw={500}>
              {applicantName(row.original)}
            </Text>
            <Text size="xs" c="dimmed">
              {row.original.nationalIdNumber ?? '—'}
            </Text>
          </div>
        ),
      },
      {
        header: 'Department',
        accessorKey: 'department',
        cell: ({ row }) => (
          <Text size="sm">
            {displaySeafarerAnswer('department', row.original.department, departmentOptions)}
          </Text>
        ),
      },
      {
        header: 'Submitted',
        accessorKey: 'submittedAt',
        cell: ({ row }) => (
          <Text size="sm">{row.original.submittedAt ? showDate(row.original.submittedAt) : '—'}</Text>
        ),
      },
      {
        header: 'Waiting',
        accessorKey: 'submittedAt',
        size: 90,
        cell: ({ row }) => (
          <WaitingFor
            since={row.original.submittedAt}
            done={row.original.status === 'APPROVED' || row.original.status === 'REJECTED'}
          />
        ),
      },
      {
        header: 'Status',
        accessorKey: 'status',
        cell: ({ row }) => (
          <StatusBadge
              tone={SEAFARER_REGISTRATION_STATUS_TONES[row.original.status]}
              label={SEAFARER_REGISTRATION_STATUS_LABELS[row.original.status]}
            />
        ),
      },
    ],
    [showDate, departmentOptions],
  );

  return (
    <Container size="xl" py="md">
      <PageHeader
        title="Seafarer Registration Queue"
        subtitle="Registrations awaiting review. Approval numbers the seafarer and opens their Seaman Book and BTC applications."
      />
      <AdvancedTable
        columns={columns}
        data={data?.items ?? []}
        tableName="Seafarer registrations"
        toolbar={
          <>
            <TextInput
              placeholder="Search number, name or ID…"
              leftSection={<IconSearch size={14} />}
              value={search}
              onChange={(e) => {
                setSearch(e.currentTarget.value);
                setPage(0);
              }}
              w={260}
            />
            <Select
              placeholder="All statuses"
              data={STATUS_FILTERS}
              value={status}
              onChange={(v) => {
                setStatus(v as SeafarerRegistrationStatus | null);
                setPage(0);
              }}
              clearable
              w={200}
            />
          </>
        }
        itemCount={data?.total ?? 0}
        pageIndex={page}
        onPageChange={setPage}
        pageSize={pageSize}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setPage(0);
        }}
        refresh={refetch}
        isLoading={isLoading || isFetching}
        emptyText="No registrations match."
        onRowClick={(row) => navigate(`/seafarer-registrations/${row.id}`)}
      />
    </Container>
  );
}

export default SeafarerRegistrationQueuePage;
