'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'
import { toast } from 'sonner'
import { formatCurrency, fmtDate, cn } from '@/lib/utils'
import { Users, Plus, Edit2, UserX, UserCheck, Trash2, Search, Eye } from 'lucide-react'
import {
  StatCard, Card, CardHeader, CardTitle, CardContent, Badge,
  Button, Modal, Input, Select, Textarea, PageHeader,
  Pagination, Amount, Alert, InfoRow, InfoGrid, FormGrid,
} from '@/components/ui/components'

// ── Status badge helper ───────────────────────────────────────────────────────
const statusVariant = (isActive: boolean) => isActive ? 'success' : 'danger'
const statusLabel   = (isActive: boolean) => isActive ? 'Active' : 'Inactive'

const EMPLOYMENT_TYPES = ['PERMANENT', 'CONTRACT', 'CASUAL', 'SELF_EMPLOYED']
const GENDERS          = ['MALE', 'FEMALE', 'OTHER']
const PAYMENT_METHODS  = ['BANK', 'MPESA', 'CASH', 'CHEQUE']

// ── Blank form ────────────────────────────────────────────────────────────────
const blankForm = {
  fullName: '', phone: '', email: '', nationalId: '', dateOfBirth: '',
  gender: '', designation: '', department: '', grade: '',
  employmentType: 'PERMANENT', hireDate: new Date().toISOString().slice(0, 10),
  contractEndDate: '', basicSalary: '',
  houseAllowance: '', transportAllowance: '', medicalAllowance: '',
  bankName: '', bankBranch: '', accountNumber: '', accountName: '',
  paymentMethod: 'BANK', kraPin: '', nssfNo: '', nhifNo: '', notes: '',
}

export default function StaffPage() {
  const qc = useQueryClient()

  // ── State ─────────────────────────────────────────────────────────────────
  const [page,   setPage]   = useState(1)
  const [search, setSearch] = useState('')
  const [status, setStatus] = useState('')    // '' | 'active' | 'inactive'

  const [createModal,     setCreateModal]     = useState(false)
  const [editModal,       setEditModal]       = useState(false)
  const [deactivateModal, setDeactivateModal] = useState(false)
  const [viewModal,       setViewModal]       = useState(false)
  const [deleteModal,     setDeleteModal]     = useState(false)

  const [selected,          setSelected]          = useState<any>(null)
  const [form,              setForm]              = useState({ ...blankForm })
  const [terminationReason, setTerminationReason] = useState('')

  // ── Queries ───────────────────────────────────────────────────────────────
  const { data, isLoading } = useQuery({
    queryKey: ['staff', page, search, status],
    queryFn:  () => axios.get(`/api/staff?page=${page}&pageSize=20&search=${encodeURIComponent(search)}&status=${status}`).then(r => r.data),
    placeholderData: (prev: unknown) => prev,
  })

  const { data: detailData } = useQuery({
    queryKey: ['staff-detail', selected?.id],
    queryFn:  () => axios.get(`/api/staff/${selected.id}`).then(r => r.data.data),
    enabled:  !!selected?.id && viewModal,
  })

  // ── Mutations ─────────────────────────────────────────────────────────────
  const createMutation = useMutation({
    mutationFn: (p: any) => axios.post('/api/staff', p),
    onSuccess: () => {
      toast.success('Staff member created')
      qc.invalidateQueries({ queryKey: ['staff'] })
      setCreateModal(false)
      setForm({ ...blankForm })
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to create staff'),
  })

  const editMutation = useMutation({
    mutationFn: ({ id, ...p }: any) => axios.patch(`/api/staff/${id}`, p),
    onSuccess: () => {
      toast.success('Staff updated successfully')
      qc.invalidateQueries({ queryKey: ['staff'] })
      qc.invalidateQueries({ queryKey: ['staff-detail'] })
      setEditModal(false)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to update staff'),
  })

  const actionMutation = useMutation({
    mutationFn: ({ id, ...p }: any) => axios.patch(`/api/staff/${id}`, p),
    onSuccess: (_, vars) => {
      const labels: Record<string, string> = {
        DEACTIVATE: 'Staff deactivated',
        ACTIVATE:   'Staff reactivated',
      }
      toast.success(labels[vars.action] ?? 'Updated')
      qc.invalidateQueries({ queryKey: ['staff'] })
      qc.invalidateQueries({ queryKey: ['staff-detail'] })
      setDeactivateModal(false)
      setTerminationReason('')
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Action failed'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => axios.delete(`/api/staff/${id}`),
    onSuccess: () => {
      toast.success('Staff member removed')
      qc.invalidateQueries({ queryKey: ['staff'] })
      setDeleteModal(false)
      setSelected(null)
    },
    onError: (e: any) => toast.error(e.response?.data?.error ?? 'Failed to remove staff'),
  })

  // ── Helpers ───────────────────────────────────────────────────────────────
  function openEdit(s: any) {
    setSelected(s)
    setForm({
      fullName:       s.fullName         ?? '',
      phone:          s.phone            ?? '',
      email:          s.email            ?? '',
      nationalId:     s.nationalId       ?? '',
      dateOfBirth:    s.dateOfBirth      ? s.dateOfBirth.slice(0, 10) : '',
      gender:         s.gender           ?? '',
      designation:    s.designation      ?? '',
      department:     s.department       ?? '',
      grade:          s.grade            ?? '',
      employmentType: s.employmentType   ?? 'PERMANENT',
      hireDate:       s.hireDate         ? s.hireDate.slice(0, 10) : '',
      contractEndDate:s.contractEndDate  ? s.contractEndDate.slice(0, 10) : '',
      basicSalary:    s.basicSalary      ? String(parseFloat(s.basicSalary)) : '',
      houseAllowance:      s.houseAllowance      ? String(parseFloat(s.houseAllowance)) : '',
      transportAllowance:  s.transportAllowance  ? String(parseFloat(s.transportAllowance)) : '',
      medicalAllowance:    s.medicalAllowance    ? String(parseFloat(s.medicalAllowance)) : '',
      bankName:       s.bankName         ?? '',
      bankBranch:     s.bankBranch       ?? '',
      accountNumber:  s.accountNumber    ?? '',
      accountName:    s.accountName      ?? '',
      paymentMethod:  s.paymentMethod    ?? 'BANK',
      kraPin:         s.kraPin           ?? '',
      nssfNo:         s.nssfNo           ?? '',
      nhifNo:         s.nhifNo           ?? '',
      notes:          s.notes            ?? '',
    })
    setEditModal(true)
  }

  const staff    = data?.data    ?? []
  const total    = data?.total   ?? 0
  const summary  = data?.summary ?? {}

  return (
    <div className="p-6 space-y-5 max-w-screen-xl mx-auto">

      <PageHeader
        title="Staff"
        description="Manage staff records, salaries and employment status"
        icon={<Users className="w-6 h-6" />}
        actions={
          <Button size="sm" icon={<Plus className="w-4 h-4" />} onClick={() => { setForm({ ...blankForm }); setCreateModal(true) }}>
            Add Staff
          </Button>
        }
      />

      {/* ── Summary cards ── */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        <StatCard
          label="Total Staff"
          value={(summary.totalStaff   ?? 0).toLocaleString()}
          icon={<Users className="w-5 h-5" />}
          color="blue"
        />
        <StatCard
          label="Active"
          value={(summary.activeStaff  ?? 0).toLocaleString()}
          icon={<UserCheck className="w-5 h-5" />}
          color="green"
        />
        <StatCard
          label="Inactive"
          value={(summary.inactiveStaff ?? 0).toLocaleString()}
          icon={<UserX className="w-5 h-5" />}
          color="red"
        />
        <StatCard
          label="Monthly Payroll Obligation"
          value={formatCurrency(summary.totalBasicPayroll)}
          icon={<Users className="w-5 h-5" />}
          color="amber"
        />
      </div>

      {/* ── Staff table ── */}
      <Card>
        <CardHeader>
          <CardTitle>Staff Register</CardTitle>
          {/* Search + filter bar */}
          <div className="flex items-center gap-2 flex-wrap">
            <div className="relative">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground" />
              <input
                className="pl-8 pr-3 py-1.5 text-sm border rounded-md w-52 bg-background"
                placeholder="Search name, staff no…"
                value={search}
                onChange={e => { setSearch(e.target.value); setPage(1) }}
              />
            </div>
            <select
              className="text-sm border rounded-md px-2 py-1.5 bg-background"
              value={status}
              onChange={e => { setStatus(e.target.value); setPage(1) }}>
              <option value="">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
        </CardHeader>

        <div className="overflow-x-auto">
          <table className="table-lms w-full">
            <thead>
              <tr>
                <th>Staff No</th>
                <th>Name</th>
                <th>Designation / Dept</th>
                <th>Employment Type</th>
                <th>Basic Salary</th>
                <th>Hire Date</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {isLoading
                ? Array.from({ length: 8 }).map((_, i) => (
                    <tr key={i}>
                      {Array.from({ length: 8 }).map((_, j) => (
                        <td key={j}><div className="h-4 bg-muted rounded animate-pulse" /></td>
                      ))}
                    </tr>
                  ))
                : staff.length === 0
                  ? <tr><td colSpan={8} className="text-center py-10 text-muted-foreground">No staff found</td></tr>
                  : staff.map((s: any) => (
                    <tr key={s.id} className={!s.isActive ? 'opacity-60' : ''}>
                      <td className="font-mono text-xs">{s.staffNo}</td>
                      <td>
                        <p className="font-medium text-sm">{s.fullName}</p>
                        <p className="text-xs text-muted-foreground">{s.phone}</p>
                      </td>
                      <td>
                        <p className="text-sm">{s.designation ?? '—'}</p>
                        <p className="text-xs text-muted-foreground">{s.department ?? '—'}</p>
                      </td>
                      <td>
                        <Badge variant="default">{s.employmentType?.replace(/_/g, ' ')}</Badge>
                      </td>
                      <td className="font-semibold"><Amount value={s.basicSalary} size="sm" /></td>
                      <td className="text-xs text-muted-foreground">{fmtDate(s.hireDate)}</td>
                      <td>
                        <Badge variant={statusVariant(s.isActive)}>{statusLabel(s.isActive)}</Badge>
                      </td>
                      <td>
                        <div className="flex items-center gap-1">
                          <Button size="xs" variant="ghost" icon={<Eye className="w-3 h-3" />}
                            onClick={() => { setSelected(s); setViewModal(true) }}>
                            View
                          </Button>
                          <Button size="xs" variant="ghost" icon={<Edit2 className="w-3 h-3" />}
                            onClick={() => openEdit(s)}>
                            Edit
                          </Button>
                          {s.isActive ? (
                            <Button size="xs" variant="ghost" icon={<UserX className="w-3 h-3" />}
                              className="text-red-600 hover:text-red-700"
                              onClick={() => { setSelected(s); setTerminationReason(''); setDeactivateModal(true) }}>
                              Deactivate
                            </Button>
                          ) : (
                            <Button size="xs" variant="ghost" icon={<UserCheck className="w-3 h-3" />}
                              className="text-green-600 hover:text-green-700"
                              onClick={() => actionMutation.mutate({ id: s.id, action: 'ACTIVATE' })}>
                              Activate
                            </Button>
                          )}
                          <Button size="xs" variant="ghost" icon={<Trash2 className="w-3 h-3" />}
                            className="text-red-500 hover:text-red-600"
                            onClick={() => { setSelected(s); setDeleteModal(true) }}>
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))
              }
            </tbody>
          </table>
        </div>
        <Pagination page={page} pages={Math.ceil(total / 20)} total={total} pageSize={20} onPage={setPage} />
      </Card>

      {/* ══════════════════════════════════════════════════════════════════════
          MODALS
      ══════════════════════════════════════════════════════════════════════ */}

      {/* ── Create Staff Modal ── */}
      <Modal
        open={createModal}
        onClose={() => setCreateModal(false)}
        size="2xl"
        title="Add New Staff Member"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setCreateModal(false)}>Cancel</Button>
            <Button size="sm" loading={createMutation.isPending}
              onClick={() => createMutation.mutate({
                ...form,
                basicSalary: parseFloat(form.basicSalary || '0'),
                houseAllowance:      parseFloat(form.houseAllowance || '0') || undefined,
                transportAllowance:  parseFloat(form.transportAllowance || '0') || undefined,
                medicalAllowance:    parseFloat(form.medicalAllowance || '0') || undefined,
                email:       form.email       || undefined,
                gender:      form.gender      || undefined,
                dateOfBirth: form.dateOfBirth || undefined,
                contractEndDate: form.contractEndDate || undefined,
              })}>
              Create Staff
            </Button>
          </>
        }
      >
        <StaffForm form={form} setForm={setForm} />
      </Modal>

      {/* ── Edit Staff Modal ── */}
      <Modal
        open={editModal}
        onClose={() => setEditModal(false)}
        size="2xl"
        title={`Edit Staff — ${selected?.fullName}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setEditModal(false)}>Cancel</Button>
            <Button size="sm" loading={editMutation.isPending}
              onClick={() => editMutation.mutate({
                id:  selected?.id,
                ...form,
                basicSalary: parseFloat(form.basicSalary || '0'),
                houseAllowance:      parseFloat(form.houseAllowance || '0') || undefined,
                transportAllowance:  parseFloat(form.transportAllowance || '0') || undefined,
                medicalAllowance:    parseFloat(form.medicalAllowance || '0') || undefined,
                email:       form.email       || undefined,
                gender:      form.gender      || undefined,
                dateOfBirth: form.dateOfBirth || undefined,
                contractEndDate: form.contractEndDate || undefined,
              })}>
              Save Changes
            </Button>
          </>
        }
      >
        <StaffForm form={form} setForm={setForm} isEdit />
      </Modal>

      {/* ── Deactivate Modal ── */}
      <Modal
        open={deactivateModal}
        onClose={() => setDeactivateModal(false)}
        title={`Deactivate — ${selected?.fullName}`}
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setDeactivateModal(false)}>Cancel</Button>
            <Button variant="destructive" size="sm" loading={actionMutation.isPending}
              onClick={() => actionMutation.mutate({
                id:                selected?.id,
                action:            'DEACTIVATE',
                terminationReason: terminationReason || undefined,
              })}>
              Deactivate Staff
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Alert variant="warning">
            <strong>{selected?.fullName}</strong> will be marked as inactive.
            Any active payroll runs will no longer include this staff member.
          </Alert>
          <div>
            <label className="text-sm font-medium">Termination / Reason <span className="text-muted-foreground">(optional)</span></label>
            <textarea
              rows={3}
              className="mt-1 w-full border rounded-md px-3 py-2 text-sm resize-none"
              placeholder="State reason for deactivation…"
              value={terminationReason}
              onChange={e => setTerminationReason(e.target.value)}
            />
          </div>
        </div>
      </Modal>

      {/* ── Delete Modal ── */}
      <Modal
        open={deleteModal}
        onClose={() => setDeleteModal(false)}
        title="Remove Staff Member"
        footer={
          <>
            <Button variant="outline" size="sm" onClick={() => setDeleteModal(false)}>Cancel</Button>
            <Button variant="destructive" size="sm" loading={deleteMutation.isPending}
              onClick={() => deleteMutation.mutate(selected?.id)}>
              Yes, Remove
            </Button>
          </>
        }
      >
        <Alert variant="error">
          Permanently remove <strong>{selected?.fullName}</strong> ({selected?.staffNo}) from the system?
          This cannot be undone. Staff with active cash advances cannot be removed.
        </Alert>
      </Modal>

      {/* ── View Staff Detail Modal ── */}
      <Modal
        open={viewModal}
        onClose={() => setViewModal(false)}
        size="2xl"
        title={`${selected?.fullName} — ${selected?.staffNo}`}
      >
        {!detailData ? (
          <div className="py-10 text-center text-muted-foreground">Loading…</div>
        ) : (
          <div className="space-y-5 text-sm">
            {/* Status */}
            <div className="flex items-center gap-3">
              <Badge variant={statusVariant(detailData.isActive)}>{statusLabel(detailData.isActive)}</Badge>
              <Badge variant="default">{detailData.employmentType?.replace(/_/g, ' ')}</Badge>
              {detailData.department && <Badge variant="default">{detailData.department}</Badge>}
            </div>

            {/* Personal */}
            <div>
              <p className="font-semibold mb-2">Personal Details</p>
              <InfoGrid cols={2}>
                <InfoRow label="Full Name"      value={detailData.fullName} />
                <InfoRow label="Staff No"       value={detailData.staffNo} />
                <InfoRow label="National ID"    value={detailData.nationalId} />
                <InfoRow label="Phone"          value={detailData.phone} />
                <InfoRow label="Email"          value={detailData.email} />
                <InfoRow label="Gender"         value={detailData.gender} />
                <InfoRow label="Date of Birth"  value={fmtDate(detailData.dateOfBirth)} />
                <InfoRow label="KRA PIN"        value={detailData.kraPin} />
              </InfoGrid>
            </div>

            {/* Employment */}
            <div className="pt-4 border-t">
              <p className="font-semibold mb-2">Employment</p>
              <InfoGrid cols={2}>
                <InfoRow label="Designation"    value={detailData.designation} />
                <InfoRow label="Department"     value={detailData.department} />
                <InfoRow label="Grade"          value={detailData.grade} />
                <InfoRow label="Hire Date"      value={fmtDate(detailData.hireDate)} />
                <InfoRow label="Contract End"   value={fmtDate(detailData.contractEndDate)} />
                <InfoRow label="Basic Salary"   value={formatCurrency(detailData.basicSalary)} />
              </InfoGrid>
            </div>

            {/* Bank */}
            <div className="pt-4 border-t">
              <p className="font-semibold mb-2">Bank Details</p>
              <InfoGrid cols={2}>
                <InfoRow label="Bank"           value={detailData.bankName} />
                <InfoRow label="Branch"         value={detailData.bankBranch} />
                <InfoRow label="Account No"     value={detailData.accountNumber} />
                <InfoRow label="Account Name"   value={detailData.accountName} />
                <InfoRow label="Payment Method" value={detailData.paymentMethod} />
              </InfoGrid>
            </div>

            {/* Advances */}
            {detailData.cashAdvances?.length > 0 && (
              <div className="pt-4 border-t">
                <p className="font-semibold mb-2">Cash Advances</p>
                <table className="table-lms w-full text-xs">
                  <thead>
                    <tr><th>Ref</th><th>Amount</th><th>Outstanding</th><th>Status</th></tr>
                  </thead>
                  <tbody>
                    {detailData.cashAdvances.map((a: any) => (
                      <tr key={a.id}>
                        <td className="font-mono">{a.advanceRef}</td>
                        <td><Amount value={a.amount} size="sm" /></td>
                        <td className="text-amber-600"><Amount value={a.outstandingBalance} size="sm" /></td>
                        <td><Badge variant="default">{a.status}</Badge></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* Recent payslips */}
            {detailData.payrollItems?.length > 0 && (
              <div className="pt-4 border-t">
                <p className="font-semibold mb-2">Recent Payroll</p>
                <table className="table-lms w-full text-xs">
                  <thead>
                    <tr><th>Period</th><th>Gross</th><th>Deductions</th><th>Net Pay</th></tr>
                  </thead>
                  <tbody>
                    {detailData.payrollItems.map((p: any) => (
                      <tr key={p.id}>
                        <td>{p.payrollRun?.period}</td>
                        <td><Amount value={p.grossPay}      size="sm" /></td>
                        <td><Amount value={p.totalDeductions}size="sm" /></td>
                        <td className="font-bold text-green-600"><Amount value={p.netPay} size="sm" /></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  )
}

// ── Staff form — reused by create + edit modals ───────────────────────────────
function StaffForm({
  form, setForm, isEdit = false,
}: {
  form: any
  setForm: React.Dispatch<React.SetStateAction<any>>
  isEdit?: boolean
}) {
  const f = (field: string, value: string) =>
    setForm((p: any) => ({ ...p, [field]: value }))

  return (
    <div className="space-y-5 max-h-[65vh] overflow-y-auto pr-1">

      {/* Personal */}
      <div>
        <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Personal Details</p>
        <FormGrid cols={2}>
          <Input label="Full Name" required value={form.fullName}     onChange={e => f('fullName',    e.target.value)} />
          <Input label="Phone"     required value={form.phone}        onChange={e => f('phone',       e.target.value)} />
          <Input label="Email"             value={form.email}         onChange={e => f('email',       e.target.value)} type="email" />
          <Input label="National ID"       value={form.nationalId}    onChange={e => f('nationalId',  e.target.value)} />
          <Input label="Date of Birth"     value={form.dateOfBirth}   onChange={e => f('dateOfBirth', e.target.value)} type="date" />
          <Select label="Gender"           value={form.gender}        onChange={e => f('gender',      e.target.value)}
            options={[{ value: '', label: 'Select…' }, ...GENDERS.map(g => ({ value: g, label: g }))]} />
        </FormGrid>
      </div>

      {/* Employment */}
      <div className="pt-4 border-t">
        <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Employment</p>
        <FormGrid cols={2}>
          <Input label="Designation"   value={form.designation}   onChange={e => f('designation',   e.target.value)} />
          <Input label="Department"    value={form.department}    onChange={e => f('department',    e.target.value)} />
          <Input label="Grade"         value={form.grade}         onChange={e => f('grade',         e.target.value)} />
          <Select label="Employment Type" required value={form.employmentType} onChange={e => f('employmentType', e.target.value)}
            options={EMPLOYMENT_TYPES.map(t => ({ value: t, label: t.replace(/_/g, ' ') }))} />
          <Input label="Hire Date" required value={form.hireDate} onChange={e => f('hireDate',      e.target.value)} type="date" />
          <Input label="Contract End Date"   value={form.contractEndDate} onChange={e => f('contractEndDate', e.target.value)} type="date" />
        </FormGrid>
      </div>

      {/* Salary */}
      <div className="pt-4 border-t">
        <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Salary & Payment</p>
        <FormGrid cols={3}>
          <Input label="Basic Salary (KES)" required type="number" min={0} value={form.basicSalary} onChange={e => f('basicSalary', e.target.value)} />
          <Input label="House Allowance" type="number" min={0} value={form.houseAllowance} onChange={e => f('houseAllowance', e.target.value)} />
          <Input label="Transport Allowance" type="number" min={0} value={form.transportAllowance} onChange={e => f('transportAllowance', e.target.value)} />
          <Input label="Medical Allowance" type="number" min={0} value={form.medicalAllowance} onChange={e => f('medicalAllowance', e.target.value)} />
          <Select label="Payment Method" value={form.paymentMethod} onChange={e => f('paymentMethod', e.target.value)}
            options={PAYMENT_METHODS.map(m => ({ value: m, label: m }))} />
          <Input label="Bank Name"      value={form.bankName}      onChange={e => f('bankName',     e.target.value)} />
          <Input label="Bank Branch"    value={form.bankBranch}    onChange={e => f('bankBranch',   e.target.value)} />
          <Input label="Account Number" value={form.accountNumber} onChange={e => f('accountNumber',e.target.value)} />
          <Input label="Account Name"   value={form.accountName}   onChange={e => f('accountName',  e.target.value)} />
        </FormGrid>
      </div>

      {/* Statutory */}
      <div className="pt-4 border-t">
        <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-3">Statutory Numbers</p>
        <FormGrid cols={3}>
          <Input label="KRA PIN"  value={form.kraPin}  onChange={e => f('kraPin',  e.target.value)} />
          <Input label="NSSF No." value={form.nssfNo}  onChange={e => f('nssfNo',  e.target.value)} />
          <Input label="NHIF No." value={form.nhifNo}  onChange={e => f('nhifNo',  e.target.value)} />
        </FormGrid>
      </div>

      {/* Notes */}
      <div className="pt-4 border-t">
        <label className="text-sm font-medium">Notes</label>
        <textarea rows={2} className="mt-1 w-full border rounded-md px-3 py-2 text-sm resize-none"
          value={form.notes} onChange={e => f('notes', e.target.value)} placeholder="Any internal notes…" />
      </div>
    </div>
  )
}
