import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Badge,
  Button,
  Card,
  Container,
  Drawer,
  Group,
  Loader,
  Modal,
  Select,
  Stack,
  Table,
  Tabs,
  Text,
  TextInput,
  Textarea,
  Title,
  Tooltip,
} from '@mantine/core';
import {
  IconAnchor,
  IconSearch,
  IconShieldCog,
  IconStethoscope,
} from '@tabler/icons-react';
import { AdvancedTable, notify, useServerTable, type AdvancedColumn } from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';
import {
  extractErrorMessage,
  useApiQuery,
  useGetMedicalForProfileQuery,
  useGetSeaServiceForProfileQuery,
  useUpdateSeafarerStatusMutation,
} from '@ema-platform/api';

interface ProfileRow {
  id: string;
  firstName: string;
  middleName?: string;
  lastName: string;
  gender?: string;
  type?: string;
  isComplete?: boolean;
  seafarerNumber?: string | null;
  seafarerStatus?: string | null;
  seafarerDepartment?: string | null;
  seafarerStatusReason?: string | null;
  profession?: { name?: { en?: string } };
  address?: { idNumber?: string; nationality?: string; primaryPhoneNumber?: string };
}

const SEAFARER_STATUS_COLORS: Record<string, string> = {
  ACTIVE: 'green',
  PENDING: 'yellow',
  SUSPENDED: 'orange',
  INACTIVE: 'gray',
};

const RECORD_STATUS_COLORS: Record<string, string> = {
  SUBMITTED: 'blue',
  VERIFIED: 'green',
  REJECTED: 'red',
};

const DEPARTMENT_LABELS: Record<string, string> = {
  DECK: 'Deck',
  ENGINE: 'Engine',
  CATERING: 'Catering',
};

/** The registered seafarer's records, read-only (verification is module 06). */
function SeafarerDetailDrawer({
  profile,
  onClose,
}: {
  profile: ProfileRow | null;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  const profileId = profile?.id ?? '';
  const { data: seaService, isLoading: loadingSea } =
    useGetSeaServiceForProfileQuery(profileId, { skip: !profileId });
  const { data: medical, isLoading: loadingMedical } =
    useGetMedicalForProfileQuery(profileId, { skip: !profileId });
  const showDate = useDateDisplayer();

  return (
    <Drawer
      opened={Boolean(profile)}
      onClose={onClose}
      position="right"
      size="lg"
      title={
        profile
          ? [profile.firstName, profile.middleName, profile.lastName]
              .filter(Boolean)
              .join(' ')
          : ''
      }
    >
      {profile && (
        <Stack>
          <Group gap="xl">
            <div>
              <Text size="xs" c="dimmed" tt="uppercase">
                {t('seafarerRegistry.drawer.seafarerNumber', 'Seafarer number')}
              </Text>
              <Text fw={700} ff="monospace">
                {profile.seafarerNumber ?? '—'}
              </Text>
            </div>
            <div>
              <Text size="xs" c="dimmed" tt="uppercase">
                {t('seafarerRegistry.drawer.department', 'Department')}
              </Text>
              <Text fw={600}>
                {profile.seafarerDepartment
                  ? t(
                      `seafarerRegistry.departments.${profile.seafarerDepartment}`,
                      DEPARTMENT_LABELS[profile.seafarerDepartment] ??
                        profile.seafarerDepartment,
                    )
                  : '—'}
              </Text>
            </div>
            <div>
              <Text size="xs" c="dimmed" tt="uppercase">
                {t('seafarerRegistry.drawer.status', 'Status')}
              </Text>
              <Badge
                color={
                  SEAFARER_STATUS_COLORS[profile.seafarerStatus ?? ''] ?? 'gray'
                }
              >
                {profile.seafarerStatus
                  ? t(`seafarerRegistry.status.${profile.seafarerStatus}`, profile.seafarerStatus)
                  : t('seafarerRegistry.drawer.notRegistered', 'NOT REGISTERED')}
              </Badge>
            </div>
          </Group>
          {profile.seafarerStatusReason && (
            <Text size="sm" c="dimmed">
              {t('seafarerRegistry.drawer.statusReason', {
                reason: profile.seafarerStatusReason,
                defaultValue: 'Status reason: {{reason}}',
              })}
            </Text>
          )}

          <Tabs defaultValue="sea-service" keepMounted={false}>
            <Tabs.List>
              <Tabs.Tab value="sea-service" leftSection={<IconAnchor size={14} />}>
                {t('seafarerRegistry.drawer.seaServiceTab', 'Sea Service')}
              </Tabs.Tab>
              <Tabs.Tab value="medical" leftSection={<IconStethoscope size={14} />}>
                {t('seafarerRegistry.drawer.medicalTab', 'Medical')}
              </Tabs.Tab>
            </Tabs.List>

            <Tabs.Panel value="sea-service" pt="sm">
              {loadingSea ? (
                <Loader size="sm" />
              ) : (seaService ?? []).length === 0 ? (
                <Text size="sm" c="dimmed">
                  {t('seafarerRegistry.drawer.noSeaService', 'No sea-service records.')}
                </Text>
              ) : (
                <Table striped>
                  <Table.Thead>
                    <Table.Tr>
                      <Table.Th>{t('seafarerRegistry.drawer.vessel', 'Vessel')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.rank', 'Rank')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.period', 'Period')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.status', 'Status')}</Table.Th>
                    </Table.Tr>
                  </Table.Thead>
                  <Table.Tbody>
                    {(seaService ?? []).map((record) => (
                      <Table.Tr key={record.id}>
                        <Table.Td>
                          {record.vesselName}
                          {record.imoNumber && (
                            <Text size="xs" c="dimmed">
                              {t('seafarerRegistry.drawer.imoPrefix', {
                                number: record.imoNumber,
                                defaultValue: 'IMO {{number}}',
                              })}
                            </Text>
                          )}
                        </Table.Td>
                        <Table.Td>{record.rank}</Table.Td>
                        <Table.Td>
                          {showDate(record.engagementDate)} → {showDate(record.dischargeDate)}
                        </Table.Td>
                        <Table.Td>
                          <Badge size="sm" color={RECORD_STATUS_COLORS[record.status]}>
                            {t(`seafarerRegistry.recordStatus.${record.status}`, record.status)}
                          </Badge>
                        </Table.Td>
                      </Table.Tr>
                    ))}
                  </Table.Tbody>
                </Table>
              )}
            </Tabs.Panel>

            <Tabs.Panel value="medical" pt="sm">
              {loadingMedical ? (
                <Loader size="sm" />
              ) : (medical ?? []).length === 0 ? (
                <Text size="sm" c="dimmed">
                  {t('seafarerRegistry.drawer.noMedical', 'No medical certificates.')}
                </Text>
              ) : (
                <Table striped>
                  <Table.Thead>
                    <Table.Tr>
                      <Table.Th>{t('seafarerRegistry.drawer.issuer', 'Issuer')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.validity', 'Validity')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.fitness', 'Fitness')}</Table.Th>
                      <Table.Th>{t('seafarerRegistry.drawer.status', 'Status')}</Table.Th>
                    </Table.Tr>
                  </Table.Thead>
                  <Table.Tbody>
                    {(medical ?? []).map((certificate) => (
                      <Table.Tr key={certificate.id}>
                        <Table.Td>{certificate.issuerName}</Table.Td>
                        <Table.Td>
                          {showDate(certificate.issueDate)} → {showDate(certificate.expiryDate)}
                        </Table.Td>
                        <Table.Td>{certificate.fitnessStatus}</Table.Td>
                        <Table.Td>
                          <Badge
                            size="sm"
                            color={RECORD_STATUS_COLORS[certificate.status]}
                          >
                            {t(`seafarerRegistry.recordStatus.${certificate.status}`, certificate.status)}
                          </Badge>
                        </Table.Td>
                      </Table.Tr>
                    ))}
                  </Table.Tbody>
                </Table>
              )}
            </Tabs.Panel>
          </Tabs>
        </Stack>
      )}
    </Drawer>
  );
}

/** US-SEA-013: suspend / reinstate / close, always with a reason. */
function StatusModal({
  profile,
  onClose,
  onDone,
}: {
  profile: ProfileRow | null;
  onClose: () => void;
  onDone: () => void;
}) {
  const { t } = useTranslation();
  const [status, setStatus] = useState<string | null>(null);
  const [reason, setReason] = useState('');
  const [updateStatus, { isLoading }] = useUpdateSeafarerStatusMutation();

  const submit = async () => {
    if (!profile || !status) return;
    try {
      await updateStatus({
        profileId: profile.id,
        status: status as 'ACTIVE' | 'INACTIVE' | 'SUSPENDED' | 'PENDING',
        reason,
      }).unwrap();
      notify.success(t('seafarerRegistry.modal.updated', 'Seafarer status updated'));
      onClose();
      onDone();
    } catch (error) {
      notify.error(
        extractErrorMessage(error, t('seafarerRegistry.modal.updateFailed', 'Could not update the status')),
      );
    }
  };

  return (
    <Modal
      opened={Boolean(profile)}
      onClose={onClose}
      title={t('seafarerRegistry.modal.title', 'Change seafarer status')}
      centered
    >
      <Stack>
        <Text size="sm" c="dimmed">
          {t('seafarerRegistry.modal.body', {
            number: profile?.seafarerNumber,
            status: profile?.seafarerStatus
              ? t(`seafarerRegistry.status.${profile.seafarerStatus}`, profile.seafarerStatus)
              : profile?.seafarerStatus,
            defaultValue:
              '{{number}} — currently {{status}}. The reason is recorded and visible to the seafarer.',
          })}
        </Text>
        <Select
          label={t('seafarerRegistry.modal.newStatus', 'New status')}
          required
          data={[
            { value: 'SUSPENDED', label: t('seafarerRegistry.modal.suspend', 'Suspend') },
            { value: 'INACTIVE', label: t('seafarerRegistry.modal.close', 'Close') },
            { value: 'ACTIVE', label: t('seafarerRegistry.modal.reinstate', 'Reinstate') },
          ].filter((o) => o.value !== profile?.seafarerStatus)}
          value={status}
          onChange={setStatus}
        />
        <Textarea
          label={t('seafarerRegistry.modal.reason', 'Reason')}
          required
          minRows={2}
          value={reason}
          onChange={(e) => setReason(e.target.value)}
        />
        <Group justify="flex-end">
          <Button variant="default" onClick={onClose}>
            {t('seafarerRegistry.modal.cancel', 'Cancel')}
          </Button>
          <Button
            color={status === 'ACTIVE' ? 'green' : 'orange'}
            disabled={!status || reason.trim().length < 3}
            loading={isLoading}
            onClick={submit}
          >
            {t('seafarerRegistry.modal.confirm', 'Confirm')}
          </Button>
        </Group>
      </Stack>
    </Modal>
  );
}

/**
 * Registered seafarer profiles, read from the real profiles endpoint.
 *
 * Registration review itself happens in the licence queue (the
 * SEAFARER_REGISTRATION application type); this page is the resulting
 * register — numbers, departments, statuses, and each seafarer's records.
 */
export function SeafarerRegistryPage() {
  const { t } = useTranslation();
  const [search, setSearch] = useState('');
  const [detail, setDetail] = useState<ProfileRow | null>(null);
  const [statusTarget, setStatusTarget] = useState<ProfileRow | null>(null);
  const { data, isLoading, refetch } = useApiQuery<{
    total: number;
    items: ProfileRow[];
  }>({
    url: '/profiles',
    method: 'GET',
    params: { q: 'i=profession,address&t=200' },
  });
  const { setPageIndex, pageSize, setPageSize, paginate } = useServerTable();

  const items = (data?.items ?? []).filter((p) => {
    if (!search.trim()) return true;
    const term = search.toLowerCase();
    return [
      p.firstName,
      p.middleName,
      p.lastName,
      p.address?.idNumber,
      p.seafarerNumber,
    ]
      .filter(Boolean)
      .some((v) => String(v).toLowerCase().includes(term));
  });
  const page = paginate(items);

  const columns: AdvancedColumn<ProfileRow>[] = [
    {
      header: t('seafarerRegistry.columns.name', 'Name'),
      cell: ({ row }) => (
        <Text
          size="sm"
          fw={500}
          style={{ cursor: 'pointer' }}
          onClick={() => setDetail(row.original)}
        >
          {[row.original.firstName, row.original.middleName, row.original.lastName].filter(Boolean).join(' ')}
        </Text>
      ),
    },
    {
      header: t('seafarerRegistry.columns.number', 'Seafarer №'),
      cell: ({ row }) => <Text size="sm" ff="monospace">{row.original.seafarerNumber ?? '—'}</Text>,
    },
    {
      header: t('seafarerRegistry.columns.department', 'Department'),
      cell: ({ row }) => (
        <Text size="sm">
          {row.original.seafarerDepartment
            ? t(
                `seafarerRegistry.departments.${row.original.seafarerDepartment}`,
                DEPARTMENT_LABELS[row.original.seafarerDepartment] ?? row.original.seafarerDepartment,
              )
            : '—'}
        </Text>
      ),
    },
    {
      header: t('seafarerRegistry.columns.idNumber', 'ID number'),
      cell: ({ row }) => <Text size="sm" c="dimmed">{row.original.address?.idNumber ?? '—'}</Text>,
    },
    {
      header: t('seafarerRegistry.columns.phone', 'Phone'),
      cell: ({ row }) => <Text size="sm" c="dimmed">{row.original.address?.primaryPhoneNumber ?? '—'}</Text>,
    },
    {
      header: t('seafarerRegistry.columns.status', 'Status'),
      cell: ({ row }) =>
        row.original.seafarerNumber ? (
          <Badge size="sm" variant="light" color={SEAFARER_STATUS_COLORS[row.original.seafarerStatus ?? ''] ?? 'gray'}>
            {t(`seafarerRegistry.status.${row.original.seafarerStatus}`, row.original.seafarerStatus ?? '')}
          </Badge>
        ) : (
          <Badge size="sm" variant="light" color={row.original.isComplete ? 'teal' : 'gray'}>
            {row.original.isComplete
              ? t('seafarerRegistry.notRegistered', 'Not registered')
              : t('seafarerRegistry.incomplete', 'Incomplete')}
          </Badge>
        ),
    },
    {
      header: '',
      label: t('seafarerRegistry.columns.actions', 'Actions'),
      cell: ({ row }) =>
        row.original.seafarerNumber ? (
          <Tooltip label={t('seafarerRegistry.statusActionTooltip', 'Suspend / reinstate / close')}>
            <Button
              size="compact-xs"
              variant="subtle"
              leftSection={<IconShieldCog size={14} />}
              onClick={() => setStatusTarget(row.original)}
            >
              {t('seafarerRegistry.statusAction', 'Status')}
            </Button>
          </Tooltip>
        ) : null,
    },
  ];

  return (
    <Container size="xl" py="md">
      <Group justify="space-between" mb="md">
        <div>
          <Title order={3}>{t('seafarerRegistry.title', 'Seafarer registry')}</Title>
          <Text size="sm" c="dimmed">
            {t('seafarerRegistry.profileCount', {
              count: data?.total ?? 0,
              defaultValue: '{{count}} profile(s)',
            })}
          </Text>
        </div>
        <TextInput
          placeholder={t('seafarerRegistry.searchPlaceholder', 'Name, ID or seafarer number')}
          leftSection={<IconSearch size={14} />}
          value={search}
          onChange={(e) => setSearch(e.currentTarget.value)}
          w={280}
        />
      </Group>

      <Card withBorder padding={0}>
        <AdvancedTable
          columns={columns}
          data={page.rows}
          tableName={t('seafarerRegistry.title', 'Seafarer registry')}
          itemCount={page.itemCount}
          pageIndex={page.pageIndex}
          onPageChange={setPageIndex}
          pageSize={pageSize}
          onPageSizeChange={setPageSize}
          refresh={refetch}
          isLoading={isLoading}
          emptyText={
            search
              ? t('seafarerRegistry.emptySearch', 'No profiles match that search.')
              : t('seafarerRegistry.emptyNone', 'No seafarers registered yet.')
          }
        />
      </Card>

      <SeafarerDetailDrawer profile={detail} onClose={() => setDetail(null)} />
      <StatusModal
        profile={statusTarget}
        onClose={() => setStatusTarget(null)}
        onDone={refetch}
      />
    </Container>
  );
}

export default SeafarerRegistryPage;
