import {
  Alert,
  Anchor,
  Badge,
  Button,
  Card,
  FileButton,
  Group,
  Loader,
  Modal,
  NumberInput,
  Paper,
  Select,
  Stack,
  Text,
  TextInput,
  Textarea,
  Title,
} from '@mantine/core';
import {
  IconAnchor,
  IconFileUpload,
  IconInfoCircle,
  IconPaperclip,
  IconPlus,
  IconStethoscope,
} from '@tabler/icons-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  AdvancedTable,
  AmharicDatePicker,
  notify,
  PdfPreviewModal,
  useServerTable,
} from '@ema-platform/ui';
import { useDateDisplayer } from '@ema-platform/shared';
import {
  extractErrorMessage,
  seaServiceDays,
  uploadDocument,
  useCreateMedicalCertificateMutation,
  useCreateSeaServiceRecordMutation,
  useDeleteMedicalCertificateMutation,
  useDeleteSeaServiceRecordMutation,
  useGetAttachmentsQuery,
  useGetMyMedicalCertificatesQuery,
  useGetMySeaServiceRecordsQuery,
  useGetMySeaTimeQuery,
  useUpdateMedicalCertificateMutation,
  useUpdateSeaServiceRecordMutation,
} from '@ema-platform/api';
import type { MedicalCertificate, SeaServiceRecord } from '@ema-platform/api';
import {
  PORTAL_PERMISSIONS,
  RequirePermission,
  usePermissions,
} from '@ema-platform/auth';
import { seaServiceColumns, medicalColumns, fitnessOptions } from './columns';
import { seaServiceActionsColumn, medicalActionsColumn } from './actions';

/**
 * Evidence viewer/uploader shared by both record kinds.
 *
 * Files upload against the record itself (`SEA_SERVICE_RECORD` /
 * `MEDICAL_CERTIFICATE` owner types), so the officer verifying it later opens
 * exactly what the seafarer attached.
 */
function EvidenceModal({
  ownerType,
  ownerId,
  onClose,
}: {
  ownerType: 'SEA_SERVICE_RECORD' | 'MEDICAL_CERTIFICATE';
  ownerId: string | null;
  onClose: () => void;
}) {
  const { t } = useTranslation();
  const { data: attachments, isLoading } = useGetAttachmentsQuery(
    { ownerType, ownerId: ownerId ?? '' },
    { skip: !ownerId },
  );
  const [preview, setPreview] = useState<{ url: string; title: string } | null>(
    null,
  );

  const files = (attachments ?? []).flatMap((a) => a.files);

  return (
    <Modal opened={Boolean(ownerId)} onClose={onClose} title={t('seaRecords.evidence.title')} centered>
      <Stack>
        {isLoading ? (
          <Loader size="sm" type="oval" />
        ) : files.length === 0 ? (
          <Text size="sm" c="dimmed">
            {t('seaRecords.evidence.none')}
          </Text>
        ) : (
          files.map((file) => (
            <Group key={file.id} gap="xs">
              <IconPaperclip size={16} />
              {file.url ? (
                <Anchor
                  component="button"
                  type="button"
                  size="sm"
                  onClick={() =>
                    setPreview({ url: file.url as string, title: file.originalName })
                  }
                >
                  {file.originalName}
                </Anchor>
              ) : (
                <Text size="sm">{file.originalName}</Text>
              )}
            </Group>
          ))
        )}
      </Stack>
      <PdfPreviewModal
        opened={Boolean(preview)}
        onClose={() => setPreview(null)}
        url={preview?.url ?? ''}
        title={preview?.title}
      />
    </Modal>
  );
}

/**
 * Evidence picker that lives inside the add/edit form. The file is held in
 * component state and uploaded right after the record is saved, because the
 * attachment needs an owner id that only exists once the record does.
 */
function EvidenceField({
  file,
  onChange,
}: {
  file: File | null;
  onChange: (file: File | null) => void;
}) {
  const { t } = useTranslation();
  return (
    <RequirePermission anyOf={[PORTAL_PERMISSIONS.UPLOAD_DOCUMENTS]} hideOnly>
      <Group gap="sm" align="center">
        <FileButton onChange={onChange} accept="image/*,application/pdf">
          {(props) => (
            <Button
              {...props}
              variant="light"
              leftSection={<IconFileUpload size={16} />}
            >
              {t('seaRecords.evidence.upload')}
            </Button>
          )}
        </FileButton>
        <Text size="sm" c={file ? undefined : 'dimmed'}>
          {file ? file.name : t('seaRecords.evidence.none')}
        </Text>
      </Group>
    </RequirePermission>
  );
}

// ---------------------------------------------------------------- sea service

/** Today as a `yyyy-mm-dd` key — same shape the pickers emit, so plain
 * string comparison is a valid date comparison. Taken in the authority's
 * timezone, matching the server's check, so a seafarer logging in from a
 * zone ahead of Addis isn't offered a day the server then rejects. */
const todayKey = () =>
  new Date().toLocaleDateString('en-CA', { timeZone: 'Africa/Addis_Ababa' });

const EMPTY_SEA_SERVICE = {
  vesselName: '',
  imoNumber: '',
  vesselType: '',
  flagState: '',
  rank: '',
  engagementDate: '',
  dischargeDate: '',
  dutiesDescription: '',
};

function SeaServiceTab() {
  const { t } = useTranslation();
  const showDate = useDateDisplayer();
  const { can } = usePermissions();
  const { data: records, isLoading, refetch } = useGetMySeaServiceRecordsQuery();
  const { data: seaTime } = useGetMySeaTimeQuery();
  const [createRecord, { isLoading: creating }] =
    useCreateSeaServiceRecordMutation();
  const [updateRecord, { isLoading: updating }] =
    useUpdateSeaServiceRecordMutation();
  const [deleteRecord] = useDeleteSeaServiceRecordMutation();

  const [editing, setEditing] = useState<SeaServiceRecord | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [evidenceFor, setEvidenceFor] = useState<string | null>(null);
  const [form, setForm] = useState(EMPTY_SEA_SERVICE);
  const [grossTonnage, setGrossTonnage] = useState<number | ''>('');
  const [evidenceFile, setEvidenceFile] = useState<File | null>(null);
  const [uploadingEvidence, setUploadingEvidence] = useState(false);
  const [uploading, setUploading] = useState(false);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY_SEA_SERVICE);
    setGrossTonnage('');
    setEvidenceFile(null);
    setModalOpen(true);
  };

  const openEdit = (record: SeaServiceRecord) => {
    setEditing(record);
    setForm({
      vesselName: record.vesselName,
      imoNumber: record.imoNumber ?? '',
      vesselType: record.vesselType ?? '',
      flagState: record.flagState ?? '',
      rank: record.rank,
      engagementDate: record.engagementDate,
      dischargeDate: record.dischargeDate,
      dutiesDescription: record.dutiesDescription ?? '',
    });
    setGrossTonnage(record.grossTonnage ? Number(record.grossTonnage) : '');
    setEvidenceFile(null);
    setModalOpen(true);
  };

  const save = async () => {
    const body = {
      vesselName: form.vesselName,
      rank: form.rank,
      engagementDate: form.engagementDate,
      dischargeDate: form.dischargeDate,
      ...(form.imoNumber ? { imoNumber: form.imoNumber } : {}),
      ...(form.vesselType ? { vesselType: form.vesselType } : {}),
      ...(form.flagState ? { flagState: form.flagState } : {}),
      ...(form.dutiesDescription
        ? { dutiesDescription: form.dutiesDescription }
        : {}),
      ...(grossTonnage !== '' ? { grossTonnage: Number(grossTonnage) } : {}),
    };
    try {
      let recordId = editing?.id;
      if (editing) {
        await updateRecord({ id: editing.id, body }).unwrap();
      } else {
        const created = await createRecord(body).unwrap();
        recordId = created.id;
        notify.success('Sea-service record added');
      }

      if (evidenceFile && recordId) {
        setUploadingEvidence(true);
        const result = await uploadDocument({
          ownerType: 'SEA_SERVICE_RECORD',
          ownerId: recordId,
          documentKey: 'evidence',
          file: evidenceFile,
        });
        setUploadingEvidence(false);
        if (result.ok) {
          notify.success('Evidence uploaded');
        } else {
          notify.error(result.error);
        }
      }

      setModalOpen(false);
    } catch (error) {
      notify.error(extractErrorMessage(error, t('seaRecords.seaService.saveFailed')));
    }
  };

  const remove = async (record: SeaServiceRecord) => {
    try {
      await deleteRecord(record.id).unwrap();
      notify.success(t('seaRecords.seaService.withdrawn'));
    } catch (error) {
      notify.error(extractErrorMessage(error, t('seaRecords.seaService.deleteFailed')));
    }
  };

  // Service already served — neither end of an engagement can be in the future.
  const today = todayKey();
  const dateError =
    form.engagementDate > today || form.dischargeDate > today
      ? t('seaRecords.seaService.dateFuture', {
          defaultValue: 'Engagement and discharge dates cannot be in the future.',
        })
      : form.engagementDate &&
          form.dischargeDate &&
          form.engagementDate >= form.dischargeDate
        ? t('seaRecords.seaService.dateOrder', {
            defaultValue: 'Discharge date must be after the engagement date.',
          })
        : null;

  // Shown once the field has something in it — a blank required field is left
  // to the button being disabled, same as the rest of the form; only an
  // actual too-short value gets called out.
  const vesselNameError =
    form.vesselName && form.vesselName.trim().length <= 1
      ? t('seaRecords.seaService.fields.vesselNameTooShort', {
          defaultValue: 'Must be at least 2 characters.',
        })
      : null;
  const rankError =
    form.rank && form.rank.trim().length <= 1
      ? t('seaRecords.seaService.fields.rankTooShort', {
          defaultValue: 'Must be at least 2 characters.',
        })
      : null;

  const valid =
    form.vesselName.trim().length > 1 &&
    form.rank.trim().length > 1 &&
    form.engagementDate &&
    form.dischargeDate &&
    !dateError;

  // Shown under the date pickers as they are filled: the seafarer sees what
  // the engagement is worth before saving it.
  const formDays = seaServiceDays(form.engagementDate, form.dischargeDate);
  // Every record as entered (verified or not), beside the approved figure.
  const declaredDays = (records ?? []).reduce(
    (sum, r) => sum + (seaServiceDays(r.engagementDate, r.dischargeDate) ?? 0),
    0,
  );

  const { setPageIndex, pageSize, setPageSize, paginate } = useServerTable({ pageSize: 10 });
  const page = paginate(records ?? []);

  const columns = [
    ...seaServiceColumns(t, showDate),
    seaServiceActionsColumn(t, {
      can,
      onEvidence: (record) => setEvidenceFor(record.id),
      onEdit: openEdit,
      onDelete: remove,
    }),
  ];

  return (
    <Stack>
      <Group justify="space-between">
        <Group gap="sm">
          <Text size="sm" c="dimmed">
            {t('seaRecords.seaService.description')}
          </Text>
          {(records ?? []).length > 0 && (
            <Badge variant="light" color="blue">
              {t('seaRecords.seaService.declaredSeaTime', {
                days: declaredDays,
                defaultValue: 'Declared sea time: {{days}} days',
              })}
            </Badge>
          )}
          {seaTime && seaTime.verifiedRecords > 0 && (
            <Badge variant="light" color="teal">
              {t('seaRecords.seaService.approvedSeaTime', { days: seaTime.totalDays })}
            </Badge>
          )}
        </Group>
        <RequirePermission anyOf={[PORTAL_PERMISSIONS.ADD_SEA_SERVICE]} hideOnly>
          <Button leftSection={<IconPlus size={16} />} onClick={openCreate}>
            {t('seaRecords.seaService.add')}
          </Button>
        </RequirePermission>
      </Group>
      {(records ?? []).length === 0 ? (
        <Paper withBorder p="xl" radius="md">
          <Text c="dimmed" ta="center">
            {t('seaRecords.seaService.empty')}
          </Text>
        </Paper>
      ) : (
        <Card withBorder padding={0}>
          <AdvancedTable
            columns={columns}
            data={page.rows}
            tableName={t('seaRecords.seaService.tableName')}
            itemCount={page.itemCount}
            pageIndex={page.pageIndex}
            onPageChange={setPageIndex}
            pageSize={pageSize}
            onPageSizeChange={setPageSize}
            isLoading={isLoading}
            refresh={refetch}
          />
        </Card>
      )}

      <Modal
        opened={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? t('seaRecords.seaService.modal.editTitle') : t('seaRecords.seaService.modal.addTitle')}
        centered
        size="lg"
      >
        <Stack>
          <Group grow>
            <TextInput
              label={t('seaRecords.seaService.fields.vesselName')}
              required
              value={form.vesselName}
              onChange={(e) => setForm({ ...form, vesselName: e.target.value })}
              error={vesselNameError}
            />
            <TextInput
              label={t('seaRecords.seaService.fields.imoNumber')}
              value={form.imoNumber}
              onChange={(e) => setForm({ ...form, imoNumber: e.target.value })}
            />
          </Group>
          <Group grow>
            <TextInput
              label={t('seaRecords.seaService.fields.vesselType')}
              value={form.vesselType}
              onChange={(e) => setForm({ ...form, vesselType: e.target.value })}
            />
            <TextInput
              label={t('seaRecords.seaService.fields.flagState')}
              value={form.flagState}
              onChange={(e) => setForm({ ...form, flagState: e.target.value })}
            />
            <NumberInput
              label={t('seaRecords.seaService.fields.grossTonnage')}
              min={0}
              value={grossTonnage}
              onChange={(v) => setGrossTonnage(typeof v === 'number' ? v : '')}
            />
          </Group>
          <TextInput
            label={t('seaRecords.seaService.fields.rank')}
            description={t('seaRecords.seaService.fields.rankHint', {
              defaultValue: 'Must be at least 2 characters, e.g. "AB" or "2nd Officer".',
            })}
            required
            value={form.rank}
            onChange={(e) => setForm({ ...form, rank: e.target.value })}
            error={rankError}
          />
          <Group grow>
            <AmharicDatePicker
              label={t('seaRecords.seaService.fields.engagementDate')}
              required
              value={form.engagementDate}
              onChange={(val) =>
                setForm({ ...form, engagementDate: val })
              }
              maxDate={form.dischargeDate || today}
              dateFormat="date"
            />
            <AmharicDatePicker
              label={t('seaRecords.seaService.fields.dischargeDate')}
              required
              value={form.dischargeDate}
              onChange={(val) =>
                setForm({ ...form, dischargeDate: val })
              }
              minDate={form.engagementDate || undefined}
              maxDate={today}
              dateFormat="date"
            />
          </Group>
          {(dateError || (form.engagementDate && form.dischargeDate)) && (
            <Alert
              variant="light"
              color={dateError ? 'red' : 'teal'}
              icon={<IconInfoCircle size={16} />}
              py={6}
            >
              {dateError ??
                t('seaRecords.seaService.daysServed', {
                  days: formDays,
                  defaultValue: 'Days served on this engagement: {{days}} (both days counted)',
                })}
            </Alert>
          )}
          <Textarea
            label={t('seaRecords.seaService.fields.duties')}
            value={form.dutiesDescription}
            onChange={(e) =>
              setForm({ ...form, dutiesDescription: e.target.value })
            }
          />
          <FileButton onChange={setEvidenceFile} accept="image/*,application/pdf">
            {(props) => (
              <Button
                {...props}
                variant="light"
                leftSection={<IconFileUpload size={16} />}
              >
                {evidenceFile ? evidenceFile.name : 'Attach evidence (optional)'}
              </Button>
            )}
          </FileButton>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setModalOpen(false)}>
              {t('common.cancel')}
            </Button>
            <Button
              onClick={save}
              disabled={!valid}
              loading={creating || updating || uploadingEvidence}
            >
              {editing ? t('common.save') : t('seaRecords.seaService.addRecord')}
            </Button>
          </Group>
        </Stack>
      </Modal>

      <EvidenceModal
        ownerType="SEA_SERVICE_RECORD"
        ownerId={evidenceFor}
        onClose={() => setEvidenceFor(null)}
      />
    </Stack>
  );
}

// -------------------------------------------------------------------- medical

const EMPTY_MEDICAL = {
  issuerName: '',
  certificateNumber: '',
  issueDate: '',
  expiryDate: '',
  fitnessStatus: 'FIT',
  restrictions: '',
};

function MedicalTab() {
  const { t } = useTranslation();
  const showDate = useDateDisplayer();
  const { can } = usePermissions();
  const { data: certificates, isLoading, refetch } = useGetMyMedicalCertificatesQuery();
  const [createCertificate, { isLoading: creating }] =
    useCreateMedicalCertificateMutation();
  const [updateCertificate, { isLoading: updating }] =
    useUpdateMedicalCertificateMutation();
  const [deleteCertificate] = useDeleteMedicalCertificateMutation();

  const [editing, setEditing] = useState<MedicalCertificate | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [evidenceFor, setEvidenceFor] = useState<string | null>(null);
  const [form, setForm] = useState(EMPTY_MEDICAL);
  const [evidenceFile, setEvidenceFile] = useState<File | null>(null);
  const [uploadingEvidence, setUploadingEvidence] = useState(false);

  const openCreate = () => {
    setEditing(null);
    setForm(EMPTY_MEDICAL);
    setEvidenceFile(null);
    setModalOpen(true);
  };

  const openEdit = (certificate: MedicalCertificate) => {
    setEditing(certificate);
    setForm({
      issuerName: certificate.issuerName,
      certificateNumber: certificate.certificateNumber ?? '',
      issueDate: certificate.issueDate,
      expiryDate: certificate.expiryDate,
      fitnessStatus: certificate.fitnessStatus,
      restrictions: certificate.restrictions ?? '',
    });
    setEvidenceFile(null);
    setModalOpen(true);
  };

  const save = async () => {
    const body = {
      issuerName: form.issuerName,
      issueDate: form.issueDate,
      expiryDate: form.expiryDate,
      fitnessStatus: form.fitnessStatus as MedicalCertificate['fitnessStatus'],
      ...(form.certificateNumber
        ? { certificateNumber: form.certificateNumber }
        : {}),
      ...(form.restrictions ? { restrictions: form.restrictions } : {}),
    };
    try {
      let certificateId = editing?.id;
      if (editing) {
        await updateCertificate({ id: editing.id, body }).unwrap();
      } else {
        const created = await createCertificate(body).unwrap();
        certificateId = created.id;
        notify.success('Medical certificate added');
      }

      if (evidenceFile && certificateId) {
        setUploadingEvidence(true);
        const result = await uploadDocument({
          ownerType: 'MEDICAL_CERTIFICATE',
          ownerId: certificateId,
          documentKey: 'evidence',
          file: evidenceFile,
        });
        setUploadingEvidence(false);
        if (result.ok) {
          notify.success('Evidence uploaded');
        } else {
          notify.error(result.error);
        }
      }

      setModalOpen(false);
    } catch (error) {
      notify.error(extractErrorMessage(error, t('seaRecords.medical.saveFailed')));
    }
  };

  const remove = async (certificate: MedicalCertificate) => {
    try {
      await deleteCertificate(certificate.id).unwrap();
      notify.success(t('seaRecords.medical.withdrawn'));
    } catch (error) {
      notify.error(extractErrorMessage(error, t('seaRecords.medical.deleteFailed')));
    }
  };

  const today = todayKey();
  const valid =
    form.issuerName.trim().length > 1 &&
    form.issueDate &&
    form.expiryDate &&
    form.issueDate <= today &&
    form.issueDate < form.expiryDate;

  const { setPageIndex, pageSize, setPageSize, paginate } = useServerTable({ pageSize: 10 });
  const page = paginate(certificates ?? []);

  const columns = [
    ...medicalColumns(t, showDate),
    medicalActionsColumn(t, {
      can,
      onEvidence: (certificate) => setEvidenceFor(certificate.id),
      onEdit: openEdit,
      onDelete: remove,
    }),
  ];

  return (
    <Stack>
      <Group justify="space-between">
        <Text size="sm" c="dimmed">
          {t('seaRecords.medical.description')}
        </Text>
        <RequirePermission anyOf={[PORTAL_PERMISSIONS.UPLOAD_MEDICAL]} hideOnly>
          <Button leftSection={<IconPlus size={16} />} onClick={openCreate}>
            {t('seaRecords.medical.add')}
          </Button>
        </RequirePermission>
      </Group>
      {(certificates ?? []).length === 0 ? (
        <Paper withBorder p="xl" radius="md">
          <Text c="dimmed" ta="center">
            {t('seaRecords.medical.empty')}
          </Text>
        </Paper>
      ) : (
        <Card withBorder padding={0}>
          <AdvancedTable
            columns={columns}
            data={page.rows}
            tableName={t('seaRecords.medical.tableName')}
            itemCount={page.itemCount}
            pageIndex={page.pageIndex}
            onPageChange={setPageIndex}
            pageSize={pageSize}
            onPageSizeChange={setPageSize}
            isLoading={isLoading}
            refresh={refetch}
          />
        </Card>
      )}

      <Modal
        opened={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? t('seaRecords.medical.modal.editTitle') : t('seaRecords.medical.modal.addTitle')}
        centered
        size="lg"
      >
        <Stack>
          <Group grow>
            <TextInput
              label={t('seaRecords.medical.fields.issuerName')}
              required
              value={form.issuerName}
              onChange={(e) => setForm({ ...form, issuerName: e.target.value })}
            />
            <TextInput
              label={t('seaRecords.medical.fields.certificateNumber')}
              value={form.certificateNumber}
              onChange={(e) =>
                setForm({ ...form, certificateNumber: e.target.value })
              }
            />
          </Group>
          <Group grow>
            <AmharicDatePicker
              label={t('seaRecords.medical.fields.issueDate')}
              required
              value={form.issueDate}
              onChange={(val) => setForm({ ...form, issueDate: val })}
              maxDate={today}
              dateFormat="date"
            />
            <AmharicDatePicker
              label={t('seaRecords.medical.fields.expiryDate')}
              required
              value={form.expiryDate}
              onChange={(val) => setForm({ ...form, expiryDate: val })}
              minDate={form.issueDate || undefined}
              dateFormat="date"
            />
          </Group>
          <Select
            label={t('seaRecords.medical.fields.fitnessOutcome')}
            data={fitnessOptions(t)}
            value={form.fitnessStatus}
            onChange={(v) => setForm({ ...form, fitnessStatus: v ?? 'FIT' })}
          />
          {form.fitnessStatus === 'FIT_WITH_RESTRICTIONS' && (
            <Textarea
              label={t('seaRecords.medical.fields.restrictions')}
              value={form.restrictions}
              onChange={(e) =>
                setForm({ ...form, restrictions: e.target.value })
              }
            />
          )}
          <FileButton onChange={setEvidenceFile} accept="image/*,application/pdf">
            {(props) => (
              <Button
                {...props}
                variant="light"
                leftSection={<IconFileUpload size={16} />}
              >
                {evidenceFile ? evidenceFile.name : 'Attach evidence (optional)'}
              </Button>
            )}
          </FileButton>
          <Group justify="flex-end">
            <Button variant="default" onClick={() => setModalOpen(false)}>
              {t('common.cancel')}
            </Button>
            <Button
              onClick={save}
              disabled={!valid}
              loading={creating || updating || uploadingEvidence}
            >
              {editing ? t('common.save') : t('seaRecords.medical.add')}
            </Button>
          </Group>
        </Stack>
      </Modal>

      <EvidenceModal
        ownerType="MEDICAL_CERTIFICATE"
        ownerId={evidenceFor}
        onClose={() => setEvidenceFor(null)}
      />
    </Stack>
  );
}

/** Sea-service history (US-SSM-001): every engagement, its days, its evidence. */
export function SeaServicePage() {
  const { t } = useTranslation();
  return (
    <Stack>
      <Group gap="xs">
        <IconAnchor size={22} />
        <Title order={2}>{t('seaRecords.tabs.seaService')}</Title>
      </Group>
      <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
        {t('seaRecords.pageIntro')}
      </Alert>
      <SeaServiceTab />
    </Stack>
  );
}

/** Medical fitness certificates (US-SSM-006), editable until verified. */
export function MedicalRecordsPage() {
  const { t } = useTranslation();
  return (
    <Stack>
      <Group gap="xs">
        <IconStethoscope size={22} />
        <Title order={2}>{t('seaRecords.tabs.medical')}</Title>
      </Group>
      <Alert variant="light" color="blue" icon={<IconInfoCircle size={16} />}>
        {t('seaRecords.pageIntro')}
      </Alert>
      <MedicalTab />
    </Stack>
  );
}
