Files
ims/components/incidents/incident-table.tsx
T

187 lines
6.9 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import { ChevronRight, Eye, Search } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { FilterChip } from '@/components/ui/filter-chip'
import { StatusTag } from '@/components/ui/status-tag'
import { TableCard, type Column } from '@/components/ui/table-card'
import { PAGE_SIZE, nextSort, withParams, type ListParams, type SortKey } from '@/lib/incidents/list-params'
import type { Incident, SiteOption, TruckOption } from '@/lib/incidents/types'
const TYPE_LABELS: Record<string, string> = {
injury: 'Injury / Medical',
near_miss: 'Near Miss',
hazard: 'Hazard',
asset_damage: 'Asset Damage',
environmental: 'Environmental',
security: 'Security',
fire: 'Fire / Emergency',
transport: 'Transport / Vehicle',
}
const STATUS_OPTIONS = [
{ value: 'reported', label: 'Reported' },
{ value: 'triaged', label: 'Triaged' },
{ value: 'investigating', label: 'Investigating' },
{ value: 'capa_pending', label: 'CAPA pending' },
{ value: 'verification', label: 'Verification' },
{ value: 'closed', label: 'Closed' },
]
const TYPE_OPTIONS = Object.entries(TYPE_LABELS).map(([value, label]) => ({ value, label }))
interface Props {
incidents: Incident[]
basePath: string
total: number
counts: { all: number; open: number; closed: number }
params: ListParams
sites: SiteOption[]
trucks: TruckOption[]
}
const fmtDate = (iso: string) => new Date(iso).toLocaleDateString('en-MY')
export function IncidentTable({ incidents, basePath, total, counts, params, sites, trucks }: Props) {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const search = searchParams.toString() ? `?${searchParams.toString()}` : ''
const [q, setQ] = useState(params.q)
const update = (updates: Record<string, string | null>) =>
router.replace(`${pathname}${withParams(search, updates)}`)
useEffect(() => {
if (q === params.q) return
const timer = setTimeout(() => update({ q: q || null }), 300)
return () => clearTimeout(timer)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [q])
const columns: Column<Incident>[] = [
{
key: 'reference',
header: 'Reference',
sortKey: 'reference_no',
cell: r => <span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>,
},
{ key: 'status', header: 'Status', sortKey: 'status', cell: r => <StatusTag status={r.status} /> },
{ key: 'type', header: 'Type', cell: r => TYPE_LABELS[r.incident_type] ?? r.incident_type },
{
key: 'location',
header: 'Location',
cell: r => [r.zones?.name, r.sites?.name, r.trucks?.truck_no].filter(Boolean).join(' · ') || '—',
},
{ key: 'severity', header: 'Severity', cell: r => (r.severity ? `Sev ${r.severity}` : '—') },
{ key: 'reported', header: 'Reported', sortKey: 'reported_at', cell: r => fmtDate(r.reported_at) },
]
const clearable = Boolean(params.q || params.status || params.type || params.siteId || params.truckId)
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const from = total === 0 ? 0 : (params.page - 1) * PAGE_SIZE + 1
const to = Math.min(total, from + incidents.length - 1)
const toolbar = (
<>
<label className="flex items-center gap-2 h-8 px-2.5 rounded-md bg-surface shadow-input text-[13px] min-w-[260px]">
<Search size={16} strokeWidth={2} className="text-muted" aria-hidden />
<input
type="search"
aria-label="Search incidents"
placeholder="Search reference or description"
value={q}
onChange={e => setQ(e.target.value)}
className="flex-1 bg-transparent outline-none placeholder:text-faint"
/>
</label>
<FilterChip label="Status" value={params.status} options={STATUS_OPTIONS} onChange={v => update({ status: v || null })} />
<FilterChip label="Type" value={params.type} options={TYPE_OPTIONS} onChange={v => update({ type: v || null })} />
{sites.length > 0 && (
<FilterChip
label="Site"
value={params.siteId}
options={sites.map(s => ({ value: s.id, label: s.name }))}
onChange={v => update({ site_id: v || null })}
/>
)}
{trucks.length > 0 && (
<FilterChip
label="Truck"
value={params.truckId}
options={trucks.map(t => ({ value: t.id, label: t.truck_no }))}
onChange={v => update({ truck_id: v || null })}
/>
)}
{clearable && (
<button
type="button"
onClick={() => {
setQ('')
router.replace(pathname)
}}
className="text-[12.5px] text-muted hover:text-ink cursor-pointer"
>
Clear filters
</button>
)}
</>
)
return (
<TableCard
columns={columns}
rows={incidents}
rowKey={r => r.id}
onRowOpen={r => router.push(`${basePath}/incidents/${r.id}`)}
rowActions={r => (
<Link
href={`${basePath}/incidents/${r.id}`}
aria-label="Open incident"
className="inline-grid place-items-center w-7 h-7 rounded-md text-ink-3 hover:bg-rule"
>
<Eye size={16} strokeWidth={2} aria-hidden />
</Link>
)}
views={{
items: [
{ key: 'all', label: 'All', count: counts.all },
{ key: 'open', label: 'Open', count: counts.open },
{ key: 'closed', label: 'Closed', count: counts.closed },
],
active: params.view,
onChange: key => update({ view: key === 'all' ? null : key }),
}}
toolbar={toolbar}
sort={{ key: params.sort, dir: params.dir }}
onSortChange={key => {
const next = nextSort({ key: params.sort, dir: params.dir }, key as SortKey)
update({ sort: next.key, dir: next.dir })
}}
footer={{ from, to, total, page: params.page, pageCount, onPage: p => update({ page: String(p) }) }}
empty={{
title: 'No incidents found',
action: <Button onClick={() => router.push('/report')}>Report incident</Button>,
}}
mobileRow={r => (
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="font-mono text-[12.5px] text-accent">{r.reference_no ?? '—'}</span>
<StatusTag status={r.status} />
</div>
<p className="text-[13px] text-ink-3">
{[TYPE_LABELS[r.incident_type] ?? r.incident_type, r.zones?.name].filter(Boolean).join(' · ')}
</p>
<p className="text-xs text-faint">{fmtDate(r.reported_at)}</p>
</div>
<ChevronRight size={16} strokeWidth={2} className="mt-1 text-faint" aria-hidden />
</div>
)}
/>
)
}