'use client'; import React, { useState, useEffect } from 'react'; import { Navigation, Wallet, Package, Clock, RefreshCw, MapPin, Loader2, Printer, ExternalLink, ShieldAlert, ArrowRight, Sparkles, } 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'; import { LogisticsHeaderNav } from '@/components/logistics/LogisticsHeaderNav'; interface DelhiveryDashboard { status: string; is_enabled: boolean; mode: string; client_cms: string; pickup_location: string; pickup_pin: string; wallet: { balance_inr: number; currency: string; is_trial_credit: boolean; status: string; }; shipment_counts: { ready_to_ship: number; in_transit: number; out_for_delivery: number; delivered: number; rto_returned: number; }; couriers: Array<{ id: number; name: string; mode: string; min_weight_kg: number; estimated_days: number; rate_inr: number; rating: number; cod_supported: boolean; }>; recent_dispatches: Array<{ order_id: string; order_no: string; awb_code: string; courier: string; destination_city: string; destination_pin: string; status: string; fulfillment_status: string; package_weight: number; dispatch_date: string; label_url: string; tracking_url: 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, hh:mm a'); } export default function DelhiveryLogisticsPage() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); // Rate calculator state const [pickupPin, setPickupPin] = useState('560001'); const [deliveryPin, setDeliveryPin] = useState(''); const [weightKg, setWeightKg] = useState(0.5); const [rateLoading, setRateLoading] = useState(false); const [calculatedRates, setCalculatedRates] = useState(null); const fetchData = async () => { try { setLoading(true); const res = await apiFetch(API_ENDPOINTS.DELHIVERY_DASHBOARD); if (res) { setData(res); setCalculatedRates(res.couriers || []); } } catch (err: unknown) { console.error('Failed to load Delhivery dashboard:', err); toast.error('Failed to load Delhivery One logistics information'); } finally { setLoading(false); } }; useEffect(() => { fetchData(); }, []); const handleCalculateRate = async (e: React.FormEvent) => { e.preventDefault(); if (!deliveryPin || deliveryPin.trim().length !== 6) { toast.error('Please enter a valid 6-digit delivery pincode'); return; } try { setRateLoading(true); const res = await apiFetch<{ couriers: DelhiveryDashboard['couriers']; }>(`${API_ENDPOINTS.DELHIVERY_RATES}?delivery_pincode=${deliveryPin}&pickup_pincode=${pickupPin}&weight_kg=${weightKg}`); if (res?.couriers) { setCalculatedRates(res.couriers); toast.success(`Rates calculated for pincode ${deliveryPin}`); } } catch (err: unknown) { toast.error('Failed to calculate shipping rates'); } finally { setRateLoading(false); } }; 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 = calculatedRates || data?.couriers || []; const dispatches = data?.recent_dispatches || []; const counts = data?.shipment_counts || { ready_to_ship: 0, in_transit: 0, out_for_delivery: 0, delivered: 0, rto_returned: 0, }; return (
{/* Page Header */}
D1

Delhivery One Logistics

Trial Mode Auto-Pickup Simulated

Automated Express Fulfillment • CMS Client:{' '} {data?.client_cms?.slice(-12) || 'e97e8488-2ebd'}

{/* Trial Mode Alert Banner */}
Delhivery One is currently running in Trial Mode.{' '} When orders are marked "Ready for delivery" with Delhivery One selected, real AWBs and printable thermal shipping slips are generated immediately. Live billing charges and physical carrier dispatches are suppressed until live API tokens are activated.
{/* Metric Cards */}
{/* Trial Wallet */}

Trial Wallet Balance

{loading ? '—' : inr(data?.wallet.balance_inr ?? 5000)}

Trial Credits Active
{/* Ready to Ship */}

Ready to Dispatch

{loading ? '—' : counts.ready_to_ship}

Manifested & Label Ready
{/* In Transit */}

In Transit / Out for Delivery

{loading ? '—' : counts.in_transit + counts.out_for_delivery}

On road to consignee
{/* Total Delivered */}

Delivered Parcels

{loading ? '—' : counts.delivered}

Successful handovers
{/* Main Grid: Rate Calculator & Available Services */}
{/* Rate Calculator */}

Delhivery Rate & TAT Calculator

setPickupPin(e.target.value)} maxLength={6} className={fieldClass} required />
setDeliveryPin(e.target.value)} maxLength={6} className={fieldClass} required />
setWeightKg(parseFloat(e.target.value) || 0.5)} className={fieldClass} required />
{/* Courier Services Table */}

Available Delhivery Service Lines

Estimated transit time and shipping charges for {weightKg} kg

{couriers.map((c) => ( ))}
Service Tier Mode Est. Transit Rate (INR) COD
{c.name}
{c.mode} {c.estimated_days} {c.estimated_days === 1 ? 'Day' : 'Days'} {inr(c.rate_inr)} {c.cod_supported ? ( Supported ) : ( Prepaid only )}
{/* Recent Delhivery Dispatches */}

Recent Delhivery Shipments

Orders dispatched via Delhivery One automated fulfillment

{dispatches.length === 0 ? (

No Delhivery shipments dispatched yet

When an order is updated to "Ready for delivery" with Delhivery One selected, it will appear here with live AWB tracking and thermal slips.

) : (
{dispatches.map((d) => ( ))}
Order No AWB Code Courier Mode Destination Status Date Actions
{d.order_no} {d.awb_code} {d.courier} {d.destination_city} ({d.destination_pin}) {d.status} {dateLabel(d.dispatch_date)} Label Track
)}
); }