'use client'; import React, { useState, useEffect } from 'react'; import { Truck, Wallet, Package, Clock, RefreshCw, MapPin, Loader2, } from 'lucide-react'; import { apiFetch } from '@/services/api/client'; import { API_ENDPOINTS } from '@/services/api/config'; import { toast } from 'sonner'; import { format } from 'date-fns'; interface LogisticsDashboard { status: string; is_enabled: boolean; mode: string; wallet_balance_inr: number; active_shipments_count: number; couriers: Array<{ id: number; name: string; mode: string; min_weight_kg: number; estimated_days: number; rate_inr: number; rating: number; }>; recent_dispatches: Array<{ tracking_id: string; order_id: string; courier: string; destination_city: string; status: string; dispatch_date: string; }>; } function inr(amount: number) { return `₹${amount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; } function dateLabel(value?: string) { if (!value) return '—'; const date = new Date(value); if (Number.isNaN(date.getTime())) return '—'; return format(date, 'dd-MMM-yyyy'); } export default function LogisticsDashboardPage() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [pickupPincode, setPickupPincode] = useState(''); const [deliveryPincode, setDeliveryPincode] = useState(''); const [weightKg, setWeightKg] = useState(0.5); const [calculatedRates, setCalculatedRates] = useState(null); const fetchData = async () => { try { setLoading(true); const res = await apiFetch(API_ENDPOINTS.SHIPPING_DASHBOARD); if (res) { setData(res); setCalculatedRates(res.couriers || []); } } catch (err: unknown) { console.error('Failed to load logistics dashboard:', err); toast.error('Failed to load logistics information'); } finally { setLoading(false); } }; useEffect(() => { fetchData(); }, []); const handleCalculateRate = (e: React.FormEvent) => { e.preventDefault(); if (!pickupPincode || !deliveryPincode) { toast.error('Please specify valid 6-digit pincodes'); return; } if (data?.couriers) { const adjusted = data.couriers.map(c => ({ ...c, rate_inr: Math.round(c.rate_inr * (weightKg <= 0.5 ? 1 : 1 + (weightKg - 0.5) * 0.8)) })); setCalculatedRates(adjusted); toast.success('Courier rates calculated successfully'); } }; const dataCardShell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const fieldClass = 'w-full h-9 px-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary'; const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5'; const primaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50'; const couriers = data?.couriers || []; const avgDays = couriers.length ? couriers.reduce((sum, courier) => sum + (courier.estimated_days || 0), 0) / couriers.length : null; const dispatches = data?.recent_dispatches || []; return (

Shiprocket

{data?.mode && ( {data.mode} )} {data && ( {data.is_enabled ? 'Enabled' : 'Disabled'} )}

Wallet

{loading ? '—' : inr(data?.wallet_balance_inr ?? 0)}

Active shipments

{loading ? '—' : data?.active_shipments_count ?? 0}

Couriers

{loading ? '—' : couriers.length}

Avg estimate

{loading ? '—' : avgDays === null ? '—' : `${avgDays.toFixed(1)} days`}

Rate check

setPickupPincode(e.target.value.replace(/\D/g, '').slice(0, 6))} className={`${fieldClass} pl-8`} />
setDeliveryPincode(e.target.value.replace(/\D/g, '').slice(0, 6))} className={`${fieldClass} pl-8`} />
{weightKg.toFixed(1)} kg
setWeightKg(parseFloat(e.target.value))} className="w-full accent-primary cursor-pointer" />

Couriers

{loading ? (
) : (
{(calculatedRates || []).length === 0 ? ( ) : (calculatedRates || []).map((courier) => ( ))}
Courier Mode Days Rate Rating
No couriers
{courier.name} {courier.mode} {courier.estimated_days} {inr(courier.rate_inr)} {courier.rating}
)}

Recent dispatches

{loading ? (
) : (
{dispatches.length === 0 ? ( ) : dispatches.map((dispatch) => ( ))}
Tracking Order Courier City Status Dispatched
No dispatches
{dispatch.tracking_id} {dispatch.order_id} {dispatch.courier} {dispatch.destination_city || '—'} {dispatch.status} {dateLabel(dispatch.dispatch_date)}
)}
); }