"use client"; import React from 'react'; import Link from 'next/link'; import dayjs from 'dayjs'; import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'; import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'; import { Calendar, ChevronRight, Clock } from 'lucide-react'; import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card'; import BadgeStatus from '@/components/ui/badge-status'; import { cn } from '@/lib/utils'; import { IClient, IClientMilestone } from '../../types'; import { resolveTechnicalStatusMeta } from '../../utils/client-overview-helpers'; dayjs.extend(isSameOrAfter); dayjs.extend(isSameOrBefore); interface ClientMilestoneTimelineProps { client: IClient; variant?: 'list' | 'grid'; } interface GroupedMilestone { dateKey: string; date: dayjs.Dayjs; percent: number; diffDays: number; isOngoing: boolean; hideDate: boolean; items: IClientMilestone[]; } interface GradientSegment { fromPercent: number; toPercent: number; fromHex: string; toHex: string; } // Starting color for active milestone line: Merah rose (Development) const START_LINE_HEX = '#f43f5e'; export default function ClientMilestoneTimeline({ client, variant = 'list' }: ClientMilestoneTimelineProps) { const today = dayjs().startOf('day'); const maxDate = today.add(2, 'month').startOf('day'); const totalDays = maxDate.diff(today, 'day') || 60; // Helper to safely parse and normalize start and end dates (handling edge cases or inverted dates) const getNormalizedDates = (m: IClientMilestone) => { const d1 = m.start_date ? dayjs(m.start_date).startOf('day') : null; const d2 = m.end_date ? dayjs(m.end_date).startOf('day') : null; if (!d1 && !d2) return null; if (d1 && !d2) return { startDate: d1, endDate: d1 }; if (!d1 && d2) return { startDate: d2, endDate: d2 }; const startDate = d1!.isBefore(d2!) ? d1! : d2!; const endDate = d1!.isAfter(d2!) ? d1! : d2!; return { startDate, endDate }; }; // Filter milestones: // 1. Ongoing agendas: started in the past (startDate < today), but endDate is still today or in the future (endDate >= today) // 2. Upcoming agendas: startDate is between today and maxDate (within next 2 months) const processedMilestones: { item: IClientMilestone; isOngoing: boolean; targetDate: dayjs.Dayjs; startDate: dayjs.Dayjs; endDate: dayjs.Dayjs; }[] = []; const rawMilestones = client.milestone || []; rawMilestones.forEach((m) => { const dates = getNormalizedDates(m); if (!dates) return; const { startDate, endDate } = dates; const isOngoing = startDate.isBefore(today) && (endDate.isAfter(today) || endDate.isSame(today, 'day')); const isUpcoming = (startDate.isAfter(today) || startDate.isSame(today, 'day')) && (startDate.isBefore(maxDate) || startDate.isSame(maxDate, 'day')); if (isOngoing) { processedMilestones.push({ item: m, isOngoing: true, targetDate: today, // Position at the start of milestone startDate, endDate, }); } else if (isUpcoming) { processedMilestones.push({ item: m, isOngoing: false, targetDate: startDate, startDate, endDate, }); } }); // Group milestones by target date / start milestone to handle multiple agendas on the same point const groupsMap: { [key: string]: GroupedMilestone } = {}; processedMilestones.forEach(({ item, isOngoing, targetDate }) => { let dateKey: string; let percent: number; let diffDays: number; const isAtStart = isOngoing || targetDate.isSame(today, 'day'); if (isAtStart) { // Group ongoing agendas at the beginning of milestone (0%) dateKey = 'start-milestone'; percent = 0; diffDays = 0; } else { dateKey = targetDate.format('YYYY-MM-DD'); diffDays = targetDate.diff(today, 'day'); const rawPercent = (diffDays / totalDays) * 100; percent = Math.max(0, Math.min(100, rawPercent)); } if (!groupsMap[dateKey]) { groupsMap[dateKey] = { dateKey, date: targetDate, percent, diffDays, isOngoing: false, hideDate: false, items: [], }; } groupsMap[dateKey].items.push(item); if (isOngoing) { groupsMap[dateKey].isOngoing = true; // Hide date label underneath start dot because varying start dates in past would confuse users groupsMap[dateKey].hideDate = true; } }); const groups = Object.values(groupsMap).sort((a, b) => a.percent - b.percent); // Compute sequential line gradient segments: // Starts at Hari Ini (0%, Merah Rose) -> Agenda 1 -> Agenda 2 -> ... -> Agenda N const gradientSegments: GradientSegment[] = []; if (groups.length > 0) { let currentPercent = 0; let currentHex = START_LINE_HEX; // If the first group is at 0%, its status color initiates the line gradient if (groups[0]?.percent === 0) { const firstGroup = groups[0]; const firstMeta = resolveTechnicalStatusMeta(firstGroup.items[0]?.project_assignment_status?.name); currentHex = firstMeta.hexColor; } for (let i = 0; i < groups.length; i++) { const group = groups[i]; const targetPercent = group.percent; const targetMeta = resolveTechnicalStatusMeta(group.items[0]?.project_assignment_status?.name); const targetHex = targetMeta.hexColor; if (targetPercent > currentPercent) { gradientSegments.push({ fromPercent: currentPercent, toPercent: targetPercent, fromHex: currentHex, toHex: targetHex, }); currentPercent = targetPercent; currentHex = targetHex; } } } // Compute month boundaries for tick lines along the 2-month rail const nextMonthStart = today.add(1, 'month').startOf('month'); const month2Start = today.add(2, 'month').startOf('month'); const monthTicks: { label: string; percent: number }[] = []; if (nextMonthStart.isAfter(today) && nextMonthStart.isBefore(maxDate)) { const diff = nextMonthStart.diff(today, 'day'); monthTicks.push({ label: nextMonthStart.format('1 MMM'), percent: (diff / totalDays) * 100, }); } if (month2Start.isAfter(today) && month2Start.isBefore(maxDate)) { const diff = month2Start.diff(today, 'day'); monthTicks.push({ label: month2Start.format('1 MMM'), percent: (diff / totalDays) * 100, }); } const isGrid = variant === 'grid'; const hasAgendas = groups.length > 0; return (
{/* Header: Title + 2-Month Date Span */}
Next 2 Months Milestone ({today.format('DD MMM')} – {maxDate.format('DD MMM YYYY')})
{hasAgendas ? ( {processedMilestones.length} {processedMilestones.length === 1 ? 'Agenda' : 'Agendas'} ) : ( No milestone scheduled )}
{/* Timeline Viewport Container with group/rail for sibling hover coordination */}
{/* Continuous 2-Month Horizontal Rail */}
{/* Gradient Segments connecting Hari Ini -> Agenda 1 -> Agenda 2 -> ... */}
{gradientSegments.map((seg, idx) => (
))}
{/* Start Pin (Today) - Rose if active progression, gray if default */}
{/* End Pin (+2 Months) */}
{/* Month Boundary Tick Markers */} {monthTicks.map((tick, idx) => (
{tick.label}
))} {/* If no milestones in range, show gentle notice */} {!hasAgendas && (
No upcoming milestones in the next 2 months
)} {/* Agenda Milestone Markers */} {groups.map((group) => { const isMulti = group.items.length > 1; const firstItem = group.items[0]; const primaryMeta = resolveTechnicalStatusMeta(firstItem.project_assignment_status?.name); return (
{/* Vertical Tick Line connecting Rail to Dot */}
{/* HoverCard Trigger (Dot + Short Badge + Date) */} {/* Dot / Multi-Dot Indicator */} {isMulti ? (
{group.items.length}
) : (
)} {/* Short Badge underneath dot */}
{isMulti ? `${group.items.length} Agendas` : primaryMeta.shortName}
{/* Date Label strictly underneath (hidden for ongoing agendas with varying start dates) */} {!group.hideDate ? ( {group.date.format('DD MMM')} ) : null} {/* Rich Hover Card Content */} {/* Header */}
{group.isOngoing ? 'Ongoing Milestones (Active Today)' : group.date.format('dddd, DD MMMM YYYY')}
{group.isOngoing ? 'Currently Active' : group.diffDays === 0 ? 'Today' : group.diffDays === 1 ? 'Tomorrow' : `In ${group.diffDays} days`}
{/* Subtitle / Counter */}
{group.items.length === 1 ? (group.isOngoing ? '1 ongoing milestone agenda currently active:' : '1 milestone agenda on this date:') : (group.isOngoing ? `${group.items.length} ongoing milestone agendas currently active:` : `${group.items.length} milestone agendas on this date:`)}
{/* List of Assignment Milestones */}
{group.items.map((item, itemIdx) => (
View Assignment
{item.project_name && (
{item.project_name} {item.project_code && ( ({item.project_code}) )}
)} {item.wo_name && (
WO: {item.wo_name} {item.wo_code && ( [{item.wo_code}] )}
)} {item.description && (

“{item.description}”

)}
{dayjs(item.start_date).format('DD MMM YYYY')} {item.end_date ? ` – ${dayjs(item.end_date).format('DD MMM YYYY')}` : ''}
))}
); })}
); }