import React, { useState, useEffect, useRef } from "react"; import ReactDOM from "react-dom"; import { useParams, useNavigate } from "react-router"; import { toast } from "react-toastify"; import { getWorkOrderById, addComment, changeWorkOrderStatus, fetchUsers, changeWorkOrderAssignment, fetchVendorsDropdown, dispatchToVendor, getDispatchById, updateDispatch, addDispatchComment } from "../api"; import "./WorkOrderViewPage.css"; function AssignDropdown({ value, onAssign }) { const [open, setOpen] = useState(false); const [users, setUsers] = useState([]); const [loaded, setLoaded] = useState(false); const btnRef = useRef(null); const menuRef = useRef(null); const [menuPos, setMenuPos] = useState({ top: 0, left: 0 }); useEffect(() => { const handleClick = (e) => { if (btnRef.current?.contains(e.target)) return; if (menuRef.current?.contains(e.target)) return; setOpen(false); }; document.addEventListener("mousedown", handleClick); return () => document.removeEventListener("mousedown", handleClick); }, []); const handleOpen = async () => { if (!loaded) { try { const data = await fetchUsers(); setUsers(data); setLoaded(true); } catch { return; } } if (btnRef.current) { const rect = btnRef.current.getBoundingClientRect(); setMenuPos({ top: rect.bottom + 4, left: rect.left }); } setOpen(!open); }; const handleSelect = async (userId, userName) => { setOpen(false); onAssign(userId, userName); }; return ( <> {open && ReactDOM.createPortal(
{users.map((u) => ( ))}
, document.body )} ); } function CollapsibleSection({ title, defaultOpen = false, children }) { const [open, setOpen] = useState(defaultOpen); return (

setOpen(!open)}> ▸ {title}

{open && children}
); } function formatDateTime(value) { const d = new Date(value.endsWith("Z") ? value : value + "Z"); if (isNaN(d)) return value; const date = d.toLocaleDateString("en-CA"); const time = d.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hour12: false }); const tz = d.toLocaleTimeString(undefined, { timeZoneName: "short" }).split(" ").pop(); return `${date} ${time} ${tz}`; } function CommentTimeline({ comments }) { const bottomRef = useRef(null); const sorted = [...(comments || [])].sort((a, b) => new Date(a.createdDate) - new Date(b.createdDate) ); useEffect(() => { bottomRef.current?.scrollIntoView(); }, [sorted.length]); if (!sorted.length) { return

No comments yet.

; } return (
{sorted.map((c) => (
{c.userName || c.commenter || "System"} {c.createdDate ? formatDateTime(c.createdDate) : ""}
{c.commenttext}
))}
); } function AuditTimeline({ entries }) { const bottomRef = useRef(null); const sorted = [...(entries || [])].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt) ); useEffect(() => { bottomRef.current?.scrollIntoView(); }, [sorted.length]); if (!sorted.length) { return

No changes recorded.

; } return (
{sorted.map((e) => (
{e.userName || "System"} {e.createdAt ? formatDateTime(e.createdAt) : ""}
{e.fieldName} {e.oldValue && {e.oldValue}} → {e.newValue}
))}
); } const DISPATCH_STATUSES = ["Sent", "Acknowledged", "In Progress", "Completed", "Cancelled"]; function DispatchDetailModal({ dispatchId, onClose, onUpdated }) { const [dispatch, setDispatch] = useState(null); const [loading, setLoading] = useState(true); const [editing, setEditing] = useState(false); const [form, setForm] = useState({}); const [saving, setSaving] = useState(false); const [commentText, setCommentText] = useState(""); const [sendEmail, setSendEmail] = useState(true); const [sendingComment, setSendingComment] = useState(false); const bottomRef = useRef(null); const loadDispatch = async () => { try { const data = await getDispatchById(dispatchId); setDispatch(data); setForm({ status: data.status || "", nteAmount: data.nteAmount != null ? String(data.nteAmount) : "", scheduledDate: data.scheduledDate ? data.scheduledDate.split("T")[0] : "", completedDate: data.completedDate ? data.completedDate.split("T")[0] : "", description: data.description || "", }); } catch { toast.error("Failed to load dispatch"); } finally { setLoading(false); } }; useEffect(() => { loadDispatch(); }, [dispatchId]); useEffect(() => { bottomRef.current?.scrollIntoView(); }, [dispatch?.comments?.length]); const handleSave = async () => { setSaving(true); try { await updateDispatch({ Id: dispatchId, Status: form.status, NTEAmount: form.nteAmount ? parseFloat(form.nteAmount) : null, ScheduledDate: form.scheduledDate || null, CompletedDate: form.completedDate || null, Description: form.description, }); toast.success("Dispatch updated"); setEditing(false); loadDispatch(); onUpdated(); } catch { toast.error("Failed to update dispatch"); } finally { setSaving(false); } }; const handleComment = async (e) => { e.preventDefault(); if (!commentText.trim()) return; setSendingComment(true); try { const newComment = await addDispatchComment(dispatchId, commentText.trim(), sendEmail); setCommentText(""); setDispatch((prev) => ({ ...prev, comments: [...(prev.comments || []), newComment], })); } catch { toast.error("Failed to send message"); } finally { setSendingComment(false); } }; if (loading) { return ReactDOM.createPortal(
Loading...
, document.body ); } if (!dispatch) return null; return ReactDOM.createPortal(
e.stopPropagation()}>

{dispatch.dispatchNumber || dispatch.poNumber} · {dispatch.vendorName}

PO: {dispatch.poNumber} · WO: {dispatch.woNumber} · {dispatch.vendorEmail}
{editing ? ( <>
setForm(f => ({ ...f, nteAmount: e.target.value }))} step="0.01" />
setForm(f => ({ ...f, scheduledDate: e.target.value }))} />
setForm(f => ({ ...f, completedDate: e.target.value }))} />