import { MapPin, Plus, Eye, Calendar, Building2, Loader2, ArrowRight } from 'lucide-react'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Textarea } from '@/components/ui/textarea'; import { useState, useEffect } from 'react'; import { User as UserType } from '@/lib/mock-data'; import { toast } from 'sonner'; import { dealerService } from '@/services/dealer.service'; import { masterService } from '@/services/master.service'; import { formatDateTime } from '@/components/ui/utils'; interface DealerRelocationPageProps { currentUser: UserType | null; onViewDetails?: (id: string) => void; } const getStatusColor = (status: string) => { if (status === 'Completed') return 'bg-green-100 text-green-700 border-green-300'; if (status.includes('Review') || status.includes('Pending')) return 'bg-yellow-100 text-yellow-700 border-yellow-300'; if (status.includes('Rejected') || status.includes('Revoked')) return 'bg-red-100 text-red-700 border-red-300'; return 'bg-slate-100 text-slate-700 border-slate-300'; }; const getApiErrorMessage = (error: any, fallback: string) => error?.response?.data?.message || error?.data?.message || error?.message || fallback; export function DealerRelocationPage({ onViewDetails }: DealerRelocationPageProps) { const [isDialogOpen, setIsDialogOpen] = useState(false); const [selectedOutlet, setSelectedOutlet] = useState(null); const [newCity, setNewCity] = useState(''); const [newState, setNewState] = useState(''); const [newAddress, setNewAddress] = useState(''); const [reason, setReason] = useState(''); const [distance, setDistance] = useState(''); const [propertyType, setPropertyType] = useState(''); const [expectedDate, setExpectedDate] = useState(''); const [newLat, setNewLat] = useState(''); const [newLong, setNewLong] = useState(''); // State/District dropdown data const [states, setStates] = useState([]); const [districts, setDistricts] = useState([]); const [selectedStateId, setSelectedStateId] = useState(''); const [selectedDistrictId, setSelectedDistrictId] = useState(''); const [masterDataLoading, setMasterDataLoading] = useState(false); const [outlets, setOutlets] = useState([]); const [requests, setRequests] = useState([]); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); useEffect(() => { fetchData(); fetchMasterData(); }, []); // Filter districts based on selected state const filteredDistricts = selectedStateId ? districts.filter(d => d.stateId === selectedStateId) : districts; const fetchData = async () => { try { setLoading(true); const dashboard = await dealerService.getDashboardData(); const relocationRes = await dealerService.getRelocationRequests(); setOutlets(dashboard.outlets || []); setRequests(relocationRes.requests || []); } catch (error) { console.error('Fetch relocation data error:', error); toast.error(getApiErrorMessage(error, 'Failed to load outlets and requests')); } finally { setLoading(false); } }; const fetchMasterData = async () => { try { setMasterDataLoading(true); const [statesRes, districtsRes] = await Promise.all([ masterService.getStates().catch(() => ({ success: false })) as Promise, masterService.getDistricts({ limit: 'all' }).catch(() => ({ success: false })) as Promise ]); const statesData = statesRes?.success ? (statesRes.data?.states || statesRes.data || []) : []; const districtsData = districtsRes?.success ? (districtsRes.data?.districts || districtsRes.data || []) : []; setStates(statesData); setDistricts(districtsData); } catch (error) { console.error('Fetch master data error:', error); toast.error(getApiErrorMessage(error, 'Failed to load master data')); } finally { setMasterDataLoading(false); } }; const handleStateChange = (stateId: string) => { setSelectedStateId(stateId); setSelectedDistrictId(''); // Reset district when state changes const selectedState = states.find(s => s.id === stateId); if (selectedState) { setNewState(selectedState.name); } }; const handleDistrictChange = (districtId: string) => { setSelectedDistrictId(districtId); const selectedDistrict = districts.find(d => d.id === districtId); if (selectedDistrict) { setNewCity(selectedDistrict.name); } }; const handleSubmitRequest = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedOutlet) { toast.error('Please select an outlet'); return; } if (!newCity.trim() || !newState.trim() || !newAddress.trim()) { toast.error('Please provide complete relocation details'); return; } if (!reason.trim()) { toast.error('Please provide a reason for relocation'); return; } if (!distance.trim() || !propertyType || !expectedDate) { toast.error('Please fill all mandatory fields (Distance, Property Type, Date)'); return; } try { setSubmitting(true); const payload = { outletId: selectedOutlet.id, relocationType: 'Intercity', currentAddress: selectedOutlet.address || '', currentCity: selectedOutlet.city || '', currentState: selectedOutlet.state || '', newAddress, newCity, newState, newDistrictId: selectedDistrictId || null, newStateId: selectedStateId || null, distance, reason, propertyType, proposedDate: expectedDate, proposedLatitude: newLat ? parseFloat(newLat) : null, proposedLongitude: newLong ? parseFloat(newLong) : null, currentLatitude: selectedOutlet.latitude || null, currentLongitude: selectedOutlet.longitude || null }; await dealerService.submitRelocationRequest(payload); toast.success(`Relocation request submitted successfully for ${selectedOutlet.name}`); setIsDialogOpen(false); fetchData(); // Refresh list // Reset form setSelectedOutlet(null); setNewCity(''); setNewState(''); setNewAddress(''); setReason(''); setDistance(''); setPropertyType(''); setExpectedDate(''); setNewLat(''); setNewLong(''); if (onViewDetails) { fetchData(); } } catch (error) { console.error('Submit relocation error:', error); toast.error(getApiErrorMessage(error, 'Failed to submit relocation request')); } finally { setSubmitting(false); } }; const stats = [ { title: 'Total Requests', value: requests.length, icon: MapPin, color: 'bg-blue-500', }, { title: 'Pending', value: requests.filter(r => r.status !== 'Completed' && r.status !== 'Rejected').length, icon: Calendar, color: 'bg-yellow-500', }, { title: 'Approved', value: requests.filter(r => r.status === 'Completed').length, icon: Building2, color: 'bg-green-500', }, ]; return (
{/* Loading Overlay */} {loading && (
)} {!loading && ( <> {/* Header */}

Relocation Requests

Request to relocate your existing dealership or studio to a new location

Submit Relocation Request Provide details about the outlet you want to relocate and its proposed new location
{/* Select Outlet */}
{selectedOutlet && (

Current Location

{selectedOutlet.location}

)} {/* New Location Details - State/District Dropdowns */}