'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' type FiveWhyStep = { why: string; answer: string } type FishboneCategory = { category: 'man' | 'machine' | 'method' | 'material' | 'environment' | 'measurement' causes: string[] } const FISHBONE_CATEGORIES: FishboneCategory['category'][] = [ 'man', 'machine', 'method', 'material', 'environment', 'measurement', ] const CATEGORY_LABELS: Record = { man: 'Man (People)', machine: 'Machine', method: 'Method', material: 'Material', environment: 'Environment', measurement: 'Measurement', } interface Props { incidentId: string existingInvestigationId: string | null } export function InvestigationForm({ incidentId, existingInvestigationId }: Props) { const router = useRouter() const [method, setMethod] = useState<'five_why' | 'fishbone' | 'other'>('five_why') const [fiveWhy, setFiveWhy] = useState([ { why: 'Why did the incident happen?', answer: '' }, ]) const [fishbone, setFishbone] = useState( FISHBONE_CATEGORIES.map(c => ({ category: c, causes: [''] })) ) const [findingsText, setFindingsText] = useState('') const [rootCause, setRootCause] = useState('') const [alcoholTest, setAlcoholTest] = useState('') const [urineTest, setUrineTest] = useState('') const [witnessRefs, setWitnessRefs] = useState(['']) const [complete, setComplete] = useState(false) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const [aiDraftLoading, setAiDraftLoading] = useState(false) function addWhyStep() { if (fiveWhy.length >= 5) return setFiveWhy([...fiveWhy, { why: '', answer: '' }]) } function updateWhyStep(i: number, field: keyof FiveWhyStep, value: string) { setFiveWhy(fiveWhy.map((s, idx) => idx === i ? { ...s, [field]: value } : s)) } function updateFishboneCause(catIdx: number, causeIdx: number, value: string) { setFishbone(fishbone.map((c, i) => i === catIdx ? { ...c, causes: c.causes.map((cause, j) => j === causeIdx ? value : cause) } : c )) } function addFishboneCause(catIdx: number) { setFishbone(fishbone.map((c, i) => i === catIdx ? { ...c, causes: [...c.causes, ''] } : c)) } async function getAiDraft() { setAiDraftLoading(true) try { const res = await fetch(`/ims/api/incidents/${incidentId}/ai/rca-draft`, { method: 'POST' }) if (!res.ok) return const draft = await res.json() as { five_why_steps: Array<{ why: string; answer: string }> root_cause_summary: string capa_suggestions: string[] } if (draft.five_why_steps?.length > 0) { setMethod('five_why') setFiveWhy(draft.five_why_steps) } if (draft.root_cause_summary) setRootCause(draft.root_cause_summary) if (draft.capa_suggestions?.length > 0) { setFindingsText(draft.capa_suggestions.map((s, i) => `${i + 1}. ${s}`).join('\n')) } } catch { // Non-blocking — investigator can fill manually } finally { setAiDraftLoading(false) } } async function handleSubmit(e: React.FormEvent) { e.preventDefault() setSaving(true) setError(null) const payload = { method, findings_text: findingsText || null, root_cause_summary: rootCause || null, alcohol_test_result: alcoholTest || null, urine_test_result: urineTest || null, witness_statement_refs: witnessRefs.map(w => w.trim()).filter(Boolean), five_why_steps: method === 'five_why' ? fiveWhy.filter(s => s.answer) : null, fishbone_categories: method === 'fishbone' ? fishbone.map(c => ({ ...c, causes: c.causes.filter(Boolean) })).filter(c => c.causes.length > 0) : null, } let res: Response if (existingInvestigationId) { res = await fetch(`/ims/api/incidents/${incidentId}/investigation`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...payload, investigation_id: existingInvestigationId, complete }), }) } else { res = await fetch(`/ims/api/incidents/${incidentId}/investigation`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), }) } if (!res.ok) { const data = await res.json() setError(data.error ?? 'Save failed') setSaving(false) return } router.push(`/hse/incidents/${incidentId}`) router.refresh() } return (
{(['five_why', 'fishbone', 'other'] as const).map(m => ( ))}
{method === 'five_why' && (

5-Why Analysis

{fiveWhy.map((step, i) => (
updateWhyStep(i, 'why', e.target.value)} placeholder="Why did this happen?" className="w-full rounded border border-gray-300 px-2 py-1.5 text-sm" />