import { useState, useEffect } from 'react' import { useParams, useNavigate, Link } from 'react-router-dom' import api from '../../api' import toast from 'react-hot-toast' import { ArrowLeft, FileText, AlertTriangle } from 'lucide-react' const SEVERITY_COLORS = { '1': { bg: '#D1FAE5', fg: '#065F46', label: '低 Low' }, '2': { bg: '#DBEAFE', fg: '#1E40AF', label: '中 Medium' }, '3': { bg: '#FEF3C7', fg: '#92400E', label: '高 High' }, '4': { bg: '#FED7AA', fg: '#9A3412', label: '嚴重 Severe' }, '5': { bg: '#FEE2E2', fg: '#7F1D1D', label: '極嚴重 Critical' }, } const FIELDS = [ { key: 'date', label: '日期 Date' }, { key: 'time', label: '時間 Time' }, { key: 'severity', label: '嚴重程度 Severity', badge: true }, { key: 'location', label: '地點 Location' }, { key: 'employee_name', label: '員工/報告人 Employee' }, { key: 'department', label: '部門 Department' }, { key: 'description', label: '事件描述 Description' }, { key: 'medical_report', label: '醫療報告 Medical Report' }, { key: 'action_taken', label: '處理情況 Action Taken' }, { key: 'responsible_person', label: '負責人 Responsible Person' }, { key: 'created_at', label: '建立時間 Created At' }, ] export default function AccidentDetail() { const { id } = useParams() const navigate = useNavigate() const [record, setRecord] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) useEffect(() => { const numericId = parseInt(id, 10) if (isNaN(numericId) || numericId <= 0) { navigate('/accident/list', { replace: true }) return } fetchRecord(numericId) }, [id]) const fetchRecord = async (recordId) => { setLoading(true) setError(null) try { const { data } = await api.get(`/api/accident/${recordId}`) setRecord(data) } catch (err) { console.error('Error fetching record:', err) const detail = err.response?.data?.detail // FastAPI 422 returns detail as array of validation errors — stringify safely let msg = 'Failed to load record' if (typeof detail === 'string') { msg = detail } else if (Array.isArray(detail)) { msg = `Invalid request: ${detail.map(d => d.msg || JSON.stringify(d)).join('; ')}` } else if (detail && typeof detail === 'object') { msg = JSON.stringify(detail) } else if (err.response?.status === 404) { msg = 'Record not found' } setError(msg) } finally { setLoading(false) } } if (loading) { return (