'use client' import { useState } from 'react' import { useRouter } from 'next/navigation' interface User { id: string name: string department: string } interface Props { incidentId: string users: User[] } export function CapaForm({ incidentId, users }: Props) { const router = useRouter() const [description, setDescription] = useState('') const [ownerId, setOwnerId] = useState('') const [department, setDepartment] = useState('') const [dueDate, setDueDate] = useState('') const [priority, setPriority] = useState<'low' | 'med' | 'high'>('med') const [rootCauseRef, setRootCauseRef] = useState('') const [saving, setSaving] = useState(false) const [error, setError] = useState(null) function handleOwnerChange(id: string) { setOwnerId(id) const u = users.find(u => u.id === id) if (u) setDepartment(u.department) } async function handleSubmit(e: React.FormEvent) { e.preventDefault() if (!ownerId || !description || !dueDate) { setError('Description, owner, and due date are required') return } setSaving(true) setError(null) const res = await fetch('/api/capa', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ incident_id: incidentId, description, owner_user_id: ownerId, department, due_date: dueDate, priority, root_cause_ref: rootCauseRef || null, }), }) if (!res.ok) { const data = await res.json() setError(data.error ?? 'Create failed') setSaving(false) return } router.push(`/hse/incidents/${incidentId}`) router.refresh() } return (