import { type StatusTone } from '@ema-platform/shared';
import { useEffect, useState } from 'react';
import {
  ActionIcon,
  Alert,
  Avatar,
  Badge,
  Box,
  Button,
  Card,
  Divider,
  Group,
  Modal,
  Paper,
  Select,
  SimpleGrid,
  Skeleton,
  Stack,
  Table,
  Tabs,
  Text,
  TextInput,
  Textarea,
  ThemeIcon,
  Title,
  rem,
} from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
import {
  IconAnchor,
  IconArrowLeft,
  IconBook,
  IconBriefcase,
  IconCertificate,
  IconCheck,
  IconClock,
  IconEdit,
  IconFileText,
  IconHeartbeat,
  IconHistory,
  IconLayoutDashboard,
  IconPlus,
  IconPrinter,
  IconShip,
  IconUser,
  IconX,
} from '@tabler/icons-react';
import { useNavigate, useParams } from 'react-router-dom';
import { StatusBadge, notify } from '@ema-platform/ui';
import type { Seafarer } from './SeafarerRegistryPage';

// ---------------------------------------------------------------------------
// Extended profile types
// ---------------------------------------------------------------------------
interface TrainingRecord {
  id: string;
  course: string;
  institution: string;
  certNo: string;
  issueDate: string;
  expiry: string;
  status: 'Approved' | 'Pending' | 'Expired';
}

interface MedicalRecord {
  id: string;
  examType: string;
  issuedBy: string;
  issueDate: string;
  expiry: string;
  result: 'Fit' | 'Unfit' | 'Conditional';
  remarks: string;
}

interface SeaServiceRecord {
  id: string;
  vesselName: string;
  vesselType: string;
  rank: string;
  flag: string;
  from: string;
  to: string;
  engagementPort: string;
}

interface CertificationRecord {
  id: string;
  name: string;
  certNo: string;
  issuedBy: string;
  issueDate: string;
  expiry: string;
  type: string;
  status: 'Valid' | 'Expired' | 'Pending';
}

interface HistoryEntry {
  id: string;
  action: string;
  performedBy: string;
  date: string;
  notes: string;
}

interface SeafarerProfile extends Seafarer {
  dob: string;
  nationalId: string;
  passportNo: string;
  bookNumber: string;
  permanentAddress: string;
  training: TrainingRecord[];
  medical: MedicalRecord[];
  seaService: SeaServiceRecord[];
  certifications: CertificationRecord[];
  history: HistoryEntry[];
}

// ---------------------------------------------------------------------------
// Dummy API — replace bodies with real fetch calls
// ---------------------------------------------------------------------------
async function fetchSeafarerProfile(id: string): Promise<SeafarerProfile> {
  await new Promise((r) => setTimeout(r, 800));
  return {
    id,
    seafarerId: 'SF-2024-0001',
    firstName: 'Abebe',
    lastName: 'Girma',
    email: 'abebe.g@email.com',
    gender: 'Male',
    nationality: 'Ethiopian',
    mobile: '+251 911 234 567',
    region: 'Addis Ababa',
    registeredAt: '2024-01-10',
    medicalStatus: 'Fit',
    bookStatus: 'Active',
    status: 'Active',
    dob: '1988-03-15',
    nationalId: 'ET-1234567',
    passportNo: 'EP123456',
    bookNumber: 'SB-2024-0001',
    permanentAddress: 'Bole Sub-City, Woreda 03, House No. 456, Addis Ababa',
    training: [
      { id: '1', course: 'Personal Survival Techniques', institution: 'Ethiopian Maritime Institute', certNo: 'PST-2023-0456', issueDate: '2023-01-10', expiry: '2028-01-14', status: 'Approved' },
      { id: '2', course: 'Fire Prevention and Fire Fighting', institution: 'Djibouti Maritime Academy', certNo: 'FFF-2023-0789', issueDate: '2023-03-05', expiry: '2028-03-07', status: 'Approved' },
      { id: '3', course: 'Elementary First Aid', institution: 'Ethiopian Maritime Institute', certNo: 'EFA-2023-0102', issueDate: '2023-01-10', expiry: '2028-01-10', status: 'Approved' },
    ],
    medical: [
      { id: '1', examType: 'STCW Medical Certificate', issuedBy: 'EMA Medical Center', issueDate: '2023-06-15', expiry: '2025-06-15', result: 'Fit', remarks: 'No medical conditions noted.' },
      { id: '2', examType: 'Pre-Employment Medical', issuedBy: 'Addis Ababa General Hospital', issueDate: '2022-01-10', expiry: '2024-01-10', result: 'Fit', remarks: 'All tests within normal range.' },
    ],
    seaService: [
      { id: '1', vesselName: 'MV Ethiopian Star', vesselType: 'Bulk Carrier', rank: 'Ordinary Seaman', flag: 'Ethiopia', from: '2022-03-01', to: '2023-02-28', engagementPort: 'Djibouti' },
      { id: '2', vesselName: 'MV Red Sea Express', vesselType: 'Container Ship', rank: 'Able Seaman', flag: 'Djibouti', from: '2023-04-01', to: '2024-03-31', engagementPort: 'Berbera' },
    ],
    certifications: [
      { id: '1', name: 'STCW Basic Safety Training', certNo: 'BST-2023-0001', issuedBy: 'Ethiopian Maritime Authority', issueDate: '2023-01-15', expiry: '2028-01-15', type: 'STCW', status: 'Valid' },
      { id: '2', name: 'Certificate of Competency — Deck Rating', certNo: 'COC-2023-0234', issuedBy: 'Ethiopian Maritime Authority', issueDate: '2023-07-01', expiry: '2028-07-01', type: 'COC', status: 'Valid' },
    ],
    history: [
      { id: '1', action: 'Profile Created', performedBy: 'System', date: '2024-01-10', notes: 'Initial registration submitted.' },
      { id: '2', action: 'Status → Active', performedBy: 'Admin Officer', date: '2024-01-15', notes: 'All documents verified and approved.' },
      { id: '3', action: 'Training Record Added', performedBy: 'Abebe Girma', date: '2024-02-20', notes: 'PST certificate uploaded.' },
    ],
  };
}

async function updateSeafarerStatus(_id: string, _status: string): Promise<void> {
  await new Promise((r) => setTimeout(r, 600));
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const STATUS_TONE: Record<string, StatusTone> = {
  Active: 'success', Pending: 'warning', Suspended: 'danger',
  Approved: 'success', Expired: 'danger', Valid: 'success',
  Fit: 'success', Unfit: 'danger', Conditional: 'pending',
};

function Chip({ value }: { value: string }) {
  return <StatusBadge tone={STATUS_TONE[value] ?? 'neutral'} label={value} variant="light" radius="sm" size="sm" />;
}

function InfoField({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <Text fz={10} fw={700} tt="uppercase" c="dimmed" lh={1.2} mb={3}>{label}</Text>
      <Text fz="sm" fw={500}>{value || '—'}</Text>
    </div>
  );
}

function SectionCard({ title, children, action }: { title: string; children: React.ReactNode; action?: React.ReactNode }) {
  return (
    <Paper withBorder radius="md" p="md">
      <Group justify="space-between" mb="sm">
        <Text fw={700} fz="sm">{title}</Text>
        {action}
      </Group>
      <Divider mb="md" />
      {children}
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Tab: Overview
// ---------------------------------------------------------------------------
function OverviewTab({ profile, onStatusChange }: { profile: SeafarerProfile; onStatusChange: (s: 'Active' | 'Suspended') => void }) {
  return (
    <SimpleGrid cols={{ base: 1, md: 2 }} spacing="md">
      <SectionCard title="Personal Information">
        <SimpleGrid cols={3} spacing="md">
          <InfoField label="Seafarer ID" value={profile.seafarerId} />
          <InfoField label="First Name" value={profile.firstName} />
          <InfoField label="Last Name" value={profile.lastName} />
          <InfoField label="Gender" value={profile.gender} />
          <InfoField label="Date of Birth" value={profile.dob} />
          <InfoField label="Nationality" value={profile.nationality} />
          <InfoField label="National ID" value={profile.nationalId} />
          <InfoField label="Passport No." value={profile.passportNo} />
        </SimpleGrid>
      </SectionCard>

      <SectionCard title="Contact & Status">
        <SimpleGrid cols={3} spacing="md" mb="md">
          <InfoField label="Mobile" value={profile.mobile} />
          <InfoField label="Email" value={profile.email} />
          <InfoField label="Region" value={profile.region} />
          <div>
            <Text fz={10} fw={700} tt="uppercase" c="dimmed" lh={1.2} mb={3}>Reg. Status</Text>
            <Chip value={profile.status} />
          </div>
          <div>
            <Text fz={10} fw={700} tt="uppercase" c="dimmed" lh={1.2} mb={3}>Medical Status</Text>
            <Chip value={profile.medicalStatus} />
          </div>
          <InfoField label="Book Number" value={profile.bookNumber} />
          <div>
            <Text fz={10} fw={700} tt="uppercase" c="dimmed" lh={1.2} mb={3}>Book Status</Text>
            <Chip value={profile.bookStatus} />
          </div>
        </SimpleGrid>
        <Divider mb="md" />
        <Group gap="xs">
          {profile.status !== 'Active' && (
            <Button size="xs" color="teal" leftSection={<IconCheck size={13} />} onClick={() => onStatusChange('Active')}>
              Approve
            </Button>
          )}
          {profile.status !== 'Suspended' && (
            <Button size="xs" color="red" variant="light" leftSection={<IconX size={13} />} onClick={() => onStatusChange('Suspended')}>
              Suspend
            </Button>
          )}
          <Button size="xs" variant="default" leftSection={<IconFileText size={13} />} onClick={() => notify.info('Documents — coming soon.')}>
            Documents
          </Button>
        </Group>
      </SectionCard>

      <Paper withBorder radius="md" p="md">
        <Text fw={700} fz="sm" mb="xs">Permanent Address</Text>
        <Text fz="sm" c="dimmed">{profile.permanentAddress || '—'}</Text>
      </Paper>
    </SimpleGrid>
  );
}

// ---------------------------------------------------------------------------
// Tab: Training
// ---------------------------------------------------------------------------
function TrainingTab({ records, onAdd }: { records: TrainingRecord[]; onAdd: () => void }) {
  return (
    <Paper withBorder radius="md">
      <Group justify="space-between" p="md">
        <Text fw={700} fz="sm">Training Records</Text>
        <Button size="xs" leftSection={<IconPlus size={13} />} onClick={onAdd}>+ Add Training</Button>
      </Group>
      <Divider />
      <Table highlightOnHover verticalSpacing="sm" fz="sm">
        <Table.Thead bg="var(--mantine-color-default-hover)">
          <Table.Tr>
            {['Course', 'Institution', 'Cert. No.', 'Issue Date', 'Expiry', 'Status', 'Actions'].map((h) => (
              <Table.Th key={h} style={{ fontSize: rem(11), textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--mantine-color-dimmed)' }}>{h}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {records.map((r) => (
            <Table.Tr key={r.id}>
              <Table.Td><Text fw={500} fz="sm">{r.course}</Text></Table.Td>
              <Table.Td>{r.institution}</Table.Td>
              <Table.Td><Text fz="sm" c="dimmed">{r.certNo}</Text></Table.Td>
              <Table.Td>{r.issueDate}</Table.Td>
              <Table.Td>{r.expiry}</Table.Td>
              <Table.Td><Chip value={r.status} /></Table.Td>
              <Table.Td>
                <Button size="xs" variant="subtle" onClick={() => notify.info('View training — coming soon.')}>View</Button>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
      {records.length === 0 && <Text ta="center" c="dimmed" fz="sm" py="xl">No training records found.</Text>}
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Tab: Medical
// ---------------------------------------------------------------------------
function MedicalTab({ records, onAdd }: { records: MedicalRecord[]; onAdd: () => void }) {
  return (
    <Paper withBorder radius="md">
      <Group justify="space-between" p="md">
        <Text fw={700} fz="sm">Medical Records</Text>
        <Button size="xs" leftSection={<IconPlus size={13} />} onClick={onAdd}>+ Add Record</Button>
      </Group>
      <Divider />
      <Table highlightOnHover verticalSpacing="sm" fz="sm">
        <Table.Thead bg="var(--mantine-color-default-hover)">
          <Table.Tr>
            {['Exam Type', 'Issued By', 'Issue Date', 'Expiry', 'Result', 'Remarks', 'Actions'].map((h) => (
              <Table.Th key={h} style={{ fontSize: rem(11), textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--mantine-color-dimmed)' }}>{h}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {records.map((r) => (
            <Table.Tr key={r.id}>
              <Table.Td><Text fw={500} fz="sm">{r.examType}</Text></Table.Td>
              <Table.Td>{r.issuedBy}</Table.Td>
              <Table.Td>{r.issueDate}</Table.Td>
              <Table.Td>{r.expiry}</Table.Td>
              <Table.Td><Chip value={r.result} /></Table.Td>
              <Table.Td><Text fz="xs" c="dimmed" style={{ maxWidth: rem(180) }} lineClamp={1}>{r.remarks}</Text></Table.Td>
              <Table.Td>
                <Button size="xs" variant="subtle" onClick={() => notify.info('View medical record — coming soon.')}>View</Button>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
      {records.length === 0 && <Text ta="center" c="dimmed" fz="sm" py="xl">No medical records found.</Text>}
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Tab: Sea Service
// ---------------------------------------------------------------------------
function SeaServiceTab({ records, onAdd }: { records: SeaServiceRecord[]; onAdd: () => void }) {
  return (
    <Paper withBorder radius="md">
      <Group justify="space-between" p="md">
        <Text fw={700} fz="sm">Sea Service Records</Text>
        <Button size="xs" leftSection={<IconPlus size={13} />} onClick={onAdd}>+ Add Service</Button>
      </Group>
      <Divider />
      <Table highlightOnHover verticalSpacing="sm" fz="sm">
        <Table.Thead bg="var(--mantine-color-default-hover)">
          <Table.Tr>
            {['Vessel Name', 'Type', 'Rank', 'Flag', 'From', 'To', 'Engagement Port', 'Actions'].map((h) => (
              <Table.Th key={h} style={{ fontSize: rem(11), textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--mantine-color-dimmed)' }}>{h}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {records.map((r) => (
            <Table.Tr key={r.id}>
              <Table.Td><Text fw={500} fz="sm">{r.vesselName}</Text></Table.Td>
              <Table.Td>{r.vesselType}</Table.Td>
              <Table.Td>{r.rank}</Table.Td>
              <Table.Td>{r.flag}</Table.Td>
              <Table.Td>{r.from}</Table.Td>
              <Table.Td>{r.to}</Table.Td>
              <Table.Td>{r.engagementPort}</Table.Td>
              <Table.Td>
                <Button size="xs" variant="subtle" onClick={() => notify.info('View sea service — coming soon.')}>View</Button>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
      {records.length === 0 && <Text ta="center" c="dimmed" fz="sm" py="xl">No sea service records found.</Text>}
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Tab: Certifications
// ---------------------------------------------------------------------------
function CertificationsTab({ records, onAdd }: { records: CertificationRecord[]; onAdd: () => void }) {
  return (
    <Paper withBorder radius="md">
      <Group justify="space-between" p="md">
        <Text fw={700} fz="sm">Certifications</Text>
        <Button size="xs" leftSection={<IconPlus size={13} />} onClick={onAdd}>+ Add Certification</Button>
      </Group>
      <Divider />
      <Table highlightOnHover verticalSpacing="sm" fz="sm">
        <Table.Thead bg="var(--mantine-color-default-hover)">
          <Table.Tr>
            {['Certificate', 'Cert. No.', 'Type', 'Issued By', 'Issue Date', 'Expiry', 'Status', 'Actions'].map((h) => (
              <Table.Th key={h} style={{ fontSize: rem(11), textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--mantine-color-dimmed)' }}>{h}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {records.map((r) => (
            <Table.Tr key={r.id}>
              <Table.Td><Text fw={500} fz="sm">{r.name}</Text></Table.Td>
              <Table.Td><Text fz="sm" c="dimmed">{r.certNo}</Text></Table.Td>
              <Table.Td><Badge variant="outline" size="xs" radius="sm">{r.type}</Badge></Table.Td>
              <Table.Td>{r.issuedBy}</Table.Td>
              <Table.Td>{r.issueDate}</Table.Td>
              <Table.Td>{r.expiry}</Table.Td>
              <Table.Td><Chip value={r.status} /></Table.Td>
              <Table.Td>
                <Button size="xs" variant="subtle" onClick={() => notify.info('View certificate — coming soon.')}>View</Button>
              </Table.Td>
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
      {records.length === 0 && <Text ta="center" c="dimmed" fz="sm" py="xl">No certifications found.</Text>}
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Tab: History
// ---------------------------------------------------------------------------
function HistoryTab({ entries }: { entries: HistoryEntry[] }) {
  return (
    <Paper withBorder radius="md" p="md">
      <Text fw={700} fz="sm" mb="md">Activity History</Text>
      <Divider mb="md" />
      <Stack gap="sm">
        {entries.map((e) => (
          <Group key={e.id} gap="md" wrap="nowrap" align="flex-start">
            <ThemeIcon variant="light" color="blue" size={32} radius="xl" style={{ flexShrink: 0, marginTop: 2 }}>
              <IconClock size={15} />
            </ThemeIcon>
            <div style={{ flex: 1 }}>
              <Group gap="xs" align="center">
                <Text fz="sm" fw={600}>{e.action}</Text>
                <Text fz="xs" c="dimmed">by {e.performedBy}</Text>
              </Group>
              <Text fz="xs" c="dimmed">{e.date}</Text>
              {e.notes && <Text fz="xs" mt={2}>{e.notes}</Text>}
            </div>
          </Group>
        ))}
        {entries.length === 0 && <Text ta="center" c="dimmed" fz="sm" py="xl">No history found.</Text>}
      </Stack>
    </Paper>
  );
}

// ---------------------------------------------------------------------------
// Add Record Modal (generic)
// ---------------------------------------------------------------------------
function AddTrainingModal({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  return (
    <Modal opened={opened} onClose={onClose} title="Add Training Record" size="lg">
      <Stack gap="sm">
        <TextInput label="Course Name" placeholder="e.g. Personal Survival Techniques" required />
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Institution" placeholder="Training institution" />
          <TextInput label="Certificate No." placeholder="CERT-0000" />
        </SimpleGrid>
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Issue Date" type="date" />
          <TextInput label="Expiry Date" type="date" />
        </SimpleGrid>
        <Select label="Status" data={['Approved', 'Pending', 'Expired']} defaultValue="Pending" />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose}>Cancel</Button>
          <Button onClick={() => { notify.success('Training record added (demo).'); onClose(); }}>Save</Button>
        </Group>
      </Stack>
    </Modal>
  );
}

function AddMedicalModal({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  return (
    <Modal opened={opened} onClose={onClose} title="Add Medical Record" size="lg">
      <Stack gap="sm">
        <TextInput label="Exam Type" placeholder="e.g. STCW Medical Certificate" required />
        <TextInput label="Issued By" placeholder="Issuing authority" />
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Issue Date" type="date" />
          <TextInput label="Expiry Date" type="date" />
        </SimpleGrid>
        <Select label="Result" data={['Fit', 'Unfit', 'Conditional']} defaultValue="Fit" />
        <Textarea label="Remarks" placeholder="Any notes" autosize minRows={2} />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose}>Cancel</Button>
          <Button onClick={() => { notify.success('Medical record added (demo).'); onClose(); }}>Save</Button>
        </Group>
      </Stack>
    </Modal>
  );
}

function AddSeaServiceModal({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  return (
    <Modal opened={opened} onClose={onClose} title="Add Sea Service Record" size="lg">
      <Stack gap="sm">
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Vessel Name" placeholder="MV Name" required />
          <TextInput label="Vessel Type" placeholder="e.g. Bulk Carrier" />
        </SimpleGrid>
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Rank" placeholder="e.g. Able Seaman" />
          <TextInput label="Flag" placeholder="Country" />
        </SimpleGrid>
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="From" type="date" />
          <TextInput label="To" type="date" />
        </SimpleGrid>
        <TextInput label="Engagement Port" placeholder="Port name" />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose}>Cancel</Button>
          <Button onClick={() => { notify.success('Sea service record added (demo).'); onClose(); }}>Save</Button>
        </Group>
      </Stack>
    </Modal>
  );
}

function AddCertModal({ opened, onClose }: { opened: boolean; onClose: () => void }) {
  return (
    <Modal opened={opened} onClose={onClose} title="Add Certification" size="lg">
      <Stack gap="sm">
        <TextInput label="Certificate Name" placeholder="e.g. STCW Basic Safety Training" required />
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Certificate No." placeholder="CERT-0000" />
          <Select label="Type" data={['STCW', 'COC', 'COE', 'GMDSS', 'Other']} placeholder="Select type" />
        </SimpleGrid>
        <TextInput label="Issued By" placeholder="Issuing authority" />
        <SimpleGrid cols={2} spacing="sm">
          <TextInput label="Issue Date" type="date" />
          <TextInput label="Expiry Date" type="date" />
        </SimpleGrid>
        <Select label="Status" data={['Valid', 'Expired', 'Pending']} defaultValue="Valid" />
        <Group justify="flex-end" mt="sm">
          <Button variant="default" onClick={onClose}>Cancel</Button>
          <Button onClick={() => { notify.success('Certification added (demo).'); onClose(); }}>Save</Button>
        </Group>
      </Stack>
    </Modal>
  );
}

// ---------------------------------------------------------------------------
// Main page
// ---------------------------------------------------------------------------
export function SeafarerProfilePage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [profile, setProfile] = useState<SeafarerProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<string | null>('overview');

  const [trainingModal, trainingModalHandlers] = useDisclosure(false);
  const [medicalModal, medicalModalHandlers] = useDisclosure(false);
  const [seaServiceModal, seaServiceModalHandlers] = useDisclosure(false);
  const [certModal, certModalHandlers] = useDisclosure(false);

  useEffect(() => {
    if (!id) return;
    fetchSeafarerProfile(id)
      .then(setProfile)
      .catch(() => notify.error('Failed to load seafarer profile.'))
      .finally(() => setLoading(false));
  }, [id]);

  const handleStatusChange = async (newStatus: 'Active' | 'Suspended') => {
    if (!profile) return;
    try {
      await updateSeafarerStatus(profile.id, newStatus);
      setProfile((p) => p ? { ...p, status: newStatus } : p);
      notify.success(`Status updated to ${newStatus}.`);
    } catch {
      notify.error('Failed to update status.');
    }
  };

  const initials = profile ? `${profile.firstName[0]}${profile.lastName[0]}` : '??';

  return (
    <Stack gap="md">
      {/* Breadcrumb */}
      <Group gap="xs" align="center">
        <ActionIcon variant="subtle" size="sm" onClick={() => navigate('/seafarer-registry')}>
          <IconArrowLeft size={16} />
        </ActionIcon>
        <Text fz="sm" c="dimmed" style={{ cursor: 'pointer' }} onClick={() => navigate('/seafarer-registry')}>
          Seafarer Registry
        </Text>
        <Text fz="sm" c="dimmed">/</Text>
        <Text fz="sm" fw={500}>
          {loading ? <Skeleton width={100} height={14} /> : `${profile?.firstName} ${profile?.lastName}`}
        </Text>
      </Group>

      {/* Profile header card */}
      <Paper withBorder radius="md" p="lg">
        {loading ? (
          <Group gap="md">
            <Skeleton circle height={64} />
            <Stack gap={6} style={{ flex: 1 }}>
              <Skeleton height={20} width={200} />
              <Skeleton height={14} width={300} />
              <Skeleton height={14} width={400} />
            </Stack>
          </Group>
        ) : profile ? (
          <Group justify="space-between" wrap="nowrap" align="flex-start">
            <Group gap="lg" wrap="nowrap" align="flex-start">
              <Avatar size={64} radius="xl" color="blue" style={{ fontSize: rem(22) }}>
                {initials}
              </Avatar>
              <div>
                <Title order={3} lh={1.2}>{profile.firstName} {profile.lastName}</Title>
                <Text fz="sm" c="dimmed" mt={2}>
                  {profile.seafarerId} · Registered {profile.registeredAt}
                </Text>
                <Group gap="lg" mt={6} wrap="wrap">
                  <Text fz="sm"><Text span fw={600}>Gender:</Text> {profile.gender}</Text>
                  <Text fz="sm"><Text span fw={600}>DOB:</Text> {profile.dob}</Text>
                  <Text fz="sm"><Text span fw={600}>Nationality:</Text> {profile.nationality}</Text>
                  <Text fz="sm"><Text span fw={600}>Mobile:</Text> {profile.mobile}</Text>
                  <Text fz="sm"><Text span fw={600}>Email:</Text> {profile.email}</Text>
                </Group>
              </div>
            </Group>
            <Stack gap="xs" align="flex-end" style={{ flexShrink: 0 }}>
              <StatusBadge
                tone={STATUS_TONE[profile.status] ?? 'neutral'}
                label={profile.status}
                variant="filled"
                radius="sm"
              />
              <Button size="xs" variant="default" leftSection={<IconEdit size={13} />} onClick={() => notify.info('Edit profile — coming soon.')}>
                Edit Profile
              </Button>
              <Button size="xs" variant="default" leftSection={<IconPrinter size={13} />} onClick={() => notify.info('Print — coming soon.')}>
                Print Profile
              </Button>
            </Stack>
          </Group>
        ) : (
          <Alert color="red">Profile not found.</Alert>
        )}
      </Paper>

      {/* Tabs */}
      {!loading && profile && (
        <Tabs value={activeTab} onChange={setActiveTab} variant="outline">
          <Tabs.List mb="md">
            <Tabs.Tab value="overview"       leftSection={<IconLayoutDashboard size={15} />}>Overview</Tabs.Tab>
            <Tabs.Tab value="training"       leftSection={<IconBook size={15} />}>Training</Tabs.Tab>
            <Tabs.Tab value="medical"        leftSection={<IconHeartbeat size={15} />}>Medical</Tabs.Tab>
            <Tabs.Tab value="sea-service"    leftSection={<IconShip size={15} />}>Sea Service</Tabs.Tab>
            <Tabs.Tab value="certifications" leftSection={<IconCertificate size={15} />}>Certifications</Tabs.Tab>
            <Tabs.Tab value="history"        leftSection={<IconHistory size={15} />}>History</Tabs.Tab>
          </Tabs.List>

          <Tabs.Panel value="overview">
            <OverviewTab profile={profile} onStatusChange={handleStatusChange} />
          </Tabs.Panel>

          <Tabs.Panel value="training">
            <TrainingTab records={profile.training} onAdd={trainingModalHandlers.open} />
          </Tabs.Panel>

          <Tabs.Panel value="medical">
            <MedicalTab records={profile.medical} onAdd={medicalModalHandlers.open} />
          </Tabs.Panel>

          <Tabs.Panel value="sea-service">
            <SeaServiceTab records={profile.seaService} onAdd={seaServiceModalHandlers.open} />
          </Tabs.Panel>

          <Tabs.Panel value="certifications">
            <CertificationsTab records={profile.certifications} onAdd={certModalHandlers.open} />
          </Tabs.Panel>

          <Tabs.Panel value="history">
            <HistoryTab entries={profile.history} />
          </Tabs.Panel>
        </Tabs>
      )}

      {/* Modals */}
      <AddTrainingModal  opened={trainingModal}   onClose={trainingModalHandlers.close} />
      <AddMedicalModal   opened={medicalModal}    onClose={medicalModalHandlers.close} />
      <AddSeaServiceModal opened={seaServiceModal} onClose={seaServiceModalHandlers.close} />
      <AddCertModal      opened={certModal}       onClose={certModalHandlers.close} />
    </Stack>
  );
}
