'use client';

import { FormEvent, useState, useEffect, useMemo, useCallback, useRef, Component, ReactNode } from 'react';
import { useSearchParams } from 'next/navigation';
import api from '../../../../lib/api-client';
import { usePlanBalance } from '../../../../hooks/use-plan-balance';
import { SmartSelect } from '../../../../components/ui/smart-select';
import { Input } from '../../../../components/ui/input';
import { Package, School, MapPin, Calendar, Hash, RefreshCw, Search, AlertCircle, CheckCircle, Truck, ChevronDown, Sparkles, Building2, FileText, Lightbulb, Plus, Trash2, List, RefreshCcw, Mic, Camera, Save, CloudOff, Wifi, ScanLine } from 'lucide-react';
import { MobileLayout } from '../../../../components/mobile-layout';
import { useQueryClient, useQuery } from '@tanstack/react-query';
import { useSupplierDirectory } from '../../../../hooks/use-supplier-directory';
import { DeliveryUnitInput, type DeliveryUnit } from '../../../../components/delivery/delivery-unit-input';
import { DeliverySmartAnalysis } from '../../../../components/delivery/delivery-smart-analysis';
import { useSmartForm } from '../../../../hooks/use-smart-form';
import { useSmart } from '../../../../components/smart-context';
import { VoiceNote, useVoiceNoteStorage } from '../../../../components/delivery/voice-note';
import { PhotoProof, usePhotoStorage } from '../../../../components/delivery/photo-proof';
import { useOfflineSync } from '../../../../hooks/use-offline-sync';
import { useDeliveryTemplates, DeliveryTemplate } from '../../../../hooks/use-delivery-templates';
import { useFormRecovery, useHaptic } from '../../../../hooks/use-ux-enhancements';
import { useNetworkStatus } from '../../../../components/ui/network-status';

// Error Boundary for graceful crash recovery
class DeliveryErrorBoundary extends Component<{ children: ReactNode }, { hasError: boolean; error?: Error }> {
  constructor(props: { children: ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Delivery page error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <MobileLayout>
          <div className="flex min-h-[80vh] flex-col items-center justify-center bg-gradient-to-br from-red-50 to-orange-50 p-6">
            <div className="rounded-2xl bg-white p-6 shadow-lg text-center max-w-sm">
              <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-red-100">
                <AlertCircle className="h-8 w-8 text-red-600" />
              </div>
              <h2 className="text-lg font-bold text-slate-900">Something went wrong</h2>
              <p className="mt-2 text-sm text-slate-600">
                The delivery form encountered an error. Please refresh to try again.
              </p>
              <button
                onClick={() => {
                  this.setState({ hasError: false, error: undefined });
                  window.location.reload();
                }}
                className="mt-4 inline-flex items-center gap-2 rounded-xl bg-emerald-600 px-4 py-2 text-sm font-semibold text-white hover:bg-emerald-700"
              >
                <RefreshCcw className="h-4 w-4" />
                Refresh Page
              </button>
            </div>
          </div>
        </MobileLayout>
      );
    }

    return this.props.children;
  }
}

interface School {
  id: number;
  code: string;
  name: string;
  region: string;
  district: string;
}

interface Commodity {
  id: number;
  code: string;
  name: string;
  unit: string;
}

// Multi-commodity delivery entry interface
interface DeliveryEntry {
  id: string; // unique key for React
  commodityId: number;
  commodityName: string;
  quantity: string;
  units: DeliveryUnit[];
  expectedBefore?: number;
  remainingAfter?: number;
}

interface PhotoCaptureMeta {
  stampedAt: string;
  location?: { lat: number; lng: number; accuracy?: number };
  hash: string;
  facesBlurred: boolean;
  source: 'camera' | 'upload';
  tamperRisk: boolean;
}

// Smart rounding helper - rounds to nearest whole number for cleaner display
// Backend allows 6% over-delivery tolerance to accommodate this rounding
const smartRound = (value: number | string): string => {
  const num = typeof value === 'string' ? parseFloat(value) : value;
  if (isNaN(num)) return '0';
  return Math.round(num).toString();
};

const GHANA_REGIONS = [
  "Ahafo", "Ashanti", "Bono", "Bono East", "Central", "Eastern", 
  "Greater Accra", "North East", "Northern", "Oti", "Savannah", 
  "Upper East", "Upper West", "Volta", "Western", "Western North"
];

const MEDIA_MAP_KEY = 'gcx_delivery_media_map';

const getMediaMap = (): Record<string, any> => {
  if (typeof window === 'undefined') return {};
  try {
    return JSON.parse(localStorage.getItem(MEDIA_MAP_KEY) || '{}');
  } catch {
    return {};
  }
};

const saveMediaMap = (map: Record<string, any>) => {
  if (typeof window === 'undefined') return;
  try {
    localStorage.setItem(MEDIA_MAP_KEY, JSON.stringify(map));
  } catch {
    // ignore
  }
};

const extractQuantityFromText = (text: string): string | null => {
  const lines = text.split(/\r?\n/);
  const preferred: number[] = [];
  lines.forEach((line) => {
    if (/qty|quantity|total/i.test(line)) {
      const nums = line.match(/\d+(?:\.\d+)?/g) || [];
      nums.forEach((n) => preferred.push(Number(n)));
    }
  });

  const allNums = text.match(/\d+(?:\.\d+)?/g) || [];
  const parsed = (preferred.length ? preferred : allNums.map(Number))
    .filter((n) => !isNaN(n) && n > 0);

  if (!parsed.length) return null;
  const best = Math.max(...parsed);
  return best ? String(best) : null;
};

function NewDeliveryPage() {
  const searchParams = useSearchParams();
  const preselectedSchoolId = searchParams.get('school_id');
  const queryClient = useQueryClient();
  
  // Fetch active plan period
  const { data: activePlanPeriod } = useQuery({
    queryKey: ['active-plan-period'],
    queryFn: async () => {
      const response = await api.get('/plan-periods');
      const periods = response.data?.data || [];
      return periods.find((p: any) => p.is_active) || periods[0] || { id: 1 };
    },
    staleTime: 5 * 60 * 1000, // 5 minutes
  });

  const planPeriodId = activePlanPeriod?.id || 1;

  const [allSchools, setAllSchools] = useState<School[]>([]);
  const [regions, setRegions] = useState<string[]>([]);
  const [commodities, setCommodities] = useState<Commodity[]>([]);
  const [selectedRegion, setSelectedRegion] = useState<string>('');
  const [schoolId, setSchoolId] = useState<number>();
  const [commodityId, setCommodityId] = useState<number>();
  const [quantity, setQuantity] = useState('');
  const [deliveryUnits, setDeliveryUnits] = useState<DeliveryUnit[]>([]);
  const [deliveryDate, setDeliveryDate] = useState<string>('');
  const [todayDisplay, setTodayDisplay] = useState<string>('');
  const [todayDisplayLong, setTodayDisplayLong] = useState<string>('');
  const {
    suppliers,
    isRefreshing: suppliersRefreshing,
    progressMessage: supplierProgress,
    stats: supplierStats,
    refreshSuppliers,
    lastRefreshed: lastSyncedAt,
    error: suppliersError,
  } = useSupplierDirectory();
  const [selectedSupplierId, setSelectedSupplierId] = useState<number | ''>('');
  const [manualSupplierMode, setManualSupplierMode] = useState(false);
  const [manualSupplierName, setManualSupplierName] = useState('');
  const [remarks, setRemarks] = useState('');
  
  // Contract Context State
  const [contractUom, setContractUom] = useState<string>(''); // e.g. "100kg Bag"
  const [contractUomSize, setContractUomSize] = useState<number>(0); // e.g. 100
  const [contractUomMeasure, setContractUomMeasure] = useState<string>(''); // e.g. "kg"
  const [contractPackageType, setContractPackageType] = useState<string>(''); // e.g. "Bucket", "Bag"
  const [contractNote, setContractNote] = useState<string>('');
  const [calculatedUnitTotal, setCalculatedUnitTotal] = useState<number | null>(null);
  
  const [supplierPrompt, setSupplierPrompt] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [dataLoading, setDataLoading] = useState(true);
  const [message, setMessage] = useState<{ type: 'success' | 'error' | 'warning'; text: string } | null>(null);
  const { trackEvent } = useSmart();
  
  // Multi-commodity mode state
  const [multiCommodityMode, setMultiCommodityMode] = useState(false);
  const [showModePrompt, setShowModePrompt] = useState(false);
  const [deliveryEntries, setDeliveryEntries] = useState<DeliveryEntry[]>([]);
  const [batchSubmitting, setBatchSubmitting] = useState(false);
  const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0, results: [] as { commodity: string; success: boolean; message: string }[] });
  
  // PWA Enhancement hooks
  const { isOnline } = useNetworkStatus();
  const haptic = useHaptic();
  const { queueDelivery, pendingCount, syncAll } = useOfflineSync();
  const { templates, createTemplate, useTemplate } = useDeliveryTemplates();
  const { savePhoto } = usePhotoStorage();
  const { saveVoiceNote } = useVoiceNoteStorage();
  const ocrInputRef = useRef<HTMLInputElement>(null);
  
  // Voice notes and photos state
  const [showVoiceNote, setShowVoiceNote] = useState(false);
  const [showPhotoProof, setShowPhotoProof] = useState(false);
  const [voiceNoteBlob, setVoiceNoteBlob] = useState<Blob | null>(null);
  const [photoBlob, setPhotoBlob] = useState<Blob | null>(null);
  const [photoThumbnail, setPhotoThumbnail] = useState<string | null>(null);
  const [photoMeta, setPhotoMeta] = useState<PhotoCaptureMeta | null>(null);
  const [voiceTranscript, setVoiceTranscript] = useState<string>('');
  const [ocrText, setOcrText] = useState<string>('');
  const [ocrDetectedQty, setOcrDetectedQty] = useState<string | null>(null);
  const [ocrLoading, setOcrLoading] = useState(false);
  const [showSaveTemplate, setShowSaveTemplate] = useState(false);
  const [templateName, setTemplateName] = useState('');
  
  // Form recovery for crash protection - use simpler form state
  const formRecovery = useFormRecovery('new-delivery-form', {
    region: '',
    schoolId: undefined as number | undefined,
    commodityId: undefined as number | undefined,
    quantity: '',
    supplierId: '' as number | '',
    remarks: '',
  });
  
  // Restore form from recovery if needed
  useEffect(() => {
    if (formRecovery.hasRecovered && !schoolId && !commodityId) {
      const recovered = formRecovery.formState;
      if (recovered.region) setSelectedRegion(recovered.region);
      if (recovered.schoolId) setSchoolId(recovered.schoolId);
      if (recovered.commodityId) setCommodityId(recovered.commodityId);
      if (recovered.quantity) setQuantity(recovered.quantity);
      if (recovered.supplierId) setSelectedSupplierId(recovered.supplierId);
      if (recovered.remarks) setRemarks(recovered.remarks);
      setMessage({ type: 'warning', text: 'Form recovered from previous session. Review your data.' });
    }
  }, [formRecovery.hasRecovered]);
  
  // Auto-save form state periodically
  useEffect(() => {
    formRecovery.setFormState({
      region: selectedRegion,
      schoolId,
      commodityId,
      quantity,
      supplierId: selectedSupplierId,
      remarks,
    });
  }, [selectedRegion, schoolId, commodityId, quantity, selectedSupplierId, remarks]);
  
  // Smart Form Integration
  const smartDefaults = useSmartForm('new-delivery', {
    region: '',
    school_id: undefined as number | undefined,
    commodity_id: undefined as number | undefined,
    supplier_id: '' as number | string,
  });

  // Apply smart defaults when available and fields are empty
  useEffect(() => {
    if (smartDefaults.region && !selectedRegion) setSelectedRegion(smartDefaults.region);
    if (smartDefaults.school_id && !schoolId) setSchoolId(smartDefaults.school_id);
    if (smartDefaults.commodity_id && !commodityId) setCommodityId(smartDefaults.commodity_id);
    if (smartDefaults.supplier_id && !selectedSupplierId) {
      const supplierId = typeof smartDefaults.supplier_id === 'number' 
        ? smartDefaults.supplier_id 
        : Number(smartDefaults.supplier_id);
      if (!isNaN(supplierId)) {
        setSelectedSupplierId(supplierId);
      }
    }
  }, [smartDefaults]);

  const { data: balance, isError: balanceError } = usePlanBalance({ 
    plan_period_id: planPeriodId, 
    school_id: schoolId, 
    commodity_id: commodityId 
  });

  // Filter schools by selected region
  const filteredSchools = selectedRegion 
    ? allSchools.filter(s => s.region === selectedRegion)
    : [];

  const selectedSchool = allSchools.find(s => s.id === schoolId);
  const selectedCommodity = commodities.find(c => c.id === commodityId);
  const normalizeSupplierName = (raw: any): string => {
    if (!raw) return '';
    if (typeof raw === 'string') return raw;
    if (typeof raw === 'object' && raw !== null) {
      return String(raw.name || raw.full_name || raw.business_name || raw.id || 'Supplier');
    }
    return String(raw);
  };

  const derivedSupplierName = useMemo(() => {
    if (manualSupplierMode) {
      return manualSupplierName.trim();
    }
    const selected = suppliers.find((supplier) => supplier.id === selectedSupplierId);
    return normalizeSupplierName(selected?.name ?? selected);
  }, [manualSupplierMode, manualSupplierName, suppliers, selectedSupplierId]);

  // Set date values after mount to avoid hydration mismatch
  useEffect(() => {
    const now = new Date();
    setDeliveryDate(now.toISOString().split('T')[0]);
    setTodayDisplay(now.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' }));
    setTodayDisplayLong(now.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }));
  }, []);

  const isSupplierValid = manualSupplierMode
    ? derivedSupplierName.length > 1
    : Boolean(selectedSupplierId);

  const supplierSelectValue = manualSupplierMode
    ? '__manual__'
    : selectedSupplierId !== ''
      ? String(selectedSupplierId)
      : '';
  const supplierSyncedLabel = suppliersRefreshing
    ? (supplierProgress || 'Syncing directory...')
    : (lastSyncedAt
      ? `Synced ${new Date(lastSyncedAt).toLocaleString()}`
      : 'Not synced yet');

  const handleSupplierSelect = (value: string) => {
    if (value === '__manual__') {
      setManualSupplierMode(true);
      setSelectedSupplierId('');
      setSupplierPrompt(null);
      return;
    }
    setManualSupplierMode(false);
    setManualSupplierName('');
    setSelectedSupplierId(value ? Number(value) : '');
    setSupplierPrompt(null);
  };

  const handleManualMode = () => {
    setManualSupplierMode(true);
    setSelectedSupplierId('');
    setSupplierPrompt(null);
  };

  const handleSupplierRefresh = async () => {
    // Force refresh to bypass cache and trigger live API sync
    const result = await refreshSuppliers(true);
    if (result.status === 'cooldown') {
      const seconds = Math.ceil(result.retryInMs / 1000);
      setSupplierPrompt(`${result.message} Try again in ${seconds}s.`);
      return;
    }
    setSupplierPrompt(result.message);
  };

  // Load schools and commodities on mount
  useEffect(() => {
    let cancelled = false;
    let retryTimer: ReturnType<typeof setTimeout> | null = null;
    const MAX_AUTO_RETRIES = 2;
    const RETRY_DELAY_MS = 1500;

    const loadData = async (attempt = 0) => {
      if (cancelled) return;

      const token = localStorage.getItem('gcx_fshs_token');
      console.log('Checking auth - Token exists:', !!token);

      if (!token) {
        console.log('No token found, redirecting to login');
        setMessage({ type: 'error', text: 'You need to login first. Redirecting...' });
        setDataLoading(false);
        setTimeout(() => {
          if (!cancelled) {
            window.location.href = '/login';
          }
        }, 1500);
        return;
      }

      try {
        if (attempt === 0) {
          setDataLoading(true);
        }
        console.log(`Loading schools and commodities (attempt ${attempt + 1})...`);

        const [schoolsRes, commoditiesRes] = await Promise.all([
          api.get('/schools?per_page=1000'),
          api.get('/commodities?per_page=100')
        ]);

        if (cancelled) return;

        console.log('Data loaded successfully');

        const schoolsData = schoolsRes.data.data || [];

        const normalizedSchools = schoolsData.map((school: School) => {
          const normalizedRegion = GHANA_REGIONS.find(r => 
            r.toLowerCase() === (school.region || '').trim().toLowerCase()
          );
          return normalizedRegion ? { ...school, region: normalizedRegion } : school;
        });

        setAllSchools(normalizedSchools);

        console.log('Total schools loaded:', normalizedSchools.length);
        console.log('Sample school regions:', normalizedSchools.slice(0, 10).map((s: School) => s.region));

        setRegions(GHANA_REGIONS);

        const cleanedCommodities = (commoditiesRes.data.data || []).map((commodity: Commodity) => ({
          ...commodity,
          name: commodity.name.replace(/\s*\([^)]*\)\s*$/g, '').trim()
        }));
        setCommodities(cleanedCommodities);

        if (preselectedSchoolId) {
          const school = normalizedSchools.find((s: School) => s.id === Number(preselectedSchoolId));
          if (school) {
            setSelectedRegion(school.region);
            setSchoolId(school.id);
          }
        }

        setMessage(null);
        setDataLoading(false);
      } catch (err: any) {
        if (cancelled) return;
        console.error('Failed to load master data:', err);

        const status = err.response?.status;
        const retryable = !status || status >= 500;

        if (retryable && attempt < MAX_AUTO_RETRIES) {
          console.warn('Transient data load failure, auto-refreshing...', { attempt: attempt + 1, status });
          if (retryTimer) {
            clearTimeout(retryTimer);
          }
          retryTimer = setTimeout(() => {
            if (!cancelled) {
              loadData(attempt + 1);
            }
          }, RETRY_DELAY_MS);
          return;
        }

        if (status === 401 || status === 403) {
          console.log('Auth error - clearing token and redirecting');
          setMessage({ type: 'error', text: 'Session expired. Please login again.' });
          localStorage.removeItem('gcx_fshs_token');
          localStorage.removeItem('gcx_fshs_user');
          setTimeout(() => {
            if (!cancelled) {
              window.location.href = '/login';
            }
          }, 2000);
        } else {
          setMessage({ type: 'error', text: `Failed to load data: ${err.message}. Please try again.` });
        }

        setDataLoading(false);
      }
    };

    loadData();

    return () => {
      cancelled = true;
      if (retryTimer) {
        clearTimeout(retryTimer);
      }
    };
  }, [preselectedSchoolId]);

  // Check for completed allocation - clear any lingering error messages when allocation is complete
  // The green "Delivery Complete" card in the UI will show the status
  useEffect(() => {
    if (balance) {
      const plannedQty = parseFloat(String(balance.planned_quantity || 0));
      const remainingQty = parseFloat(String(balance.remaining_quantity ?? balance.planned_quantity ?? 0));
      const hasAllocation = plannedQty > 0;
      const isFullyDelivered = hasAllocation && remainingQty <= 0;
      
      // Clear quantity input if allocation is already complete to prevent accidental submissions
      if (isFullyDelivered && quantity) {
        setQuantity('');
      }
    }
  }, [balance, quantity]);

  // Reset school selection when region changes
  const handleRegionChange = (region: string) => {
    setSelectedRegion(region);
    setSchoolId(undefined);
    setCommodityId(undefined);
    setDeliveryUnits([]); // Clear units on region change
    setContractUom(''); 
    setQuantity('');
  };
  
  // Clear units when commodity changes
  useEffect(() => {
     setDeliveryUnits([]);
     setContractUom('');
     setContractUomSize(0);
     setContractUomMeasure('');
     setSupplierPrompt(null);
  }, [commodityId]);

  // Handle changes from the smart unit component
  const handleUnitsChange = useCallback((units: DeliveryUnit[]) => {
    setDeliveryUnits(units);
    if (units.length === 0) {
      setCalculatedUnitTotal(null);
    }
  }, []);

  // Handle auto-normalization from unit component
  const handleNormalizationChange = useCallback((normalizedQty: number, note: string) => {
    setCalculatedUnitTotal(normalizedQty);

    // Only update if the value is different to avoid loops
    setQuantity(prev => {
      const current = parseFloat(prev || '0');
      // If close enough, don't update to avoid cursor jumps
      if (Math.abs(current - normalizedQty) < 0.01) return prev;
      return normalizedQty.toFixed(2);
    });

    if (note) {
      setContractNote(note);
      // Auto-append to remarks if not present
      setRemarks(prev => {
        if (prev.includes(note)) return prev;
        // Remove old auto-notes if they exist (simple check)
        const cleanPrev = prev.split('\n\nReceived:')[0]; 
        return cleanPrev ? `${cleanPrev}\n\n${note}` : note;
      });
    }
  }, []);

  // Multi-commodity mode helpers with ROBUST error handling
  const addCommodityToList = useCallback(() => {
    try {
      // Defensive validation - multiple layers
      if (!commodityId) {
        setMessage({ type: 'warning', text: 'Please select a commodity first.' });
        return;
      }
      if (!quantity || isNaN(parseFloat(quantity)) || parseFloat(quantity) <= 0) {
        setMessage({ type: 'warning', text: 'Please enter a valid quantity.' });
        return;
      }
      if (!selectedCommodity) {
        setMessage({ type: 'warning', text: 'Commodity data not loaded. Please try again.' });
        return;
      }
      
      // Check if commodity already in list
      if (deliveryEntries.some(e => e.commodityId === commodityId)) {
        setMessage({ type: 'warning', text: `${selectedCommodity?.name || 'This commodity'} is already in your delivery list. Remove it first to add again.` });
        return;
      }

      // Safely parse values with fallbacks
      const safeQuantity = String(quantity || '0');
      const safeRemaining = balance?.remaining_quantity != null 
        ? parseFloat(String(balance.remaining_quantity)) 
        : undefined;
      const parsedQty = parseFloat(safeQuantity) || 0;

      const newEntry: DeliveryEntry = {
        id: `${commodityId}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        commodityId: Number(commodityId),
        commodityName: selectedCommodity?.name || `Commodity #${commodityId}`,
        quantity: safeQuantity,
        units: Array.isArray(deliveryUnits) ? [...deliveryUnits] : [],
        expectedBefore: safeRemaining,
        remainingAfter: safeRemaining != null ? Math.max(0, safeRemaining - parsedQty) : undefined,
      };

      setDeliveryEntries(prev => Array.isArray(prev) ? [...prev, newEntry] : [newEntry]);
      
      // Reset commodity-specific fields for next entry
      setCommodityId(undefined);
      setQuantity('');
      setDeliveryUnits([]);
      setCalculatedUnitTotal(null);
      setMessage({ type: 'success', text: `Added ${selectedCommodity?.name || 'commodity'} to delivery list` });
    } catch (error) {
      console.error('Error adding commodity to list:', error);
      setMessage({ type: 'error', text: 'Failed to add commodity. Please try again.' });
    }
  }, [commodityId, quantity, selectedCommodity, deliveryUnits, balance, deliveryEntries]);

  const removeCommodityFromList = useCallback((entryId: string) => {
    try {
      if (!entryId) return;
      setDeliveryEntries(prev => Array.isArray(prev) ? prev.filter(e => e?.id !== entryId) : []);
    } catch (error) {
      console.error('Error removing commodity:', error);
    }
  }, []);

  const clearDeliveryList = useCallback(() => {
    try {
      setDeliveryEntries([]);
      setBatchProgress({ current: 0, total: 0, results: [] });
      setMessage(null);
    } catch (error) {
      console.error('Error clearing list:', error);
      setDeliveryEntries([]);
    }
  }, []);

  const saveEvidenceForDelivery = useCallback(async (deliveryId: string | number) => {
    if (!deliveryId) return;
    const id = String(deliveryId);
    const map = getMediaMap();

    let photoId: string | undefined;
    let voiceId: string | undefined;

    if (photoBlob && photoThumbnail) {
      photoId = await savePhoto(id, photoBlob, photoThumbnail);
    }
    if (voiceNoteBlob) {
      voiceId = await saveVoiceNote(id, voiceNoteBlob);
    }

    map[id] = {
      ...(map[id] || {}),
      photoId,
      voiceId,
      photoMeta,
      transcript: voiceTranscript || undefined,
      ocrText: ocrText || undefined,
      updatedAt: Date.now(),
    };

    saveMediaMap(map);
  }, [photoBlob, photoThumbnail, voiceNoteBlob, photoMeta, voiceTranscript, ocrText, savePhoto, saveVoiceNote]);

  const handleOcrFile = useCallback(async (file: File) => {
    try {
      setOcrLoading(true);
      setOcrDetectedQty(null);
      const { createWorker } = await import('tesseract.js');
      const worker = await createWorker('eng');
      await worker.setParameters({ tessedit_char_whitelist: '0123456789.' });
      const { data } = await worker.recognize(file);
      await worker.terminate();

      const text = data?.text || '';
      setOcrText(text);

      const detected = extractQuantityFromText(text);
      setOcrDetectedQty(detected);
      if (detected && (!quantity || Number(quantity) === 0)) {
        setQuantity(detected);
      }
    } catch (error) {
      console.error('OCR failed:', error);
      setMessage({ type: 'error', text: 'OCR failed. Please try again.' });
    } finally {
      setOcrLoading(false);
    }
  }, [quantity]);

  // Helper function to submit a single delivery with retries
  const submitSingleDelivery = async (entry: DeliveryEntry, retryCount = 0): Promise<{ success: boolean; message: string; data?: any }> => {
    const MAX_RETRIES = 2;
    const RETRY_DELAY = 1000;

    try {
      // Validate entry before submission
      if (!entry || !entry.commodityId || !entry.quantity) {
        return { success: false, message: 'Invalid entry data' };
      }

      // Build payload with defensive checks
      const payload: Record<string, any> = {
        plan_period_id: planPeriodId || 1,
        school_id: Number(schoolId) || 0,
        commodity_id: Number(entry.commodityId) || 0,
        delivery_date: deliveryDate || new Date().toISOString().split('T')[0],
        actual_quantity: parseFloat(String(entry.quantity)) || 0,
        supplier_id: manualSupplierMode ? undefined : (Number(selectedSupplierId) || undefined),
        supplier_name: derivedSupplierName || 'Unknown Supplier',
        remarks: (remarks || '').trim() || undefined,
      };

      if (voiceTranscript) payload.voice_transcript = voiceTranscript;
      if (ocrText) payload.ocr_text = ocrText;
      if (photoMeta) payload.photo_meta = photoMeta;

      // Validate critical fields
      if (!payload.school_id || !payload.commodity_id || payload.actual_quantity <= 0) {
        return { success: false, message: 'Missing required fields' };
      }

      // Add units if present and valid
      if (Array.isArray(entry.units) && entry.units.length > 0) {
        payload.units = entry.units.filter(u => u && typeof u === 'object');
      }

      // If offline, queue the delivery for background sync
      if (!isOnline) {
        haptic.warning();
        const queuedId = queueDelivery({
          plan_period_id: payload.plan_period_id,
          school_id: payload.school_id,
          commodity_id: payload.commodity_id,
          delivery_date: payload.delivery_date,
          actual_quantity: payload.actual_quantity,
          notes: payload.remarks,
          voice_transcript: voiceTranscript || undefined,
          ocr_text: ocrText || undefined,
          photo_meta: photoMeta || undefined,
        });

        if (queuedId) {
          await saveEvidenceForDelivery(queuedId);
        }
        
        return {
          success: true,
          message: `Queued for sync (offline)`,
          data: { offline: true, queued: true }
        };
      }

      // Make API call with timeout
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 30000); // 30s timeout

      try {
        const { data } = await api.post('/deliveries', payload, {
          signal: controller.signal
        });
        clearTimeout(timeoutId);
        haptic.success();

        if (data?.delivery_id) {
          await saveEvidenceForDelivery(data.delivery_id);
        }

        return {
          success: true,
          message: `Saved! Remaining: ${smartRound(data?.remaining_after ?? 0)}`,
          data
        };
      } catch (apiError: any) {
        clearTimeout(timeoutId);
        throw apiError;
      }

    } catch (err: any) {
      // Check if we should retry
      const isNetworkError = !err.response || err.code === 'ECONNABORTED' || err.message?.includes('Network');
      const isServerError = err.response?.status >= 500;

      // If network error, queue for offline sync
      if (isNetworkError && retryCount >= MAX_RETRIES) {
        haptic.warning();
        const queuedId = queueDelivery({
          plan_period_id: planPeriodId || 1,
          school_id: Number(schoolId) || 0,
          commodity_id: Number(entry.commodityId) || 0,
          delivery_date: deliveryDate || new Date().toISOString().split('T')[0],
          actual_quantity: parseFloat(String(entry.quantity)) || 0,
          notes: remarks?.trim() || undefined,
          voice_transcript: voiceTranscript || undefined,
          ocr_text: ocrText || undefined,
          photo_meta: photoMeta || undefined,
        });

        if (queuedId) {
          await saveEvidenceForDelivery(queuedId);
        }
        
        return {
          success: true,
          message: `Queued for sync (network error)`,
          data: { offline: true, queued: true }
        };
      }

      if ((isNetworkError || isServerError) && retryCount < MAX_RETRIES) {
        console.log(`Retrying delivery for ${entry.commodityName} (attempt ${retryCount + 2}/${MAX_RETRIES + 1})`);
        await new Promise(resolve => setTimeout(resolve, RETRY_DELAY * (retryCount + 1)));
        return submitSingleDelivery(entry, retryCount + 1);
      }

      haptic.error();
      // Extract error message safely
      let errorMessage = 'Failed to save';
      try {
        errorMessage = err.response?.data?.error 
          || err.response?.data?.message 
          || err.message 
          || 'Failed to save';
      } catch {
        errorMessage = 'Failed to save';
      }

      return { success: false, message: errorMessage };
    }
  };

  // Submit all entries in batch using the efficient batch endpoint
  const submitBatch = async () => {
    // Pre-flight validation
    try {
      if (!Array.isArray(deliveryEntries) || deliveryEntries.length === 0) {
        setMessage({ type: 'warning', text: 'No items to submit. Add commodities first.' });
        return;
      }
      if (!derivedSupplierName) {
        setMessage({ type: 'error', text: 'Please select or enter a supplier before submitting.' });
        return;
      }
      if (!schoolId) {
        setMessage({ type: 'error', text: 'Please select a school first.' });
        return;
      }
    } catch (validationError) {
      console.error('Validation error:', validationError);
      setMessage({ type: 'error', text: 'Validation failed. Please refresh and try again.' });
      return;
    }

    setBatchSubmitting(true);
    setBatchProgress({ current: 0, total: deliveryEntries.length, results: [] });

    try {
      // Build batch payload with common fields + individual deliveries
      const batchPayload = {
        // Common fields shared by all deliveries
        plan_period_id: planPeriodId || 1,
        school_id: Number(schoolId) || 0,
        delivery_date: deliveryDate || new Date().toISOString().split('T')[0],
        supplier_id: manualSupplierMode ? undefined : (Number(selectedSupplierId) || undefined),
        supplier_name: derivedSupplierName,
        remarks: remarks?.trim() || undefined,
        // Array of individual delivery items
        deliveries: deliveryEntries.map(entry => ({
          commodity_id: Number(entry.commodityId),
          commodity_name: entry.commodityName,
          actual_quantity: parseFloat(String(entry.quantity)) || 0,
          units: entry.units && entry.units.length > 0 ? entry.units : undefined,
        })),
      };

      console.log('Submitting batch delivery:', {
        school_id: batchPayload.school_id,
        supplier: batchPayload.supplier_name,
        items: batchPayload.deliveries.length,
      });

      // Use the batch endpoint (single HTTP call for all items)
      const { data } = await api.post('/deliveries/batch', batchPayload, {
        timeout: 60000, // 60 seconds for batch operations
      });

      haptic.success();

      // Process results from batch response
      const results: { commodity: string; success: boolean; message: string }[] = [];
      const successfulIds: string[] = [];

      if (data?.results && Array.isArray(data.results)) {
        data.results.forEach((result: any, index: number) => {
          const entry = deliveryEntries[index];
          results.push({
            commodity: result.commodity_name || entry?.commodityName || `Item ${index + 1}`,
            success: result.success,
            message: result.message || (result.success ? 'Saved' : 'Failed'),
          });
          if (result.success && entry) {
            successfulIds.push(entry.id);
            // Save evidence if we have delivery_id
            if (result.delivery_id) {
              saveEvidenceForDelivery(result.delivery_id).catch(console.warn);
            }
          }
        });
      }

      setBatchProgress({ 
        current: deliveryEntries.length, 
        total: deliveryEntries.length, 
        results 
      });

      // Safely invalidate caches
      try {
        queryClient.invalidateQueries({ queryKey: ['my-deliveries'] });
        queryClient.invalidateQueries({ queryKey: ['plan-balance'] });
        queryClient.invalidateQueries({ queryKey: ['plan-metrics'] });
      } catch (cacheError) {
        console.warn('Cache invalidation failed:', cacheError);
      }

      const successCount = data?.success_count ?? results.filter(r => r?.success).length;
      const failCount = data?.error_count ?? results.filter(r => !r?.success).length;

      // Update state based on results
      if (failCount === 0 && successCount > 0) {
        setMessage({ 
          type: 'success', 
          text: `✓ All ${successCount} ${successCount === 1 ? 'delivery' : 'deliveries'} saved successfully!` 
        });
        setDeliveryEntries([]);
        // Reset form safely
        try {
          setSelectedSupplierId('');
          setManualSupplierMode(false);
          setManualSupplierName('');
          setRemarks('');
          setVoiceNoteBlob(null);
          setPhotoBlob(null);
          setPhotoThumbnail(null);
          setPhotoMeta(null);
          setVoiceTranscript('');
          setOcrText('');
          setOcrDetectedQty(null);
        } catch (resetError) {
          console.warn('Form reset error:', resetError);
        }

        // Track event safely
        try {
          trackEvent('FORM_SUBMIT', 'new-delivery-batch', {
            region: selectedRegion || '',
            school_id: Number(schoolId) || 0,
            items_count: successCount,
            supplier_id: manualSupplierMode ? undefined : (Number(selectedSupplierId) || undefined)
          });
        } catch (trackError) {
          console.warn('Event tracking failed:', trackError);
        }
      } else if (successCount > 0) {
        setMessage({ 
          type: 'warning', 
          text: `${successCount} saved, ${failCount} failed. Check results below.` 
        });
        // Remove only successful entries
        setDeliveryEntries(prev => 
          Array.isArray(prev) ? prev.filter(e => e && !successfulIds.includes(e.id)) : []
        );
      } else if (failCount > 0) {
        setMessage({ 
          type: 'error', 
          text: `All ${failCount} ${failCount === 1 ? 'delivery' : 'deliveries'} failed. Please check your connection and try again.` 
        });
      }

    } catch (err: any) {
      console.error('Batch submission error:', err);

      // Check if we should fall back to sequential mode
      const isNetworkError = !err.response || err.code === 'ECONNABORTED';
      const isServerError = err.response?.status >= 500;
      const isBatchNotFound = err.response?.status === 404;

      if (isBatchNotFound) {
        // Batch endpoint not available, fall back to sequential
        console.warn('Batch endpoint not available, falling back to sequential mode');
        await submitBatchSequential();
        return;
      }

      if (isNetworkError) {
        // Queue all for offline sync
        haptic.warning();
        let queuedCount = 0;
        for (const entry of deliveryEntries) {
          const queuedId = queueDelivery({
            plan_period_id: planPeriodId || 1,
            school_id: Number(schoolId) || 0,
            commodity_id: Number(entry.commodityId) || 0,
            delivery_date: deliveryDate || new Date().toISOString().split('T')[0],
            actual_quantity: parseFloat(String(entry.quantity)) || 0,
            notes: remarks?.trim() || undefined,
          });
          if (queuedId) queuedCount++;
        }
        setMessage({ 
          type: 'warning', 
          text: `Network error. ${queuedCount} items queued for sync when online.` 
        });
        setDeliveryEntries([]);
      } else {
        haptic.error();
        const errorMessage = err.response?.data?.error || err.response?.data?.message || err.message || 'Batch submission failed';
        setMessage({ type: 'error', text: errorMessage });
      }
    } finally {
      setBatchSubmitting(false);
    }
  };

  // Fallback: Submit entries one by one (legacy sequential mode)
  const submitBatchSequential = async () => {
    const results: { commodity: string; success: boolean; message: string }[] = [];
    const successfulIds: string[] = [];

    for (let i = 0; i < deliveryEntries.length; i++) {
      try {
        const entry = deliveryEntries[i];
        if (!entry) continue;

        setBatchProgress(prev => ({ ...prev, current: i + 1 }));

        const result = await submitSingleDelivery(entry);
        
        results.push({
          commodity: entry.commodityName || `Item ${i + 1}`,
          success: result.success,
          message: result.message
        });

        if (result.success) {
          successfulIds.push(entry.id);
          
          // Track event safely
          try {
            trackEvent('FORM_SUBMIT', 'new-delivery-batch', {
              region: selectedRegion || '',
              school_id: Number(schoolId) || 0,
              commodity_id: entry.commodityId || 0,
              supplier_id: manualSupplierMode ? undefined : (Number(selectedSupplierId) || undefined)
            });
          } catch (trackError) {
            console.warn('Event tracking failed:', trackError);
          }
        }

        setBatchProgress(prev => ({ ...prev, results: [...results] }));
        
        // Small delay between requests
        if (i < deliveryEntries.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      } catch (loopError) {
        console.error(`Error processing entry ${i}:`, loopError);
        results.push({
          commodity: deliveryEntries[i]?.commodityName || `Item ${i + 1}`,
          success: false,
          message: 'Processing error'
        });
      }
    }

    setBatchSubmitting(false);

    // Safely invalidate caches
    try {
      queryClient.invalidateQueries({ queryKey: ['my-deliveries'] });
      queryClient.invalidateQueries({ queryKey: ['plan-balance'] });
      queryClient.invalidateQueries({ queryKey: ['plan-metrics'] });
    } catch (cacheError) {
      console.warn('Cache invalidation failed:', cacheError);
    }

    const successCount = results.filter(r => r?.success).length;
    const failCount = results.filter(r => !r?.success).length;

    // Update state based on results
    if (failCount === 0 && successCount > 0) {
      setMessage({ 
        type: 'success', 
        text: `✓ All ${successCount} ${successCount === 1 ? 'delivery' : 'deliveries'} saved successfully!` 
      });
      setDeliveryEntries([]);
      // Reset form safely
      try {
        setSelectedSupplierId('');
        setManualSupplierMode(false);
        setManualSupplierName('');
        setRemarks('');
        setVoiceNoteBlob(null);
        setPhotoBlob(null);
        setPhotoThumbnail(null);
        setPhotoMeta(null);
        setVoiceTranscript('');
        setOcrText('');
        setOcrDetectedQty(null);
      } catch (resetError) {
        console.warn('Form reset error:', resetError);
      }
    } else if (successCount > 0) {
      setMessage({ 
        type: 'warning', 
        text: `${successCount} saved, ${failCount} failed. Check results below.` 
      });
      // Remove only successful entries
      setDeliveryEntries(prev => 
        Array.isArray(prev) ? prev.filter(e => e && !successfulIds.includes(e.id)) : []
      );
    } else if (failCount > 0) {
      setMessage({ 
        type: 'error', 
        text: `All ${failCount} ${failCount === 1 ? 'delivery' : 'deliveries'} failed. Please check your connection and try again.` 
      });
    }
  };

  // Fetch Contract Details from Real PU API using Supplier Name (not local ID)
  useEffect(() => {
    if (!commodityId || !derivedSupplierName) return;

    const loadContractDetails = async () => {
      const commodityName = commodities.find(c => c.id === Number(commodityId))?.name || '';
      if (!commodityName) return;

      setSupplierPrompt('Checking contract terms...');
      
      try {
        setLoading(true);
        // Using internal proxy due to CORS/Ngrok issues
        const PROXY_URL = '/api/proxy/po';

        console.log('Contract Sync Start (via Proxy):', {
            supplierName: derivedSupplierName,
            commodity: commodityName
        });

        // 1. First, lookup the supplier by name in the PO API to get their API-side ID
        // Note: encode the ENTIRE endpoint param value to ensure query strings inside it (like & in names) don't break the proxy URL parsing
        const lookupEndpoint = `/suppliers/lookup?q=${encodeURIComponent(derivedSupplierName)}`;
        const lookupRes = await fetch(`${PROXY_URL}?endpoint=${encodeURIComponent(lookupEndpoint)}`);
        
        let poApiSupplierId: string | null = null;
        
        if (lookupRes.ok) {
          const lookupData = await lookupRes.json();
          const suggestions = lookupData.data?.suggestions || [];
          const normalizedQuery = derivedSupplierName.toLowerCase().trim();
          
          // Find the best match from suggestions by comparing company names
          // Priority: exact match > contains match > highest confidence
          let bestSuggestion = suggestions.find((s: any) => 
            s.company_name && s.company_name.toLowerCase().trim() === normalizedQuery
          );
          
          if (!bestSuggestion) {
            // Try partial match
            bestSuggestion = suggestions.find((s: any) => 
              s.company_name && (
                s.company_name.toLowerCase().includes(normalizedQuery) ||
                normalizedQuery.includes(s.company_name.toLowerCase())
              )
            );
          }
          
          if (!bestSuggestion && suggestions.length > 0) {
            // Fallback to highest confidence that has a name
            bestSuggestion = suggestions.find((s: any) => s.company_name && s.company_name.length > 0);
          }
          
          if (bestSuggestion && bestSuggestion.supplier_id) {
            poApiSupplierId = bestSuggestion.supplier_id;
            console.log(`Supplier match: "${derivedSupplierName}" -> ${bestSuggestion.company_name} (supplier_id: ${poApiSupplierId})`);
          }
        }
        
        if (!poApiSupplierId) {
          console.log(`Supplier "${derivedSupplierName}" not found in PO API - skipping contract lookup`);
          setSupplierPrompt('Supplier not in contract system');
          setContractUom(''); setContractUomSize(0); setContractUomMeasure('');
          setLoading(false);
          return;
        }

        // 2. Fetch active purchase orders for this supplier via Proxy using the PO API's supplier ID
        // Note: API uses 'Active' status (1), so we remove explicit 'Approved' filter to catch them
        const ordersEndpoint = `/purchase-orders?supplier_id=${poApiSupplierId}`;
        const ordersRes = await fetch(`${PROXY_URL}?endpoint=${encodeURIComponent(ordersEndpoint)}`);
        
        if (!ordersRes.ok) {
            console.error('PO API Error:', ordersRes.status, await ordersRes.text());
            throw new Error(`Contract API Error: ${ordersRes.status}`);
        }
        const ordersData = await ordersRes.json();
        const orders = ordersData.data || [];
        console.log(`PO API Success: Found ${orders.length} orders for supplier ID ${poApiSupplierId}`);
        
        // 3. Search recent orders for this commodity
        let matchFound = false;

        if (Array.isArray(orders)) {
          for (const order of orders) {
            // Need to fetch items if not in list view
            let items = order.items;
            
            if (!items) {
              console.log(`Fetching items for PO #${order.id}`);
              try {
                const itemsEndpoint = `/purchase-orders/${order.id}/items`;
                const detailRes = await fetch(`${PROXY_URL}?endpoint=${encodeURIComponent(itemsEndpoint)}`);
                if (detailRes.ok) {
                  const detailData = await detailRes.json();
                  // API returns { data: { items: [...] } } or { data: [...] }
                  if (detailData.data && !Array.isArray(detailData.data) && Array.isArray(detailData.data.items)) {
                    items = detailData.data.items;
                  } else {
                    items = detailData.data || [];
                  }
                }
              } catch (e) { continue; }
            }

            if (items && Array.isArray(items)) {
              // Fuzzy match the commodity name
              // Map API fields: item_name, unit_of_measure
              const item = items.find((i: any) => 
                (i.item_name || '').toLowerCase().includes(commodityName.toLowerCase()) || 
                commodityName.toLowerCase().includes((i.item_name || '').toLowerCase())
              );
              
              if (item) {
                console.log('Matched Contract Item:', item);
                // Found the contract spec!
                let uomString = item.unit_of_measure || '';

                // DATA CLEANING: Fix corrupted/weird UOM strings (e.g. "(50|-u'70g)")
                if (uomString.includes("|-u'")) {
                    // Convert "(50|-u'70g)" -> "50 units 70g" (Meaning: 1 Carton contains 50 units of 70g)
                    uomString = uomString.replace("|-u'", " units ").replace(/[()]/g, "").trim();
                }

                // Match: "100" "Kg" "Bag" OR "50" "units" "70g"
                const uomMatch = uomString.match(/^(\d+(?:\.\d+)?)\s*([a-zA-Z]+)(?:\s+(.*))?$/);
                
                const parsedSize = uomMatch ? parseFloat(uomMatch[1]) : 1;
                const parsedMeasure = uomMatch ? uomMatch[2].toLowerCase() : 'unit';
                // Extract package type (e.g., "Bucket", "Bag", "Sachet") - clean up singular/plural
                let parsedPackage = uomMatch && uomMatch[3] ? uomMatch[3].trim() : '';
                if (parsedPackage.endsWith('s')) parsedPackage = parsedPackage.slice(0, -1);

                setContractUom(uomString || 'Unit');
                setContractUomSize(parsedSize);
                setContractUomMeasure(parsedMeasure);
                setContractPackageType(parsedPackage); // New state for filtering
                
                // Also update prompt to confirm to user
                setSupplierPrompt(`Contract verified: ${item.order_quantity}x ${uomString}`);
                matchFound = true;
                break;
              }
            }
          }
        }
        
        if (!matchFound) {
           console.log('No contract match found for', commodityName);
           setSupplierPrompt('Contract not found - using standard units');
           // Reset to benign defaults so user isn't blocked
           setContractUom(''); setContractUomSize(0); setContractUomMeasure(''); setContractPackageType('');
        }

      } catch (err) {
        console.error('Failed to sync with PU API:', err);
        setSupplierPrompt('Offline Mode: Contract sync unavailable');
        // Fallback to empty so manual entry works
        setContractUom(''); setContractUomSize(0); setContractUomMeasure(''); setContractPackageType('');
      } finally {
        setLoading(false);
      }
    };

    loadContractDetails();
  }, [commodityId, derivedSupplierName, commodities]);

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setMessage(null);
    setLoading(true);

    try {
      if (!derivedSupplierName) {
        setMessage({ type: 'error', text: 'Please select or enter a supplier before submitting.' });
        setLoading(false);
        return;
      }

      // Intelligent Anomaly Detection
      // If the quantity is significantly higher than the remaining balance (e.g. > 120%), warn the user
      // This prevents "fat finger" errors where users type 1000 instead of 100
      const qty = parseFloat(quantity);
      const remaining = balance ? parseFloat(String(balance.remaining_quantity ?? 0)) : 0;
      
      if (remaining > 0 && qty > remaining * 1.2) {
        const confirmed = window.confirm(
          `⚠️ Unusual Quantity Detected\n\n` +
          `You are entering ${qty}, which is significantly higher than the remaining balance of ${remaining}.\n\n` +
          `Are you sure this is correct?`
        );
        if (!confirmed) {
          setLoading(false);
          return;
        }
      }

      const payload: Record<string, any> = {
        plan_period_id: planPeriodId,
        school_id: Number(schoolId),
        commodity_id: Number(commodityId),
        delivery_date: deliveryDate,
        actual_quantity: parseFloat(quantity),
        supplier_id: manualSupplierMode ? undefined : Number(selectedSupplierId) || undefined,
        supplier_name: derivedSupplierName,
        remarks: remarks.trim() || undefined,
      };

      if (voiceTranscript) payload.voice_transcript = voiceTranscript;
      if (ocrText) payload.ocr_text = ocrText;
      if (photoMeta) payload.photo_meta = photoMeta;
      
      // Include unit details if provided
      if (deliveryUnits.length > 0) {
        payload.units = deliveryUnits;
      }
      
      const { data } = await api.post('/deliveries', payload);
      if (data?.delivery_id) {
        await saveEvidenceForDelivery(data.delivery_id);
      }
      // Track successful submission for learning
      trackEvent('FORM_SUBMIT', 'new-delivery', {
        region: selectedRegion,
        school_id: Number(schoolId),
        commodity_id: Number(commodityId),
        supplier_id: manualSupplierMode ? undefined : Number(selectedSupplierId)
      });

      
      const remainingAfter = parseFloat(String(data.remaining_after || 0));
      const isDeliveryComplete = remainingAfter <= 0;
      const isPendingReview = String(data.review_status || '').toUpperCase() === 'PENDING_REVIEW' || Boolean(data.is_flagged);
      
      let messageType: 'success' | 'error' | 'warning' = 'success';
      let successMessage: string;
      
      if (isPendingReview) {
        messageType = 'warning';
        successMessage = '⚠️ Record Saved but Flagged. The quantity exceeds the expected allocation. It will be reviewed by the Coordinator.';
      } else if (isDeliveryComplete) {
        successMessage = `🎉 Delivery Complete! All ${selectedCommodity?.name || 'commodity'} allocations for this school have been fulfilled.`;
      } else {
        successMessage = `✓ Delivery saved! Remaining balance: ${smartRound(data.remaining_after)} unit`;
        if (data.has_unit_details) {
          successMessage += ` (with ${deliveryUnits.length} unit breakdown${deliveryUnits.length > 1 ? 's' : ''})`;
        }
      }
      
      setMessage({ 
        type: messageType, 
        text: successMessage
      });

      queryClient.invalidateQueries({ queryKey: ['my-deliveries'] });
      queryClient.invalidateQueries({ queryKey: ['plan-balance'] });
      queryClient.invalidateQueries({ queryKey: ['plan-metrics'] });
      
      // Reset form fields
      setQuantity('');
      setDeliveryUnits([]);
      setDeliveryDate(new Date().toISOString().split('T')[0]);
      setSelectedSupplierId('');
      setManualSupplierMode(false);
      setManualSupplierName('');
      setRemarks('');
      setCommodityId(undefined);
      setVoiceNoteBlob(null);
      setPhotoBlob(null);
      setPhotoThumbnail(null);
      setPhotoMeta(null);
      setVoiceTranscript('');
      setOcrText('');
      setOcrDetectedQty(null);

      if (typeof window !== 'undefined') {
        setTimeout(() => window.location.reload(), isDeliveryComplete ? 1500 : 300);
      }
      // We keep the school selected as they might want to record another commodity for the same school
    } catch (err: any) {
      setMessage({ 
        type: 'error', 
        text: err.response?.data?.error || 'Failed to save delivery' 
      });
    } finally {
      setLoading(false);
    }
  };

  const predictedRemaining = balance ? Number(balance.remaining_quantity ?? 0) - Number(quantity || 0) : null;
  
  // Check if allocation is complete (no more deliveries allowed)
  const isAllocationComplete = balance && (() => {
    const plannedQty = parseFloat(String(balance.planned_quantity || 0));
    const remainingQty = parseFloat(String(balance.remaining_quantity ?? balance.planned_quantity ?? 0));
    return plannedQty > 0 && remainingQty <= 0;
  })();

  // Show loading screen while fetching initial data
  if (dataLoading) {
    return (
      <MobileLayout>
        <div className="flex min-h-[80vh] items-center justify-center bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-500">
          <div className="text-center">
            <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-white/20 backdrop-blur-sm">
              <div className="h-12 w-12 animate-spin rounded-full border-4 border-white/30 border-t-white"></div>
            </div>
            <p className="mt-6 text-lg font-medium text-white">Loading...</p>
            <p className="mt-1 text-sm text-white/70">Preparing delivery form</p>
          </div>
        </div>
      </MobileLayout>
    );
  }

  return (
    <MobileLayout>
      <div className="min-h-screen bg-slate-50 pb-6">
        {/* Hero Header */}
        <div className="relative bg-gradient-to-br from-emerald-500 via-teal-600 to-cyan-500 px-4 pb-20 pt-6">
          <div className="absolute inset-0 overflow-hidden">
            <div className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/5"></div>
            <div className="absolute -bottom-10 -left-10 h-40 w-40 rounded-full bg-white/5"></div>
          </div>
          
          <div className="relative">
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm">
                <Truck className="h-6 w-6 text-white" />
              </div>
              <div>
                <h1 className="text-xl font-bold text-white">Record Delivery</h1>
                <p className="text-sm text-white/80">Select school and commodity</p>
              </div>
            </div>
            
            {/* Quick Info Pills */}
            <div className="mt-4 flex flex-wrap gap-2">
              <span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-3 py-1 text-xs font-medium text-white backdrop-blur-sm">
                <Calendar className="h-3 w-3" />
                {todayDisplay || 'Loading...'}
              </span>
              <span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-3 py-1 text-xs font-medium text-white backdrop-blur-sm">
                <MapPin className="h-3 w-3" />
                {selectedRegion || 'Select Region'}
              </span>
            </div>
          </div>
        </div>

        {/* Floating Message Alert */}
        {message && (
          <div className="relative z-10 -mt-14 px-4">
            <div className={`rounded-2xl border px-4 py-3 shadow-lg ${
              message.type === 'success' 
                ? 'border-green-200 bg-green-50 text-green-800' 
                : message.type === 'warning'
                ? 'border-amber-200 bg-amber-50 text-amber-800'
                : 'border-red-200 bg-red-50 text-red-800'
            }`}>
              <div className="flex items-start gap-3">
                {message.type === 'success' ? (
                  <CheckCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-green-500" />
                ) : message.type === 'warning' ? (
                  <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-amber-500" />
                ) : (
                  <AlertCircle className="mt-0.5 h-5 w-5 flex-shrink-0 text-red-500" />
                )}
                <div>
                    <p className={`text-sm font-medium ${message.type === 'warning' ? 'text-base font-bold' : ''}`}>
                        {message.type === 'warning' ? 'Attention Needed' : ''}
                    </p>
                    <p className="text-sm font-medium">{message.text}</p>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Multi-Commodity Mode Prompt - Shows when school & supplier selected */}
        {!multiCommodityMode && !showModePrompt && schoolId && isSupplierValid && (!Array.isArray(deliveryEntries) || deliveryEntries.length === 0) && (
          <div className={`relative z-10 px-4 ${message ? 'mt-4' : '-mt-14'}`}>
            <div className="rounded-2xl border border-violet-200 bg-gradient-to-r from-violet-50 to-indigo-50 p-4 shadow-lg">
              <div className="flex items-start gap-3">
                <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-violet-100">
                  <List className="h-5 w-5 text-violet-600" />
                </div>
                <div className="flex-1">
                  <h3 className="text-sm font-semibold text-violet-900">Recording multiple commodities?</h3>
                  <p className="mt-1 text-xs text-violet-700">
                    Would you like to add multiple commodity deliveries for this school and supplier in one go?
                  </p>
                  <div className="mt-3 flex flex-wrap gap-2">
                    <button
                      type="button"
                      onClick={() => {
                        try {
                          setMultiCommodityMode(true);
                          setShowModePrompt(true);
                          setDeliveryEntries([]); // Ensure clean state
                          setBatchProgress({ current: 0, total: 0, results: [] });
                        } catch (e) {
                          console.error('Mode switch error:', e);
                        }
                      }}
                      className="inline-flex items-center gap-1.5 rounded-lg bg-violet-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-violet-700"
                    >
                      <Plus className="h-3.5 w-3.5" />
                      Yes, add multiple
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        try {
                          setShowModePrompt(true);
                          setMultiCommodityMode(false);
                        } catch (e) {
                          console.error('Mode switch error:', e);
                        }
                      }}
                      className="inline-flex items-center gap-1.5 rounded-lg border border-violet-300 bg-white px-3 py-2 text-xs font-semibold text-violet-700 shadow-sm hover:bg-violet-50"
                    >
                      No, just one
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Multi-Commodity Delivery List */}
        {multiCommodityMode && Array.isArray(deliveryEntries) && deliveryEntries.length > 0 && (
          <div className={`relative z-10 px-4 ${message ? 'mt-4' : '-mt-14'}`}>
            <div className="rounded-2xl border border-emerald-200 bg-white shadow-lg overflow-hidden">
              <div className="border-b border-emerald-100 bg-gradient-to-r from-emerald-50 to-teal-50 px-4 py-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Package className="h-4 w-4 text-emerald-600" />
                    <span className="text-sm font-semibold text-slate-700">
                      Delivery List ({deliveryEntries.length} {deliveryEntries.length === 1 ? 'item' : 'items'})
                    </span>
                  </div>
                  <button
                    type="button"
                    onClick={clearDeliveryList}
                    className="text-xs text-red-600 hover:text-red-700 font-medium"
                  >
                    Clear all
                  </button>
                </div>
              </div>
              <div className="divide-y divide-slate-100 max-h-64 overflow-y-auto">
                {Array.isArray(deliveryEntries) && deliveryEntries.filter(Boolean).map((entry) => (
                  <div key={entry?.id || Math.random()} className="flex items-center justify-between p-3 hover:bg-slate-50">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-900 truncate">{entry?.commodityName || 'Unknown'}</p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs text-slate-500">Qty: <strong className="text-emerald-600">{smartRound(entry?.quantity || 0)}</strong></span>
                        {entry?.expectedBefore != null && (
                          <span className="text-xs text-slate-400">
                            (Before: {smartRound(entry.expectedBefore)} → After: {smartRound(entry?.remainingAfter ?? 0)})
                          </span>
                        )}
                        {Array.isArray(entry?.units) && entry.units.length > 0 && (
                          <span className="inline-flex items-center rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600">
                            {entry.units.length} unit{entry.units.length > 1 ? 's' : ''}
                          </span>
                        )}
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => entry?.id && removeCommodityFromList(entry.id)}
                      className="ml-2 flex h-8 w-8 items-center justify-center rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600"
                      title="Remove from list"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
              {/* Batch Submit Button */}
              <div className="border-t border-slate-100 bg-slate-50 p-3">
                <button
                  type="button"
                  onClick={() => {
                    try {
                      submitBatch();
                    } catch (e) {
                      console.error('Batch submit error:', e);
                      setMessage({ type: 'error', text: 'Submission failed. Please try again.' });
                      setBatchSubmitting(false);
                    }
                  }}
                  disabled={batchSubmitting || !Array.isArray(deliveryEntries) || deliveryEntries.length === 0 || !isSupplierValid}
                  className="w-full rounded-xl bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 px-4 py-3 text-sm font-bold text-white shadow-lg shadow-emerald-500/30 transition-all hover:shadow-xl active:scale-[0.98] disabled:opacity-50 disabled:shadow-none"
                >
                  {batchSubmitting ? (
                    <span className="flex items-center justify-center gap-2">
                      <div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white"></div>
                      Submitting {batchProgress?.current || 0}/{batchProgress?.total || 0}...
                    </span>
                  ) : (
                    <span className="flex items-center justify-center gap-2">
                      <Truck className="h-4 w-4" />
                      Submit All {Array.isArray(deliveryEntries) ? deliveryEntries.length : 0} Deliveries
                    </span>
                  )}
                </button>
                {/* Network status hint */}
                {typeof navigator !== 'undefined' && !navigator.onLine && (
                  <p className="mt-2 text-center text-xs text-amber-600">
                    ⚠️ You appear to be offline. Submissions may fail.
                  </p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Batch Progress Results */}
        {Array.isArray(batchProgress?.results) && batchProgress.results.length > 0 && (
          <div className="relative z-10 mt-4 px-4">
            <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">
              <div className="border-b border-slate-100 bg-slate-50 px-4 py-2">
                <span className="text-xs font-semibold text-slate-600">Submission Results</span>
              </div>
              <div className="divide-y divide-slate-100 max-h-48 overflow-y-auto">
                {batchProgress.results.filter(Boolean).map((result, idx) => (
                  <div key={idx} className={`flex items-center gap-2 px-4 py-2 ${result?.success ? 'bg-green-50' : 'bg-red-50'}`}>
                    {result?.success ? (
                      <CheckCircle className="h-4 w-4 text-green-500 flex-shrink-0" />
                    ) : (
                      <AlertCircle className="h-4 w-4 text-red-500 flex-shrink-0" />
                    )}
                    <span className="text-xs font-medium text-slate-700">{result?.commodity || 'Unknown'}:</span>
                    <span className={`text-xs ${result?.success ? 'text-green-700' : 'text-red-700'}`}>{result?.message || 'No details'}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Main Form Content */}
        <div className={`relative ${message || (multiCommodityMode && Array.isArray(deliveryEntries) && deliveryEntries.length > 0) || (!multiCommodityMode && !showModePrompt && schoolId && isSupplierValid) || (Array.isArray(batchProgress?.results) && batchProgress.results.length > 0) ? 'mt-4' : '-mt-14'} px-4`}>
          <form onSubmit={submit} className="space-y-4">
            {/* Location Selection Card */}
            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
              <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-4 py-3">
                <div className="flex items-center gap-2">
                  <MapPin className="h-4 w-4 text-emerald-600" />
                  <span className="text-sm font-semibold text-slate-700">Location</span>
                </div>
              </div>
              <div className="space-y-4 p-4">
                {/* Region Selection */}
                <SmartSelect
                  label="Region"
                  placeholder="-- Select Region --"
                  options={regions.map(region => ({ value: region, label: region }))}
                  value={selectedRegion}
                  onChange={(val) => handleRegionChange(String(val))}
                  required
                  disabled={loading}
                  helperText={`${regions.length} regions available`}
                  searchable={true}
                />

                {/* School Selection */}
                <SmartSelect
                  label="School"
                  placeholder="-- Select School --"
                  options={filteredSchools.map(school => ({ 
                    value: school.id, 
                    label: `${school.code} - ${school.name}`,
                    sublabel: school.district
                  }))}
                  value={schoolId || ''}
                  onChange={(val) => setSchoolId(Number(val) || undefined)}
                  required
                  disabled={loading || !selectedRegion}
                  helperText={
                    !selectedRegion 
                      ? 'Please select a region first' 
                      : `${filteredSchools.length} schools in ${selectedRegion}`
                  }
                  searchable={true}
                  pageSize={30}
                />

                {/* School Details Card */}
                {selectedSchool && (
                  <div className="rounded-xl border border-emerald-100 bg-gradient-to-r from-emerald-50 to-teal-50 p-4">
                    <div className="flex items-start gap-3">
                      <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-emerald-500">
                        <School className="h-5 w-5 text-white" />
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="truncate font-semibold text-slate-900">{selectedSchool.name}</div>
                        <div className="mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-slate-600">
                          <span className="flex items-center gap-1">
                            <MapPin className="h-3 w-3" />
                            {selectedSchool.region}
                          </span>
                          <span className="flex items-center gap-1">
                            <Hash className="h-3 w-3" />
                            {selectedSchool.code}
                          </span>
                        </div>
                        <div className="mt-1 text-xs text-slate-500">{selectedSchool.district}</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Commodity Selection Card */}
            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
              <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-4 py-3">
                <div className="flex items-center gap-2">
                  <Package className="h-4 w-4 text-emerald-600" />
                  <span className="text-sm font-semibold text-slate-700">Commodity</span>
                </div>
              </div>
              <div className="p-4">
                <SmartSelect
                  label="Select Commodity"
                  placeholder="-- Select Commodity --"
                  options={commodities.map(commodity => ({ 
                    value: commodity.id, 
                    label: commodity.name 
                  }))}
                  value={commodityId || ''}
                  onChange={(val) => setCommodityId(Number(val) || undefined)}
                  required
                  disabled={loading || !schoolId}
                  helperText={!schoolId ? 'Please select a school first' : undefined}
                  searchable={true}
                />
              </div>
            </div>

            {/* Plan Balance Status Card */}
            {balance && selectedCommodity && (() => {
              const plannedQty = parseFloat(String(balance.planned_quantity || 0));
              const remainingQty = parseFloat(String(balance.remaining_quantity ?? balance.planned_quantity ?? 0));
              const hasAllocation = plannedQty > 0;
              const isFullyDelivered = hasAllocation && remainingQty <= 0;
              const deliveredQty = plannedQty - remainingQty;
              const progressPercent = hasAllocation ? Math.min(100, (deliveredQty / plannedQty) * 100) : 0;
              
              // Case 1: No allocation at all (planned = 0)
              if (!hasAllocation) {
                return (
                  <div className="overflow-hidden rounded-2xl border border-amber-200 bg-gradient-to-br from-amber-50 to-orange-50 shadow-sm">
                    <div className="p-4">
                      <div className="flex items-start gap-3">
                        <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-2xl bg-amber-100">
                          <AlertCircle className="h-6 w-6 text-amber-600" />
                        </div>
                        <div>
                          <p className="font-semibold text-amber-800">No Allocation Found</p>
                          <p className="mt-1 text-sm text-amber-700">
                            This school does not have any <span className="font-medium">{selectedCommodity.name}</span> allocated.
                          </p>
                          <p className="mt-2 text-xs text-amber-600">
                            Contact your supervisor if this is an error.
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              }
              
              // Case 2: Allocation exists but fully delivered (remaining = 0)
              if (isFullyDelivered) {
                return (
                  <div className="overflow-hidden rounded-2xl border border-green-200 bg-gradient-to-br from-green-50 to-emerald-50 shadow-sm">
                    <div className="p-4">
                      <div className="flex items-start gap-3">
                        <div className="flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-2xl bg-green-100">
                          <CheckCircle className="h-6 w-6 text-green-600" />
                        </div>
                        <div>
                          <p className="font-semibold text-green-800">✓ Delivery Complete</p>
                          <p className="mt-1 text-sm text-green-700">
                            All <span className="font-medium">{smartRound(plannedQty)}</span> units of <span className="font-medium">{selectedCommodity.name}</span> delivered.
                          </p>
                        </div>
                      </div>
                      {/* Progress bar at 100% */}
                      <div className="mt-4">
                        <div className="h-2 overflow-hidden rounded-full bg-green-200">
                          <div className="h-full w-full rounded-full bg-green-500"></div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              }
              
              // Case 3: Normal - has allocation with remaining balance
              return (
                <div className="overflow-hidden rounded-2xl bg-white shadow-lg shadow-emerald-500/10">
                  <div className="border-b border-slate-100 bg-gradient-to-r from-emerald-50 via-teal-50 to-cyan-50 px-4 py-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <Sparkles className="h-4 w-4 text-emerald-600" />
                        <span className="text-sm font-semibold text-slate-700">Supply Plan Status</span>
                      </div>
                      <span className="rounded-full bg-gradient-to-r from-emerald-500 to-cyan-500 px-2.5 py-0.5 text-xs font-bold text-white shadow-sm">
                        {Math.round(progressPercent)}% Complete
                      </span>
                    </div>
                  </div>
                  <div className="p-4">
                    {/* Progress Bar */}
                    <div className="mb-4">
                      <div className="h-3.5 overflow-hidden rounded-full bg-slate-100 shadow-inner">
                        <div 
                          className="h-full rounded-full bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 shadow-lg transition-all duration-500 progress-bar"
                        ></div>
                      </div>
                      <style jsx>{`
                        .progress-bar {
                          width: ${progressPercent}%;
                        }
                      `}</style>
                    </div>
                    
                    {/* Stats Grid */}
                    <div className="grid grid-cols-2 gap-3">
                      <div className="rounded-xl bg-slate-50 p-3 text-center shadow-sm">
                        <p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Total Expected</p>
                        <p className="mt-1 text-xl font-bold text-slate-900">{smartRound(balance.planned_quantity)}</p>
                      </div>
                      <div className="rounded-xl bg-gradient-to-br from-emerald-50 to-teal-50 p-3 text-center shadow-sm">
                        <p className="text-xs font-semibold uppercase tracking-wide text-emerald-600">Total Remaining</p>
                        <p className="mt-1 text-xl font-bold text-emerald-700">{smartRound(balance.remaining_quantity)}</p>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })()}

            {/* Supplier Card */}
            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
              <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-4 py-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Building2 className="h-4 w-4 text-emerald-600" />
                    <span className="text-sm font-semibold text-slate-700">Supplier</span>
                  </div>
                  <button
                    type="button"
                    onClick={handleSupplierRefresh}
                    disabled={loading || suppliersRefreshing}
                    className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-3 py-1 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    <RefreshCw className={`h-3 w-3 ${suppliersRefreshing ? 'animate-spin' : ''}`} />
                    {suppliersRefreshing ? 'Syncing' : 'Sync'}
                  </button>
                </div>
                <p className="mt-1 text-xs text-slate-500">{supplierSyncedLabel}</p>
              </div>
              <div className="p-4">
                {/* Supplier Select */}
                <SmartSelect
                  placeholder="-- Select Supplier --"
                  options={[
                    ...suppliers.map(supplier => ({ 
                      value: String(supplier.id), 
                      label: normalizeSupplierName(supplier.name ?? supplier),
                      sublabel: supplier.phone ? `📞 ${supplier.phone}` : undefined
                    })),
                    { value: '__manual__', label: '✏️ Enter supplier manually' }
                  ]}
                  value={supplierSelectValue}
                  onChange={(val) => handleSupplierSelect(String(val))}
                  disabled={loading || (suppliersRefreshing && suppliers.length === 0)}
                  searchable={true}
                  pageSize={30}
                />

                {/* Show selected supplier contact */}
                {!manualSupplierMode && selectedSupplierId && (() => {
                  const selectedSupplier = suppliers.find(s => s.id === selectedSupplierId);
                  const supplierName = normalizeSupplierName(selectedSupplier?.name ?? selectedSupplier);
                  if (selectedSupplier?.phone) {
                    return (
                      <div className="mt-3 rounded-xl border border-emerald-100 bg-gradient-to-r from-emerald-50 to-teal-50 p-3">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-sm font-semibold text-slate-900">{supplierName}</p>
                            <p className="mt-0.5 text-xs text-slate-600">
                              {selectedSupplier.region && <span>{selectedSupplier.region} • </span>}
                              📞 {selectedSupplier.phone}
                            </p>
                          </div>
                          <a
                            href={`tel:${selectedSupplier.phone}`}
                            className="flex h-10 w-10 items-center justify-center rounded-full bg-emerald-500 text-white shadow-md transition-transform active:scale-95"
                            title="Call supplier"
                          >
                            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                            </svg>
                          </a>
                        </div>
                      </div>
                    );
                  }
                  return null;
                })()}

                {suppliersError && (
                  <p className="mt-2 text-xs text-red-600">{suppliersError}</p>
                )}
                {supplierPrompt && (
                  <p className="mt-2 text-xs text-slate-600">{supplierPrompt}</p>
                )}
                <p className="mt-2 text-xs text-slate-500">{supplierStats.total} suppliers cached locally</p>

                {/* Not Found Helper */}
                {suppliers.length === 0 && !manualSupplierMode && (
                  <div className="mt-3 rounded-xl border border-amber-200 bg-amber-50 p-3">
                    <div className="flex items-center gap-2 text-sm text-amber-800">
                      <AlertCircle className="h-4 w-4 flex-shrink-0" />
                      <span>Supplier not found?</span>
                    </div>
                    <div className="mt-2 flex flex-wrap gap-2">
                      <button
                        type="button"
                        onClick={handleSupplierRefresh}
                        className="rounded-lg border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-800 shadow-sm"
                        disabled={suppliersRefreshing}
                      >
                        Refresh list
                      </button>
                      <button
                        type="button"
                        onClick={handleManualMode}
                        className="rounded-lg border border-amber-300 bg-white px-3 py-1.5 text-xs font-semibold text-amber-800 shadow-sm"
                      >
                        Enter manually
                      </button>
                    </div>
                  </div>
                )}

                {/* Manual Input */}
                {manualSupplierMode && (
                  <div className="mt-3">
                    <Input
                      label="Manual Supplier Name"
                      type="text"
                      value={manualSupplierName}
                      onChange={(e) => setManualSupplierName(e.target.value)}
                      placeholder="Enter supplier name"
                      required
                      disabled={loading}
                      helperText="Only use this if the supplier is brand new"
                    />
                  </div>
                )}
              </div>
            </div>

            {/* Delivery Details Card */}
            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
              <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-4 py-3">
                <div className="flex items-center gap-2">
                  <FileText className="h-4 w-4 text-emerald-600" />
                  <span className="text-sm font-semibold text-slate-700">Delivery Details</span>
                </div>
              </div>
              <div className="space-y-4 p-4">
                {/* Delivery Date Input */}
                <Input
                  label="Delivery Date"
                  type="date"
                  value={deliveryDate}
                  onChange={(e) => setDeliveryDate(e.target.value)}
                  required
                  disabled={loading || !commodityId}
                  helperText="Select the date of the delivery"
                />

                {/* Quantity Input with Side-by-Side UOM */}
                <div className="space-y-2">
                  <label className="block text-sm font-medium text-slate-700">
                    Actual Quantity Delivered <span className="text-rose-500 ml-1">*</span>
                  </label>
                  <div className="flex gap-2">
                    <div className="relative flex-1">
                      <Input
                        type="number"
                        step="0.01"
                        min="0"
                        value={quantity}
                        onChange={(e) => setQuantity(e.target.value)}
                        placeholder={deliveryUnits && deliveryUnits.length > 0 
                          ? "Auto-calculated..." 
                          : "Enter quantity"}
                        required
                        disabled={loading || !commodityId}
                        className={deliveryUnits && deliveryUnits.length > 0 ? "font-bold text-slate-800" : ""}
                      />
                      {deliveryUnits && deliveryUnits.length > 0 && (
                        <div className="absolute right-3 top-3 flex items-center gap-1.5 rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-bold text-emerald-700 z-10">
                          <Sparkles className="h-3 w-3" />
                          Auto
                        </div>
                      )}
                    </div>
                    {/* Contract UOM Badge */}
                    {contractUom && (
                      <div className="flex shrink-0">
                        <div className="flex h-11 items-center justify-center rounded-lg border border-slate-200 bg-slate-100 px-3 font-medium text-slate-600 shadow-sm" title="Contract Unit of Measure">
                          {contractUom}
                        </div>
                      </div>
                    )}
                  </div>
                  {/* Helper Text (Moved outside Input since we stripped the label) */}
                  {!(deliveryUnits && deliveryUnits.length > 0) && (
                    <p className="text-xs text-slate-500">Enter the total quantity delivered</p>
                  )}
                </div>

                {/* OCR Scan */}
                <div className="rounded-xl border border-slate-200 bg-slate-50 p-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-emerald-100">
                        <ScanLine className="h-4 w-4 text-emerald-600" />
                      </div>
                      <div>
                        <p className="text-sm font-semibold text-slate-700">Scan delivery note (OCR)</p>
                        <p className="text-xs text-slate-500">Auto-detect quantity from receipt</p>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => ocrInputRef.current?.click()}
                      disabled={ocrLoading}
                      className="rounded-lg bg-emerald-600 px-3 py-1.5 text-xs font-semibold text-white shadow-sm hover:bg-emerald-700 disabled:opacity-50"
                    >
                      {ocrLoading ? 'Scanning…' : 'Scan'}
                    </button>
                  </div>

                  <input
                    ref={ocrInputRef}
                    type="file"
                    accept="image/*"
                    title="Scan delivery note"
                    aria-label="Scan delivery note"
                    className="hidden"
                    onChange={async (e) => {
                      const inputEl = e.currentTarget;
                      const file = inputEl?.files?.[0];
                      if (file) {
                        await handleOcrFile(file);
                      }
                      if (inputEl) {
                        inputEl.value = '';
                      }
                    }}
                  />

                  {ocrDetectedQty && (
                    <div className="mt-2 flex items-center justify-between rounded-lg bg-white px-3 py-2 text-xs">
                      <span className="text-slate-700">Detected quantity: <strong>{ocrDetectedQty}</strong></span>
                      <button
                        type="button"
                        onClick={() => setQuantity(ocrDetectedQty)}
                        className="rounded-md bg-emerald-50 px-2 py-1 text-emerald-700 font-semibold"
                      >
                        Use
                      </button>
                    </div>
                  )}

                  {ocrText && (
                    <details className="mt-2 text-xs text-slate-600">
                      <summary className="cursor-pointer">OCR text preview</summary>
                      <pre className="mt-2 whitespace-pre-wrap rounded-lg bg-white p-2 text-[10px] text-slate-600">
                        {ocrText.slice(0, 1200)}
                      </pre>
                    </details>
                  )}
                </div>

                {/* Optional Unit Breakdown */}
                {selectedCommodity && (
                  <DeliveryUnitInput
                    commodityName={selectedCommodity.name}
                    onUnitsChange={handleUnitsChange}
                    disabled={loading}
                    contractUom={contractUom}
                    contractUomSize={contractUomSize}
                    contractUomMeasure={contractUomMeasure}
                    filterByType={contractPackageType}
                    // expectedContractQty={plannedQty} // Can be passed if we had exact row-level plan
                    onNormalizationChange={handleNormalizationChange}
                  />
                )}

                {/* Smart Anomaly Suggestion */}
                {deliveryUnits.length > 0 && calculatedUnitTotal !== null && quantity && !isNaN(parseFloat(quantity)) && Math.abs(parseFloat(quantity) - calculatedUnitTotal) > 0.05 && (
                  <div className="animate-in fade-in slide-in-from-top-2 duration-300 overflow-hidden rounded-xl border border-violet-200 bg-violet-50">
                    <div className="flex items-start gap-3 p-3">
                      <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-violet-100 text-violet-600">
                        <Lightbulb className="h-4 w-4" />
                      </div>
                      <div className="flex-1">
                        <h4 className="text-sm font-semibold text-violet-900">Smart Suggestion: Quantity Discrepancy</h4>
                        <p className="mt-1 text-xs text-violet-700">
                          You entered <strong>{quantity}</strong>, but the unit breakdown sums to <strong>{calculatedUnitTotal.toFixed(2)}</strong>. 
                        </p>
                        <div className="mt-2 flex flex-wrap gap-2">
                          <button
                            type="button"
                            onClick={() => setQuantity(calculatedUnitTotal.toFixed(2))}
                            className="rounded-lg bg-white px-3 py-1.5 text-xs font-medium text-violet-700 shadow-sm ring-1 ring-inset ring-violet-200 hover:bg-violet-50"
                          >
                            Use Calculated ({calculatedUnitTotal.toFixed(2)})
                          </button>
                          <button
                            type="button"
                            onClick={() => {
                              const note = `Verify: Quantity entered as ${quantity} (Breakdown sums to ${calculatedUnitTotal.toFixed(2)}).`;
                              setRemarks(prev => {
                                // Avoid duplicates
                                if (prev.includes(note)) return prev;
                                return prev ? `${prev}\n\n${note}` : note;
                              });
                            }}
                            className="flex items-center gap-1.5 rounded-lg bg-violet-600 px-3 py-1.5 text-xs font-medium text-white shadow-sm hover:bg-violet-700"
                          >
                            <Sparkles className="h-3 w-3" />
                            Add Explanation to Notes
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {/* Remarks */}
                <div>
                  <label className="mb-1.5 block text-sm font-medium text-slate-700">
                    Remarks <span className="text-slate-400">(Optional)</span>
                  </label>
                  <textarea
                    value={remarks}
                    onChange={(e) => setRemarks(e.target.value)}
                    placeholder="Any additional notes about this delivery..."
                    rows={3}
                    disabled={loading}
                    className="w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-900 placeholder-slate-400 transition-all focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 disabled:opacity-50"
                  />
                  <p className="mt-1 text-xs text-slate-500">E.g., delivery conditions, packaging issues, etc.</p>
                </div>
              </div>
            </div>

            {/* Smart Analysis Panel */}
            <DeliverySmartAnalysis
              quantity={Number(quantity)}
              date={deliveryDate}
              commodityName={selectedCommodity?.name}
              isManualSupplier={manualSupplierMode}
              unitCount={deliveryUnits.length}
            />

            {/* Record Date Info */}
            <div className="flex items-center gap-3 rounded-2xl border border-slate-200 bg-white px-4 py-3 shadow-sm">
              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-slate-100">
                <Calendar className="h-5 w-5 text-slate-600" />
              </div>
              <div>
                <span className="text-xs font-medium uppercase tracking-wide text-slate-500">Record Date</span>
                <p className="font-semibold text-slate-900">{todayDisplayLong || 'Loading...'}</p>
              </div>
            </div>

            {/* Voice Notes & Photo Proof Section */}
            <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
              <div className="border-b border-slate-100 bg-gradient-to-r from-slate-50 to-white px-4 py-3">
                <div className="flex items-center gap-2">
                  <Mic className="h-4 w-4 text-emerald-600" />
                  <span className="text-sm font-semibold text-slate-700">Attachments</span>
                  <span className="text-xs text-slate-400">(Optional)</span>
                </div>
              </div>
              <div className="p-4 space-y-3">
                {/* Voice Note Toggle */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-rose-50">
                      <Mic className="h-5 w-5 text-rose-600" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-slate-700">Voice Note</p>
                      <p className="text-xs text-slate-500">Record audio memo</p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => {
                      haptic.light();
                      setShowVoiceNote(!showVoiceNote);
                    }}
                    className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-colors ${
                      showVoiceNote || voiceNoteBlob 
                        ? 'bg-rose-100 text-rose-700' 
                        : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                    }`}
                  >
                    {voiceNoteBlob ? '✓ Recorded' : showVoiceNote ? 'Cancel' : 'Add'}
                  </button>
                </div>
                
                {showVoiceNote && (
                  <div className="rounded-xl border border-rose-100 bg-rose-50/50 p-3">
                    <VoiceNote
                      onRecordingComplete={(blob: Blob, duration: number) => {
                        setVoiceNoteBlob(blob);
                        haptic.success();
                        setShowVoiceNote(false);
                        setMessage({ type: 'success', text: `Voice note recorded (${Math.round(duration)}s)!` });
                      }}
                      onTranscript={(text) => setVoiceTranscript(text)}
                      maxDuration={120}
                    />
                  </div>
                )}

                {/* Photo Proof Toggle */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-50">
                      <Camera className="h-5 w-5 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-slate-700">Photo Proof</p>
                      <p className="text-xs text-slate-500">Capture delivery photo</p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => {
                      haptic.light();
                      setShowPhotoProof(!showPhotoProof);
                    }}
                    className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-colors ${
                      showPhotoProof || photoBlob 
                        ? 'bg-blue-100 text-blue-700' 
                        : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                    }`}
                  >
                    {photoBlob ? '✓ Captured' : showPhotoProof ? 'Cancel' : 'Add'}
                  </button>
                </div>
                
                {showPhotoProof && (
                  <div className="rounded-xl border border-blue-100 bg-blue-50/50 p-3">
                    <PhotoProof
                      onPhotoCapture={(blob: Blob, thumbnail: string, meta: PhotoCaptureMeta) => {
                        setPhotoBlob(blob);
                        setPhotoThumbnail(thumbnail);
                        setPhotoMeta(meta);
                        haptic.success();
                        setShowPhotoProof(false);
                        setMessage({ type: 'success', text: 'Photo captured!' });
                      }}
                      maxSizeKB={500}
                      quality={0.8}
                    />
                  </div>
                )}

                {/* Attachment Summary */}
                {(voiceNoteBlob || photoBlob || ocrDetectedQty || voiceTranscript) && (
                  <div className="flex flex-col gap-1 rounded-lg bg-emerald-50 px-3 py-2">
                    <div className="flex items-center gap-2">
                      <CheckCircle className="h-4 w-4 text-emerald-600" />
                      <span className="text-xs text-emerald-700">
                        {[voiceNoteBlob && 'Voice note', photoBlob && 'Photo'].filter(Boolean).join(' and ')} attached
                      </span>
                    </div>
                    {voiceTranscript && (
                      <span className="text-[10px] text-emerald-700">Transcript captured</span>
                    )}
                    {ocrDetectedQty && (
                      <span className="text-[10px] text-emerald-700">OCR qty: {ocrDetectedQty}</span>
                    )}
                  </div>
                )}
              </div>
            </div>

            {/* Save as Template Option */}
            {schoolId && commodityId && (
              <div className="overflow-hidden rounded-2xl bg-white shadow-sm">
                <div className="p-4">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-teal-50">
                        <Save className="h-5 w-5 text-teal-600" />
                      </div>
                      <div>
                        <p className="text-sm font-medium text-slate-700">Save as Template</p>
                        <p className="text-xs text-slate-500">Reuse this delivery pattern</p>
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        haptic.light();
                        setShowSaveTemplate(!showSaveTemplate);
                      }}
                      className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-colors ${
                        showSaveTemplate 
                          ? 'bg-teal-100 text-teal-700' 
                          : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                      }`}
                    >
                      {showSaveTemplate ? 'Cancel' : 'Save'}
                    </button>
                  </div>
                  
                  {showSaveTemplate && (
                    <div className="mt-3 space-y-2">
                      <input
                        type="text"
                        value={templateName}
                        onChange={(e) => setTemplateName(e.target.value)}
                        placeholder="Template name (e.g., 'Weekly Rice Delivery')"
                        className="w-full rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm text-slate-900 placeholder-slate-400 transition-all focus:border-teal-500 focus:outline-none focus:ring-2 focus:ring-teal-500/20"
                      />
                      <button
                        type="button"
                        onClick={() => {
                          if (templateName.trim() && schoolId && commodityId) {
                            createTemplate(templateName.trim(), {
                              school_id: schoolId,
                              school_name: selectedSchool?.name,
                              commodity_id: commodityId,
                              commodity_name: selectedCommodity?.name,
                              supplier_id: typeof selectedSupplierId === 'number' ? selectedSupplierId : undefined,
                              supplier_name: derivedSupplierName || undefined,
                            });
                            haptic.success();
                            setMessage({ type: 'success', text: `Template "${templateName}" saved!` });
                            setTemplateName('');
                            setShowSaveTemplate(false);
                          }
                        }}
                        disabled={!templateName.trim()}
                        className="w-full rounded-xl bg-teal-500 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-teal-600 disabled:opacity-50"
                      >
                        Save Template
                      </button>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* Offline Status Banner */}
            {!isOnline && (
              <div className="flex items-center gap-3 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 shadow-sm">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-amber-100">
                  <CloudOff className="h-5 w-5 text-amber-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium text-amber-800">You're offline</p>
                  <p className="text-xs text-amber-600">Deliveries will be queued and synced when online</p>
                </div>
              </div>
            )}

            {/* Pending Sync Indicator */}
            {pendingCount > 0 && (
              <div className="flex items-center gap-3 rounded-2xl border border-blue-200 bg-blue-50 px-4 py-3 shadow-sm">
                <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-100">
                  <Wifi className="h-5 w-5 text-blue-600" />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-medium text-blue-800">{pendingCount} delivery{pendingCount > 1 ? 'ies' : ''} pending sync</p>
                  <p className="text-xs text-blue-600">Will sync automatically when connection improves</p>
                </div>
              </div>
            )}

            {/* Submit Button - changes based on mode */}
            {multiCommodityMode ? (
              <div className="space-y-3">
                {/* Add to List Button */}
                <button
                  type="button"
                  onClick={() => {
                    try {
                      addCommodityToList();
                    } catch (e) {
                      console.error('Add to list error:', e);
                      setMessage({ type: 'error', text: 'Failed to add. Please try again.' });
                    }
                  }}
                  disabled={loading || batchSubmitting || !schoolId || !commodityId || !quantity || !isSupplierValid || isAllocationComplete}
                  className="w-full rounded-2xl bg-gradient-to-r from-violet-500 to-indigo-500 px-6 py-4 text-base font-bold text-white shadow-xl shadow-violet-500/30 transition-all hover:shadow-2xl hover:shadow-violet-500/40 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50 disabled:shadow-none"
                >
                  <span className="flex items-center justify-center gap-2">
                    <Plus className="h-5 w-5" />
                    Add to Delivery List
                  </span>
                </button>
                
                {/* Switch to Single Mode */}
                <button
                  type="button"
                  onClick={() => {
                    try {
                      setMultiCommodityMode(false);
                      setShowModePrompt(true);
                    } catch (e) {
                      console.error('Mode switch error:', e);
                    }
                  }}
                  disabled={batchSubmitting}
                  className="w-full text-center text-xs text-slate-500 hover:text-slate-700 disabled:opacity-50"
                >
                  Switch to single delivery mode
                </button>
              </div>
            ) : (
              <button
                type="submit"
                disabled={loading || !schoolId || !commodityId || !quantity || !isSupplierValid || isAllocationComplete}
                className="w-full rounded-2xl bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 px-6 py-4 text-base font-bold text-white shadow-xl shadow-emerald-500/40 transition-all hover:shadow-2xl hover:shadow-emerald-500/50 active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50 disabled:shadow-none"
              >
                {loading ? (
                  <span className="flex items-center justify-center gap-2">
                    <div className="h-5 w-5 animate-spin rounded-full border-2 border-white/30 border-t-white"></div>
                    Saving...
                  </span>
                ) : isAllocationComplete ? (
                  <span className="flex items-center justify-center gap-2">
                    <CheckCircle className="h-5 w-5" />
                    Delivery Complete
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    <Truck className="h-5 w-5" />
                    Submit Delivery
                  </span>
                )}
              </button>
            )}
          </form>
        </div>
      </div>
    </MobileLayout>
  );
}

// Wrap with Error Boundary for production safety
export default function NewDeliveryPageWithBoundary() {
  return (
    <DeliveryErrorBoundary>
      <NewDeliveryPage />
    </DeliveryErrorBoundary>
  );
}
