import React, { useState, useEffect } from 'react'; import { XMarkIcon, MapPinIcon, WrenchScrewdriverIcon, BeakerIcon } from '@heroicons/react/24/outline'; import PropertyMap from '../Maps/PropertyMap'; import toast from 'react-hot-toast'; const ApplicationPlanModal = ({ onClose, properties, products, equipment, nozzles, selectedPropertyDetails, onPropertySelect, editingPlan, onSubmit }) => { const [selectedPropertyId, setSelectedPropertyId] = useState(''); const [selectedAreas, setSelectedAreas] = useState([]); const [selectedEquipmentId, setSelectedEquipmentId] = useState(''); const [selectedNozzleId, setSelectedNozzleId] = useState(''); const [selectedProducts, setSelectedProducts] = useState([]); const [applicationType, setApplicationType] = useState(''); const [plannedDate, setPlannedDate] = useState(''); const [notes, setNotes] = useState(''); const [loading, setLoading] = useState(false); // Calculate map center from property or sections const mapCenter = React.useMemo(() => { // First try to use property coordinates if (selectedPropertyDetails?.latitude && selectedPropertyDetails?.longitude) { return [selectedPropertyDetails.latitude, selectedPropertyDetails.longitude]; } // Fall back to calculating center from sections if (selectedPropertyDetails?.sections?.length > 0) { let totalLat = 0; let totalLng = 0; let pointCount = 0; selectedPropertyDetails.sections.forEach(section => { let polygonData = section.polygonData; if (typeof polygonData === 'string') { try { polygonData = JSON.parse(polygonData); } catch (e) { return; } } if (polygonData?.coordinates?.[0]) { polygonData.coordinates[0].forEach(([lat, lng]) => { totalLat += lat; totalLng += lng; pointCount++; }); } }); if (pointCount > 0) { return [totalLat / pointCount, totalLng / pointCount]; } } // Default center return [39.8283, -98.5795]; }, [selectedPropertyDetails]); // Initialize form with editing data if provided useEffect(() => { if (editingPlan) { setSelectedPropertyId(editingPlan.propertyId || ''); setSelectedAreas(editingPlan.selectedAreas || []); setSelectedEquipmentId(editingPlan.equipmentId || ''); setSelectedNozzleId(editingPlan.nozzleId || ''); setSelectedProducts(editingPlan.products || []); setPlannedDate(editingPlan.plannedDate || ''); setNotes(editingPlan.notes || ''); } }, [editingPlan]); // Handle property selection const handlePropertyChange = async (propertyId) => { setSelectedPropertyId(propertyId); setSelectedAreas([]); // Clear selected areas when property changes if (propertyId && onPropertySelect) { await onPropertySelect(propertyId); } }; // Debug logging React.useEffect(() => { console.log('ApplicationPlanModal - selectedPropertyDetails:', selectedPropertyDetails); console.log('ApplicationPlanModal - mapCenter:', mapCenter); console.log('ApplicationPlanModal - sections:', selectedPropertyDetails?.sections); }, [selectedPropertyDetails, mapCenter]); // Handle area selection on map const handleAreaClick = (area) => { setSelectedAreas(prev => { if (prev.includes(area.id)) { return prev.filter(id => id !== area.id); } else { return [...prev, area.id]; } }); }; // Add product to plan (for liquid tank mixes) const addProduct = () => { setSelectedProducts(prev => [...prev, { uniqueId: '', productId: null, userProductId: null, productName: '', productBrand: '', productType: applicationType, rateAmount: '', rateUnit: applicationType === 'granular' ? 'lb/1000sqft' : 'oz/1000sqft', isUserProduct: false }]); }; // Handle application type change const handleApplicationTypeChange = (type) => { setApplicationType(type); // Clear products when switching type setSelectedProducts([]); // Add initial product setTimeout(() => { setSelectedProducts([{ uniqueId: '', productId: null, userProductId: null, productName: '', productBrand: '', productType: type, rateAmount: '', rateUnit: type === 'granular' ? 'lb/1000sqft' : 'oz/1000sqft', isUserProduct: false }]); }, 0); }; // Remove product from plan const removeProduct = (index) => { setSelectedProducts(prev => prev.filter((_, i) => i !== index)); }; // Update product in plan const updateProduct = (index, field, value) => { setSelectedProducts(prev => prev.map((product, i) => i === index ? { ...product, [field]: value } : product )); }; // Handle form submission const handleSubmit = async (e) => { e.preventDefault(); // Validation if (!selectedPropertyId) { toast.error('Please select a property'); return; } if (selectedAreas.length === 0) { toast.error('Please select at least one area'); return; } if (!selectedEquipmentId) { toast.error('Please select equipment'); return; } if (selectedProducts.length === 0) { toast.error('Please add at least one product'); return; } if (!plannedDate) { toast.error('Please select a planned date'); return; } // Validate products have required fields for (const product of selectedProducts) { if (!product.productId && !product.userProductId) { toast.error('Please select a product for all entries'); return; } if (!product.rateAmount) { toast.error('Please enter rate amount for all products'); return; } } setLoading(true); try { const planData = { propertyId: parseInt(selectedPropertyId), selectedAreas, equipmentId: selectedEquipmentId, nozzleId: selectedNozzleId || null, products: selectedProducts, plannedDate, notes }; await onSubmit(planData); onClose(); } catch (error) { console.error('Failed to submit plan:', error); toast.error('Failed to save application plan'); } finally { setLoading(false); } }; return (
{/* Header */}

{editingPlan ? 'Edit Application Plan' : 'Plan New Application'}

{/* Left Column - Form */}
{/* Property Selection */}
{/* Equipment Selection */}
{/* Nozzle Selection (for sprayers) */} {selectedEquipmentId && equipment.find(eq => eq.id == selectedEquipmentId)?.type === 'sprayer' && (
)} {/* Planned Date */}
setPlannedDate(e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2" required />
{/* Application Type */}
{/* Products */}
{applicationType === 'liquid' && ( )}
{selectedProducts.map((product, index) => (
{/* Product Selection */}
{/* Rate Input */}
updateProduct(index, 'rateAmount', e.target.value)} className="w-full border border-gray-300 rounded px-3 py-2" required />
{/* Remove Button */} {applicationType === 'liquid' && selectedProducts.length > 1 && (
)}
))} {selectedProducts.length === 0 && (

{applicationType ? `Select a ${applicationType} product to continue` : 'Select application type first'}

)}
{/* Notes */}