"use client"; import { useMemo, useState, type FC } from 'react'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Button } from '@/components/ui/button'; import { DatePicker } from '@/components/ui/datepicker'; import { Textarea } from '@/components/ui/textarea'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { AlertCircle, Calendar, Edit2, History, Loader2, Plus, Save, Trash2 } from 'lucide-react'; import { useFetchWithAxios } from '@/lib/axios/useFetch'; import { Skeleton } from '@/components/ui/skeleton'; import { serverApiCall } from '@/lib/server-api'; import { toast } from 'sonner'; import { useRouter } from 'next/navigation'; import BadgeStatus from '@/components/ui/badge-status'; import dayjs from 'dayjs'; export interface IDateInterval { start_date: string; end_date: string; description?: string; } export interface IProjectAssignmentTimeline { id: number; start_date: string | null; end_date: string | null; date?: IDateInterval[] | string | null; data?: IDateInterval[] | string | null; description?: string | null; updated_at?: string | null; project_assignment_status: ProjectAssignmentStatus; } export interface ProjectAssignmentStatus { id: number; name: string; description?: string | null; remark?: any; } export interface StatusItem { detailId: number; technicalId: number; statusName: string; description: string; dates: IDateInterval[]; } type Props = { assignmentId: string | number; onClose?: VoidFunction; }; interface ModalState { mode: 'ADD' | 'EDIT'; technicalId: number; detailId: number; statusName: string; existingDates: IDateInterval[]; editIndex?: number; initialStartDate?: Date; initialEndDate?: Date; initialDescription: string; } function extractDatesFromRow(row: any): IDateInterval[] { if (!row) return []; let rawDate = row.data ?? row.date; if (typeof rawDate === 'string') { try { rawDate = JSON.parse(rawDate); } catch { rawDate = null; } } if (Array.isArray(rawDate) && rawDate.length > 0) { return rawDate .filter(Boolean) .map((item: any) => ({ start_date: item?.start_date ? dayjs(item.start_date).format('YYYY-MM-DD') : '', end_date: item?.end_date ? dayjs(item.end_date).format('YYYY-MM-DD') : '', description: typeof item?.description === 'string' ? item.description.trim() : typeof row.description === 'string' ? row.description.trim() : '', })) .filter((d: IDateInterval) => Boolean(d.start_date || d.end_date)); } if (row.start_date || row.end_date) { return [{ start_date: row.start_date ? dayjs(row.start_date).format('YYYY-MM-DD') : '', end_date: row.end_date ? dayjs(row.end_date).format('YYYY-MM-DD') : '', description: typeof row.description === 'string' ? row.description.trim() : '', }]; } return []; } interface EditModalProps { assignmentId: string | number; data: ModalState; onClose: VoidFunction; onSuccess: VoidFunction; } function EditTechnicalStatusModal({ assignmentId, data, onClose, onSuccess }: EditModalProps) { const [startDate, setStartDate] = useState(data.initialStartDate); const [endDate, setEndDate] = useState(data.initialEndDate); const [description, setDescription] = useState(data.initialDescription || ''); const [isSaving, setIsSaving] = useState(false); // Validation: end date must not be earlier than start date const isDateRangeInvalid = useMemo(() => { if (!startDate || !endDate) return false; return dayjs(endDate).isBefore(dayjs(startDate), 'day'); }, [startDate, endDate]); const isDateMissing = !startDate; const handleSave = async () => { if (isDateMissing) { toast.error('Start Date is required', { description: 'Please select both a start date and an end date.' }); return; } if (isDateRangeInvalid) { toast.error('Invalid date interval', { description: 'End date cannot be earlier than start date.' }); return; } setIsSaving(true); let finalDates: IDateInterval[] = [...data.existingDates]; if (data.mode === 'ADD') { const newInterval: IDateInterval = { start_date: startDate ? dayjs(startDate).format('YYYY-MM-DD') : '', end_date: endDate ? dayjs(endDate).format('YYYY-MM-DD') : '', description: description.trim(), }; // Retain all existing dates and append the new one finalDates.push(newInterval); } else if (data.mode === 'EDIT' && typeof data.editIndex === 'number') { const updatedInterval: IDateInterval = { start_date: startDate ? dayjs(startDate).format('YYYY-MM-DD') : '', end_date: endDate ? dayjs(endDate).format('YYYY-MM-DD') : '', description: description.trim(), }; // Update only the targeted date, preserve all other existing dates finalDates = finalDates.map((item, idx) => idx === data.editIndex ? updatedInterval : item ); } const submitPayload = { project_assignment_technical_status_id: Number(data.technicalId), project_assignment_status_detail_id: Number(data.detailId), data: finalDates, }; const res = await serverApiCall('PUT', `/project-assignment/technical-status/${assignmentId}`, submitPayload); setIsSaving(false); if (res.success) { toast.success(data.mode === 'ADD' ? 'Schedule interval added successfully' : 'Schedule interval updated successfully'); onSuccess(); } else { toast.error('Failed to save status', { description: `(${res.code || '-'}) ${res.message}` }); } }; const modalTitle = data.mode === 'ADD' ? 'Add Schedule' : 'Edit Schedule'; const modalDescription = data.mode === 'ADD' ? `Add a new schedule interval and description for ${data.statusName}. Previously recorded dates will be retained.` : `Update the selected schedule interval and description.`; return ( { if (!open && !isSaving) onClose(); }}>
{modalTitle} {modalDescription}
{/* Show existing dates overview when adding */} {data.existingDates.length > 0 && data.mode === 'ADD' && (
Existing Schedules ({data.existingDates.length}) +1 new interval will be added
{data.existingDates.map((item, idx) => (
{dayjs(item.start_date).format('DD MMM YYYY')} – {dayjs(item.end_date).format('DD MMM YYYY')}
{item.description && (

"{item.description}"

)}
))}
)}
{isDateRangeInvalid && (
End date cannot be earlier than start date.
)}
{description.length}/250