import React, { useState, useEffect } from 'react'; import { X, MapPin, Loader2, Clock } from 'lucide-react'; import { useTourStore } from './useTourStore.js'; export const AddLocationModal = ({ isOpen, onClose, tourId, initialLegId }: { isOpen: boolean, onClose: () => void, tourId: string, initialLegId?: string }) => { const [formData, setFormData] = useState({ name: '', address: '', latitude: 10.7769, longitude: 106.7009, type: 'VISIT', legId: '', plannedStart: '', plannedEnd: '' }); const [isLoading, setIsLoading] = useState(false); // Gom các selector lại để giảm số lượng Hook gọi nội bộ và tăng hiệu năng const { legs, addLocation } = useTourStore(); // 1. Luôn khai báo Hook ở cấp cao nhất, không đặt code logic/return giữa các Hook useEffect(() => { // Chỉ cập nhật nếu giá trị thực sự thay đổi để tránh vòng lặp re-render if (initialLegId && formData.legId !== initialLegId) { setFormData(prev => ({ ...prev, legId: initialLegId })); } }, [initialLegId, isOpen]); // 2. Thực hiện các tính toán phụ trợ const currentLegId = formData.legId || (legs.length > 0 ? legs[0].id : ''); const targetLeg = legs.find(l => l.id === currentLegId); const titleText = initialLegId ? `Thêm địa điểm cho ${targetLeg?.note || `Chặng ${targetLeg?.sequence}`}` : 'Thêm địa điểm mới'; const buttonText = initialLegId ? 'Xác nhận thêm vào chặng' : 'Thêm địa điểm'; // 3. Early return phải nằm SAU tất cả các khai báo Hook if (!isOpen) return null; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setIsLoading(true); try { await addLocation(tourId, { ...formData, legId: currentLegId, latitude: parseFloat(formData.latitude as any), longitude: parseFloat(formData.longitude as any), }); onClose(); } catch (error) { alert('Lỗi khi thêm địa điểm'); } finally { setIsLoading(false); } }; return (

{titleText}

setFormData({...formData, name: e.target.value})} />
setFormData({...formData, address: e.target.value})} />
setFormData({...formData, latitude: e.target.value as any})} />
setFormData({...formData, longitude: e.target.value as any})} />
setFormData({...formData, plannedStart: e.target.value})} />
); };