import React, { useState, useEffect, useMemo } from 'react';
import { format, differenceInMinutes, parseISO } from 'date-fns';
import { CheckCircle2, Circle, Clock, MapPin, AlertCircle, Zap, Navigation, Edit2, Trash2, Plus, List, X, Calendar as CalendarIcon, AlignLeft, MessageSquare, FileText, Flag } from 'lucide-react';
import { useTourStore } from '@/store/useTourStore';
import { useConfirm } from '@/hooks/useConfirm';
import { useNotification } from '@/hooks/useNotification';
import { CommentModal } from '@/components/CommentModal';
const TimeVariance = ({ planned, actual }: { planned: string, actual: string | null }) => {
if (!actual) return null;
const diff = differenceInMinutes(parseISO(actual), parseISO(planned));
const isLate = diff > 0;
return (
{isLate ?
:
}
{isLate ? `Trễ ${diff} phút` : diff === 0 ? 'Đúng giờ' : `Sớm ${Math.abs(diff)} phút`}
);
};
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number) => {
const p = 0.017453292519943295; // Math.PI / 180
const c = Math.cos;
const a = 0.5 - c((lat2 - lat1) * p) / 2 +
c(lat1 * p) * c(lat2 * p) *
(1 - c((lon2 - lon1) * p)) / 2;
return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
};
const formatTravelTime = (minutes: number) => {
if (minutes < 60) return `${minutes} phút`;
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return mins > 0 ? `${hours} giờ ${mins} phút` : `${hours} giờ`;
};
export const ItineraryTimeline = ({
onAddLocation,
onEditLocation,
onQuickNote,
onSuccess,
isPublicView = false
}: {
onAddLocation?: (legId: string, isStart?: boolean, isEnd?: boolean) => void,
onEditLocation?: (location: any) => void,
onQuickNote?: (name: string) => void,
onSuccess?: () => void,
isPublicView?: boolean
}) => {
// Tối ưu hóa selectors để chỉ lắng nghe những thay đổi cần thiết
const currentTour = useTourStore(state => state.currentTour);
const legs = useTourStore(state => state.legs);
const userRole = useTourStore(state => state.userRole);
const optimizeRouting = useTourStore(state => state.optimizeRouting);
const addLeg = useTourStore(state => state.addLeg);
const updateLeg = useTourStore(state => state.updateLeg);
// Removed: const { isPublicView } = useTourStore(state => state); // isPublicView is passed as a prop
const deleteLeg = useTourStore(state => state.deleteLeg);
const initializeLegs = useTourStore(state => state.initializeLegs);
const fetchTour = useTourStore(state => state.fetchTour);
const deleteLocation = useTourStore(state => state.deleteLocation);
// Khai báo logic canEdit để sử dụng trong toàn bộ component
const canEdit = isPublicView ? false : ['OWNER', 'MANAGER'].includes(userRole || '');
const confirm = useConfirm();
const notify = useNotification();
const [isLegCountModalOpen, setIsLegCountModalOpen] = useState(false);
const [tempLegCount, setTempLegCount] = useState(3);
const [isCommentModalOpen, setIsCommentModalOpen] = useState(false);
const [commentLocationId, setCommentLocationId] = useState('');
const [commentLocationName, setCommentLocationName] = useState('');
// Tối ưu hóa: Cập nhật UI ngay lập tức bằng cách can thiệp vào State của Store
const handleCommentIncrement = (locationId: string) => {
const currentLegs = useTourStore.getState().legs;
const updatedLegs = currentLegs.map(leg => ({
...leg,
locations: leg.locations.map(loc =>
loc.id === locationId
? { ...loc, _count: { ...loc._count, comments: (loc._count?.comments || 0) + 1 } }
: loc
)
}));
// Dùng setState của Zustand để cập nhật một phần dữ liệu
useTourStore.setState({ legs: updatedLegs });
};
const handleCommentDecrement = (locationId: string) => {
const currentLegs = useTourStore.getState().legs;
const updatedLegs = currentLegs.map(leg => ({
...leg,
locations: leg.locations.map(loc =>
loc.id === locationId
? { ...loc, _count: { ...loc._count, comments: Math.max(0, (loc._count?.comments || 1) - 1) } }
: loc
)
}));
useTourStore.setState({ legs: updatedLegs });
};
// State cho Modal sửa chặng
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [editingLegData, setEditingLegData] = useState({
id: '',
note: '',
description: '',
startDate: '',
endDate: ''
});
const toggleComplete = async (locationId: string) => {
// Gọi API PATCH /api/v1/locations/:id để cập nhật trạng thái
console.log("Toggle status for location:", locationId);
};
const handleAddLeg = async () => {
const note = window.prompt("Nhập ghi chú cho chặng mới:", `Chặng ${legs.length + 1}`);
if (note && currentTour) {
await addLeg(currentTour.id, { note });
}
};
const handleDeclareLegs = async () => {
setTempLegCount(legs.length > 0 ? legs.length : 3);
setIsLegCountModalOpen(true);
};
const confirmDeclareLegs = async () => {
if (tempLegCount > 0 && tempLegCount <= 20 && currentTour) {
await initializeLegs(currentTour.id, tempLegCount);
}
setIsLegCountModalOpen(false);
};
const handleEditLeg = async (leg: any) => {
setEditingLegData({
id: leg.id,
note: leg.note || "",
description: leg.description || "",
startDate: leg.startDate ? leg.startDate.split('T')[0] : "",
endDate: leg.endDate ? leg.endDate.split('T')[0] : ""
});
setIsEditModalOpen(true);
};
const saveLegEdit = async () => {
if (editingLegData.id) {
await updateLeg(editingLegData.id, {
note: editingLegData.note,
description: editingLegData.description,
startDate: editingLegData.startDate || null,
endDate: editingLegData.endDate || null
});
setIsEditModalOpen(false);
}
};
const handleDeleteLeg = async (legId: string) => {
const isConfirmed = await confirm({
title: 'Xóa chặng',
message: 'Bạn có chắc chắn muốn xóa chặng này?'
});
if (isConfirmed) {
try {
await deleteLeg(legId);
onSuccess?.();
} catch (err: any) {
notify({ title: 'Lỗi', message: err.message, type: 'error' });
}
}
};
const handleDeleteLocation = async (id: string) => {
const isConfirmed = await confirm({
title: 'Xóa địa điểm',
message: 'Bạn có chắc chắn muốn xóa địa điểm này?'
});
if (isConfirmed) {
try {
await deleteLocation(id);
onSuccess?.();
} catch (err: any) {
notify({ title: 'Lỗi', message: err.message, type: 'error' });
}
}
};
// Tạo mảng phẳng tất cả địa điểm để tính toán quãng đường liên tục giữa các chặng
const allLocations = useMemo(() => legs.flatMap(l => l.locations), [legs]);
useEffect(() => {
console.log("ItineraryTimeline: Legs updated", legs);
}, [legs]);
return (
{legs.length === 0 ? (
Chưa có chặng nào trong lộ trình.
) : (
legs.map((leg, legIdx) => {
const totalDwellMinutes = leg.locations.reduce((acc: number, loc: any) => {
if (loc.plannedStart && loc.plannedEnd) {
return acc + differenceInMinutes(parseISO(loc.plannedEnd), parseISO(loc.plannedStart));
}
return acc;
}, 0);
// Xác định địa điểm cuối cùng của chặng trước đó để hiển thị tính liên tục
const prevLegLastLoc = legIdx > 0 ? legs[legIdx - 1]?.locations.slice(-1)[0] : null;
return (
{/* Leg Header */}
{leg.sequence}
{leg.note || `Chi tiết Chặng ${leg.sequence}`}
{leg.startDate && (
{format(parseISO(leg.startDate), 'dd/MM/yyyy')}
{leg.endDate && leg.endDate !== leg.startDate && ` - ${format(parseISO(leg.endDate), 'dd/MM/yyyy')}`}
)}
{prevLegLastLoc && (
Tiếp nối từ {prevLegLastLoc.name}
)}
{canEdit && (
<>
onAddLocation?.(leg.id)}
className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all"
title="Thêm địa điểm vào chặng này"
>
handleEditLeg(leg)}
className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all"
>
handleDeleteLeg(leg.id)}
className="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-xl transition-all"
>
>
)}
{leg.totalDistance !== undefined && (
{leg.totalDistance} km
~ {formatTravelTime(Math.round((leg.totalDistance / 35) * 60))}
)}
{totalDwellMinutes > 0 && ( // Always show dwell time
Dừng: {formatTravelTime(totalDwellMinutes)}
)}
{['OWNER', 'MANAGER'].includes(userRole || '') && legs.length > 0 && (
optimizeRouting(leg.id)}
className="ml-auto flex items-center gap-1.5 text-xs font-bold text-indigo-600 hover:text-indigo-700 bg-indigo-50 hover:bg-indigo-100 px-3 py-1.5 rounded-xl transition-all"
>
Tối ưu
)} {/* Only show optimize button if canEdit */}
{/* Vertical Line for the whole leg */}
{/* Mở rộng đường kẻ xuống dưới (bottom-[-3rem]) để nối liền với chặng tiếp theo */}
{/* Nút thêm nhanh "Điểm xuất phát" cho Chặng 1 nếu chưa có */}
{legIdx === 0 && !leg.locations.some(loc => loc.plannedStart && new Date(loc.plannedStart).getTime() === 0) && (
onAddLocation?.(leg.id, true)}
className="flex-1 bg-blue-50/20 p-4 rounded-xl border border-dashed border-blue-100 hover:border-blue-400 hover:bg-blue-50 transition-all flex items-center justify-between group"
>
Điểm xuất phát
Nhấn để ghim điểm bắt đầu cho Tour...
)}
{/* Nút thêm nhanh "Điểm kết thúc" cho Chặng cuối nếu chưa có */}
{legIdx === legs.length - 1 && !legs.some(l => l.locations.some(loc => loc.plannedEnd && new Date(loc.plannedEnd).getTime() === 0)) && (
onAddLocation?.(leg.id, false, true)}
className="flex-1 bg-red-50/20 p-4 rounded-xl border border-dashed border-red-100 hover:border-red-400 hover:bg-red-50 transition-all flex items-center justify-between group"
>
Điểm kết thúc
Nhấn để ghim điểm kết thúc cho Tour...
)}
{leg.locations.map((location, idx) => {
// Tìm vị trí của điểm này trong toàn bộ hành trình
const globalIdx = allLocations.findIndex(loc => loc.id === location.id);
const prevLocation = globalIdx > 0 ? allLocations[globalIdx - 1] : null;
const distanceFromPrev = prevLocation
? calculateDistance(prevLocation.latitude, prevLocation.longitude, location.latitude, location.longitude)
: null;
const dwellMinutes = (location.plannedStart && location.plannedEnd)
? differenceInMinutes(parseISO(location.plannedEnd), parseISO(location.plannedStart))
: null;
const locationExpense = leg.expenses?.find((e: any) => e.locationId === location.id);
// Nhận diện điểm mốc dựa trên timestamp đặc biệt (0) thay vì chỉ số mảng
const isStartPoint = location.plannedStart && new Date(location.plannedStart).getTime() === 0;
const isEndPoint = location.plannedEnd && new Date(location.plannedEnd).getTime() === 0;
return (
{/* Timeline Node */}
toggleComplete(location.id)}
className={`transition-colors duration-200 ${location.status === 'COMPLETED' ? 'text-green-500' : 'text-gray-300 hover:text-blue-500'}`}
>
{location.status === 'COMPLETED' ? (
) : (
)}
{/* Card Content */}
{isStartPoint && (
Điểm bắt đầu
)}
{isEndPoint && (
Điểm kết thúc
)}
{location.name}
{location.address}
{location.note && (
{location.note}
)}
{dwellMinutes !== null && (
Thời gian dừng: {formatTravelTime(dwellMinutes)}
)}
{locationExpense && (
Chi phí: {Number(locationExpense.amount).toLocaleString()}đ
{locationExpense.description && (
Dịch vụ: {locationExpense.description}
)}
{locationExpense.note && (
{locationExpense.note}
)}
{locationExpense.paidBy && (
Đã thanh toán: {locationExpense.paidBy.name}
)}
)}
{onQuickNote && !isPublicView && (
onQuickNote(location.name)}
className="flex items-center gap-1 px-2 py-1 bg-amber-50 hover:bg-amber-100 text-amber-600 rounded-lg text-[10px] font-bold transition-all border border-amber-100"
title="Ghi chú nhanh"
>
)}
{
setCommentLocationId(location.id);
setCommentLocationName(location.name);
setIsCommentModalOpen(true);
}}
className="flex items-center gap-1 px-2 py-1 bg-gray-50 hover:bg-blue-50 text-gray-400 hover:text-blue-600 rounded-lg text-[10px] font-bold transition-all border border-gray-100 hover:border-blue-100"
>
{location._count?.comments > 0 && `(${location._count.comments})`}
{location.plannedStart ? format(parseISO(location.plannedStart), 'HH:mm') : '--:--'}
{location.status === 'COMPLETED' && location.actualStart && (
Thực tế: {format(parseISO(location.actualStart), 'HH:mm')}
)}
{canEdit && !isStartPoint && !isEndPoint && ( // Only show edit/delete if canEdit
onEditLocation?.(location)} className="p-1 text-gray-400 hover:text-blue-600 transition-colors">
handleDeleteLocation(location.id)} className="p-1 text-gray-400 hover:text-red-600 transition-colors">
)}
{/* Logic tính toán độ lệch thời gian */}
{/* Hiển thị quãng đường di chuyển từ điểm trước ĐẾN điểm hiện tại */}
{distanceFromPrev !== null && distanceFromPrev > 0 && (
+{distanceFromPrev.toFixed(1)} km từ {prevLocation?.name.split(',')[0]}
)}
);
})}
);
})
)}
{/* Actions at the bottom of the list */}
{canEdit && ( // Only show these buttons if canEdit
{legs.length > 0 ? "Khai báo lại số lượng chặng" : "Bắt đầu bằng việc khai báo số chặng"}
Thêm chặng lẻ vào cuối
)}
{/* Modal Khai báo số chặng (Popover) */}
{isLegCountModalOpen && (
setIsLegCountModalOpen(false)} />
Số chặng lộ trình
setIsLegCountModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
Bạn muốn chia chuyến đi này thành bao nhiêu chặng nhỏ? (Tối đa 20 chặng)
setTempLegCount(Math.max(1, tempLegCount - 1))}
className="w-12 h-12 rounded-2xl border-2 border-gray-100 flex items-center justify-center text-2xl font-bold text-gray-400 hover:border-blue-200 hover:text-blue-600 transition-all"
>
-
{tempLegCount}
setTempLegCount(Math.min(20, tempLegCount + 1))}
className="w-12 h-12 rounded-2xl border-2 border-gray-100 flex items-center justify-center text-2xl font-bold text-gray-400 hover:border-blue-200 hover:text-blue-600 transition-all"
>
+
Xác nhận
)}
{/* Modal Chỉnh sửa Chặng (Popover) */}
{isEditModalOpen && (
setIsEditModalOpen(false)} />
Chỉnh sửa Chặng
setIsEditModalOpen(false)} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
setIsEditModalOpen(false)}
className="py-4 bg-gray-100 hover:bg-gray-200 text-gray-600 font-bold rounded-2xl transition-all active:scale-95"
>
Hủy
Lưu thay đổi
)}
setIsCommentModalOpen(false)}
locationId={commentLocationId}
locationName={commentLocationName}
isPublicView={isPublicView}
onCommentAdded={() => handleCommentIncrement(commentLocationId)}
onCommentDeleted={() => handleCommentDecrement(commentLocationId)}
/>
);
};