'use client'; import { useEffect, useState } from 'react'; import { useTranslations } from 'next-intl'; import { Button } from '@/components/ui/shared/Button'; import { Checkbox } from '@/components/ui/shared/Checkbox'; import { isLabCaseCompleted } from '@/components/treatment/treatmentDetailRules'; import { AppDateInput } from '@/components/ui/shared/AppDateInput'; import { toDateInputValue } from '@/components/lab/labCaseDueDateDisplay'; import { LinkedOrganizationSearchCombobox } from '@/components/ui/treatment/LinkedOrganizationSearchCombobox'; import { CaseSentLabel } from '@/components/ui/treatment/CaseSentLabel'; import { DetailLabCaseCommentsSection } from '@/components/ui/treatment/DetailLabCaseCommentsSection'; import { LabCaseTrackerCard } from '@/components/ui/treatment/LabCaseTrackerCard'; import { treatmentTypeLabelFromCatalog } from '@/components/shared/treatmentTypeDisplay'; import { treatmentsApi } from '@/lib/api/treatments'; import { prosthesisCatalogApi } from '@/lib/api/prosthesis-catalog'; import type { ProsthesisCatalogEntry, TreatmentCatalogEntry } from '@/types/treatment-catalog'; import type { LabCaseDraft, LinkedOrganizationOption, TreatmentDetailDraft } from '@/types/treatment'; import type { PatientLabCaseSummary } from '@/types/lab-case-activity'; import { getUserFacingError } from '@/components/shared/formatApiError'; import { FORM_SELECT_CLASS } from '@/components/shared/formSelectStyles'; import { isArchSentinel, toothJobRowsForDetail, } from '@/components/treatment/prosthesisTree'; import { LabCaseToothJobsList } from '@/components/ui/lab/LabCaseProsthesisGroupsList'; interface LabCasesDispatchPanelProps { details: TreatmentDetailDraft[]; activeDetailId: string; labCases: LabCaseDraft[]; labDependentCodes: Set; treatmentCatalog: TreatmentCatalogEntry[]; prosthesisCatalog?: ProsthesisCatalogEntry[]; labCaseSummary?: PatientLabCaseSummary | null; locale: string; onLabCaseSummaryChange?: (summary: PatientLabCaseSummary) => void; onLabCaseMarkedRead?: (labCaseId: string) => void; onLabCaseActivityChange?: () => void; activeLabCaseId: string | null; onLabCasesChange: (labCases: LabCaseDraft[]) => void; disabled: boolean; canEdit: boolean; orgs: LinkedOrganizationOption[]; organizationSearch: string; onOrganizationSearchChange: (value: string) => void; recentOrganizationIds: string[]; canInviteLab?: boolean; onInviteLab?: () => void; sendBusyId: string | null; onSendLabCase: (labCase: LabCaseDraft, comment?: string) => void | Promise; onCommentError?: (message: string) => void; } function prosthesisTeethForDetail(activeDetail: TreatmentDetailDraft): string[] { if (activeDetail.treatmentType !== 'prosthesis') return []; if (activeDetail.toothSelectionGroups.length > 0) { return activeDetail.toothSelectionGroups.flatMap((g) => g.teeth); } return activeDetail.teeth; } function isProsthesisMapComplete( labCase: LabCaseDraft, fdiTeeth: string[], detailClientId: string, ): boolean { const assigned = new Set( labCase.toothProsthesis .filter((tp) => tp.detailClientId === detailClientId && Boolean(tp.prosthesisTypeCode)) .map((tp) => tp.tooth), ); const hasArch = [...assigned].some(isArchSentinel); if (fdiTeeth.length === 0) return hasArch; return fdiTeeth.every((tooth) => assigned.has(tooth)); } export function LabCasesDispatchPanel({ details, activeDetailId, labCases, labDependentCodes, treatmentCatalog, prosthesisCatalog = [], labCaseSummary, locale, onLabCaseSummaryChange, onLabCaseMarkedRead, onLabCaseActivityChange, activeLabCaseId, onLabCasesChange, disabled, canEdit, orgs, organizationSearch, onOrganizationSearchChange, recentOrganizationIds, canInviteLab = false, onInviteLab, sendBusyId, onSendLabCase, onCommentError, }: LabCasesDispatchPanelProps) { const t = useTranslations('treatment'); const tErrors = useTranslations('errors'); const [fetchedCatalog, setFetchedCatalog] = useState([]); const [pendingComment, setPendingComment] = useState(''); const hasTrackerSummary = Boolean(labCaseSummary && labCaseSummary.labCaseId); const activeLinkedOrganizations = orgs.filter((o) => o.active); const recentOrganizations = recentOrganizationIds .map((id) => activeLinkedOrganizations.find((o) => o.id === id)) .filter(Boolean) as LinkedOrganizationOption[]; const activeDetail = details.find((d) => d.clientId === activeDetailId) ?? null; const isLabDependentDetail = Boolean( activeDetail && labDependentCodes.has(activeDetail.treatmentType), ); const labCaseForActiveDetail = labCases.find((lc) => lc.detailClientId === activeDetailId) ?? null; const activeLabCase = labCaseForActiveDetail ?? (activeLabCaseId ? labCases.find( (lc) => lc.clientId === activeLabCaseId && (lc.detailClientId == null || lc.detailClientId === activeDetailId), ) : null) ?? null; const sent = Boolean(activeLabCase?.sentAt); const activeLabOrgName = activeLabCase?.destinationOrganizationId ? orgs.find((o) => o.id === activeLabCase.destinationOrganizationId)?.name : null; const fdiTeeth = activeDetail ? prosthesisTeethForDetail(activeDetail) : []; const prosthesisComplete = activeLabCase ? isProsthesisMapComplete(activeLabCase, fdiTeeth, activeDetailId) : false; const catalog = prosthesisCatalog.length > 0 ? prosthesisCatalog : fetchedCatalog; useEffect(() => { if (prosthesisCatalog.length > 0) return; let cancelled = false; void prosthesisCatalogApi .list() .then((res) => { if (!cancelled) setFetchedCatalog(res.data); }) .catch(() => { if (!cancelled) setFetchedCatalog([]); }); return () => { cancelled = true; }; }, [prosthesisCatalog.length]); useEffect(() => { setPendingComment(''); }, [activeLabCase?.clientId]); function updateActiveLabCase(patch: Partial) { if (!activeLabCase) return; onLabCasesChange( labCases.map((lc) => (lc.clientId === activeLabCase.clientId ? { ...lc, ...patch } : lc)), ); } useEffect(() => { if (!activeLabCase || sent || !activeDetail) return; const ids = activeDetail.attachmentMetas.map((a) => a.id); const missing = ids.filter((id) => !activeLabCase.attachmentIds.includes(id)); if (missing.length === 0) return; updateActiveLabCase({ attachmentIds: [...activeLabCase.attachmentIds, ...missing] }); // eslint-disable-next-line react-hooks/exhaustive-deps -- only sync newly uploaded files }, [activeDetail?.attachmentMetas, activeLabCase?.clientId, sent]); if (!activeDetail || !isLabDependentDetail) { return null; } function toggleAttachmentInActiveLabCase(attachmentId: string, checked: boolean) { if (!activeLabCase || sent) return; const set = new Set(activeLabCase.attachmentIds); if (checked) set.add(attachmentId); else set.delete(attachmentId); updateActiveLabCase({ attachmentIds: [...set] }); } function handleSelectOrganization(org: LinkedOrganizationOption) { updateActiveLabCase({ destinationOrganizationId: org.id, }); } const caseFullyComplete = isLabCaseCompleted(activeLabCase?.taskProgress); const canEditDueDate = canEdit && !disabled && (!sent || !caseFullyComplete); const canPostComments = canEdit && !caseFullyComplete; const canShowComments = Boolean(activeLabCase?.id); const commentsDeferSubmit = Boolean(!sent); async function handleSentDueDateBlur(nextValue: string) { if (!activeLabCase?.id || !sent || !canEditDueDate) return; const dueDate = nextValue || null; if (dueDate === (activeLabCase.dueDate?.slice(0, 10) ?? null)) return; try { const response = await treatmentsApi.updateLabCaseDueDate(activeLabCase.id, dueDate); updateActiveLabCase({ dueDate: response.data.dueDate, taskProgress: response.data.taskProgress ?? activeLabCase.taskProgress, }); } catch (error) { onCommentError?.(getUserFacingError(error, tErrors, t('dueDateUpdateError'))); } } function renderDueDateField() { if (!activeLabCase) return null; const inputValue = toDateInputValue(activeLabCase.dueDate); const dueDateInputId = `lab-case-due-date-${activeLabCase.clientId}`; return (
{ updateActiveLabCase({ dueDate: next || null }); }} onBlur={(committed) => { if (sent) void handleSentDueDateBlur(committed); }} className={`${FORM_SELECT_CLASS} w-full min-w-0 max-w-full sm:max-w-[11rem] rounded-md py-1.5 text-sm`} />
{sent && caseFullyComplete && activeLabCase.dueDate ? (

{t('dueDateLockedCompleted')}

) : null}
); } const typeLabel = treatmentTypeLabelFromCatalog(activeDetail.treatmentType, treatmentCatalog); const toothJobRows = activeLabCase ? toothJobRowsForDetail(activeLabCase.toothProsthesis, activeDetailId) : []; const activeDetailAttachments = activeDetail.attachmentMetas ?? []; return (

{t('labDispatchTitle')}

{typeLabel}

{activeLabCase ? renderDueDateField() : null}
{activeLabCase ? (
{sent ? ( <> {activeLabOrgName ? (

{t('selectLab')}

{activeLabOrgName}

) : null} {toothJobRows.length > 0 ? ( ) : null} {hasTrackerSummary && labCaseSummary ? ( ) : null} {canShowComments && activeLabCase?.id ? ( ) : null} ) : ( <>

{t('selectLab')}

{recentOrganizations.length > 0 && (
{t('recent')} {recentOrganizations.map((o) => ( ))}
)}

{t('prosthesisTypesTitle')}

{t('prosthesisEditOnChart')}

{toothJobRows.length === 0 ? (

{t('prosthesisMissingOnChart')}

) : ( )}
{activeDetailAttachments.length > 0 ? (

{t('labShipmentAttachments')}

{t('labShipmentAttachmentsHint')}

{activeDetailAttachments.map((att) => ( toggleAttachmentInActiveLabCase(att.id, next)} label={`${att.fileName} (${(att.sizeBytes / 1024).toFixed(1)} KB)`} /> ))}
) : null} {hasTrackerSummary && labCaseSummary ? ( ) : null} {canShowComments && activeLabCase?.id ? ( ) : null}
)}
) : null}
); }