import * as React from 'react';
import { useState, useEffect, Fragment, useRef } from 'react';
import { DashboardOutlined, DeleteFilled, DeleteOutlined, ShoppingCartOutlined } from '@ant-design/icons';
import { Empty } from 'antd';
import dayjs from 'dayjs';
import { useQuery, useMutation, useInfiniteQuery } from '@tanstack/react-query';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import { CloseOutlined } from '@ant-design/icons';
import { PopupTransition } from 'components/@extended/Transitions';
import CircularLoader from 'components/CircularLoader';
import Loader from 'components/Loader';
import { KeyboardArrowDownOutlined, KeyboardArrowUpOutlined } from '@mui/icons-material';

import { PiMapPinLineDuotone } from 'react-icons/pi';
import {
  MdOutlineDateRange,
  MdPersonOff,
  MdEventBusy,
  MdLocalShipping,
  MdHourglassEmpty,
  MdCheckCircle,
  MdCancel,
  MdMyLocation,
  MdGroups,
  MdPlace,
  MdStraighten,
  MdCurrencyRupee,
  MdInventory2,
  MdReceiptLong,
  MdHistoryToggleOff,
  MdCalendarMonth
} from 'react-icons/md';
import { VscArchive } from 'react-icons/vsc';
import DateFilterDialog from 'components/DateFilterDialog';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import TitleCard from 'components/nearle_components/TitleCard';
import MainCard from 'components/MainCard';
import { OpenToast } from 'components/third-party/OpenToast';
import { OrdersTableSkeleton } from './OrdersTableSkeleton';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import AiImage from '../../../assets/images/aiImage.png';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import EnergySavingsLeafIcon from '@mui/icons-material/EnergySavingsLeaf';
import DirectionsBikeOutlinedIcon from '@mui/icons-material/DirectionsBikeOutlined';
import WarningIcon from '@mui/icons-material/Warning';
import BoltIcon from '@mui/icons-material/Bolt';
import { ArrowRightAltOutlined } from '@mui/icons-material';
import { HiOutlineArrowLeft } from 'react-icons/hi';

import { IoReload } from 'react-icons/io5';

var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

import {
  Avatar,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  TextField,
  Chip,
  Typography,
  Table,
  TableCell,
  TableBody,
  TableHead,
  Dialog,
  TableRow,
  DialogContent,
  DialogTitle,
  Tooltip,
  Skeleton,
  DialogActions,
  Autocomplete,
  TableContainer,
  Checkbox,
  useMediaQuery,
  Backdrop,
  SpeedDial,
  SpeedDialIcon,
  SpeedDialAction,
  Badge,
  Divider,
  AccordionDetails,
  AccordionSummary,
  Accordion,
  Paper,
  Box
} from '@mui/material';

import {
  fetchOrders,
  fetchorderscount,
  fetchPercentageData,
  createOptimisationDeliveries,
  // notifyRider,
  cancelOrder,
  getTenants,
  gettenantlocations,
  cancelMultipleOrder,
  createAutomationDeliveries,
  fetchPaymentType,
  fetchRidersList,
  finalCreatedeliveries,
  notifyRider,
  getallriders
} from '../../api/api';
import LoaderWithImage from 'components/nearle_components/LoaderWithImage';
import { useNavigate } from 'react-router';
import CSVExport from 'components/third-party/ReactTable';
import Dispatch from '../dispatch/Dispatch';
// import usePreventReload from 'hooks/usePreventReload';

// ============================================================================
// Design tokens — shared with deliveries / tenants / customers / pricing /
// invoice / orders-details / riders-summary pages.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 16,
  shadowSoft: '0 14px 40px rgba(15, 23, 42, 0.10)',
  shadowMd: '0 8px 24px rgba(15, 23, 42, 0.08)',
  shadowPop: '0 18px 50px rgba(15, 23, 42, 0.18)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const dtA = (c, suffix) => `${c}${suffix}`;
const dtTint = (c) => dtA(c, '08');
const dtSoft = (c) => dtA(c, '18');
const dtRing = (c) => dtA(c, '26');
const dtEdge = (c) => dtA(c, '55');

const BRAND = '#662582';
const BRAND_LIGHT = '#9255AB';

const SoftPaper = (props) => (
  <Paper
    {...props}
    sx={{
      mt: 0.75,
      borderRadius: 2,
      boxShadow: DT.shadowPop,
      border: '1px solid',
      borderColor: 'divider',
      overflow: 'hidden'
    }}
  />
);

const DTAccentAvatar = ({ color, selected, size = 24, children }) => (
  <Avatar
    sx={{
      width: size,
      height: size,
      bgcolor: selected ? color : dtSoft(color),
      color: selected ? '#fff' : color,
      transition: 'background-color 0.15s, color 0.15s'
    }}
  >
    {children}
  </Avatar>
);

const pillFieldSx = (color) => ({
  '& .MuiOutlinedInput-root': {
    borderRadius: DT.radiusPill + 'px',
    bgcolor: dtTint(color),
    fontWeight: 600,
    '& fieldset': { borderColor: dtEdge(color), borderWidth: 1.5 },
    '&:hover fieldset': { borderColor: color },
    '&.Mui-focused': { boxShadow: `0 0 0 3px ${dtRing(color)}` },
    '&.Mui-focused fieldset': { borderColor: color, borderWidth: 2 }
  }
});

// Order row status meta — semantic palette for the per-row status badge.
const ROW_STATUS_META = {
  created:   { label: 'Created',   color: '#0ea5e9', icon: MdLocalShipping },
  pending:   { label: 'Pending',   color: '#f59e0b', icon: MdHourglassEmpty },
  processing:{ label: 'Processing',color: '#0ea5e9', icon: MdHistoryToggleOff },
  modified:  { label: 'Modified',  color: '#06b6d4', icon: MdHistoryToggleOff },
  confirmed: { label: 'Confirmed', color: '#10b981', icon: MdCheckCircle },
  accepted:  { label: 'Accepted',  color: '#6366f1', icon: MdCheckCircle },
  delivered: { label: 'Delivered', color: '#10b981', icon: MdCheckCircle },
  cancelled: { label: 'Cancelled', color: '#ef4444', icon: MdCancel }
};

// Tab pill meta — controls the 4 top-level status tabs.
const ORDERS_STATUS_TABS = [
  { idx: 0, status: 'created',   label: 'Created',   color: BRAND,     icon: MdLocalShipping,  countKey: 'created' },
  { idx: 1, status: 'pending',   label: 'Pending',   color: '#f59e0b', icon: MdHourglassEmpty, countKey: 'pending' },
  { idx: 2, status: 'delivered', label: 'Delivered', color: '#10b981', icon: MdCheckCircle,    countKey: 'delivered' },
  { idx: 3, status: 'cancelled', label: 'Cancelled', color: '#ef4444', icon: MdCancel,         countKey: 'cancelled' }
];

const Orders = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const locationRef = useRef(null);
  const tenantRef = useRef(null);
  const [appId, setAppId] = useState(0);
  const [locaName, setLocoName] = useState('All');
  const [assignLoading, setAssignLoading] = useState(false);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [datestatus, setDatestatus] = useState('Today');
  const [open, setOpen] = useState(false);
  const [tabvalue, setTabvalue] = useState(0);
  const [currentStatus, setCurrentStatus] = useState('created');
  const [cancelDialog, setCancelDialog] = useState(false);
  const [assignDialog, setAssignDialog] = useState(false);
  const [multiDeleteDialog, setMultiDeleteDialog] = useState(false);
  const [rider, setRider] = useState(null);
  const [payment, setPayment] = useState(null);
  const [orderheaderid, setOrderheaderid] = useState('');
  const [page, setPage] = useState(0);
  const [productCollapse, setProductCollapse] = useState(null);
  const [tenantid, setTenantid] = useState(0);
  const [locationid, setLocationid] = useState(0);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [createloader, setCreateloader] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [tenantValue, setTenantValue] = useState(null);
  const [locationValue, setLocationValue] = useState(null);
  const [speedDialOpen, setSpeedDialOpen] = useState(false);
  const [aiDialog, setAiDialog] = useState(false);
  const [normalAssignDialog, setNormalAssignDialog] = useState(false);
  const [dispatchPreviewData, setDispatchPreviewData] = useState(null);
  const [deliverylist, setDeliverylist] = useState([]);
  const [deliveryDetails, setDeliveryDetails] = useState([]);
  const [zoneData, setZoneData] = useState(null);
  const [metaData, setMetaData] = useState(null);
  const [aiMode] = useState(0);
  const [csvExportData, setCsvExportData] = useState([]);
  const [finaldeliveryList, setFinalDeliveryList] = useState([]);

  const aiModeRef = useRef(0);
  // Caches the inputs of the most recent AI Assign call so we can forward them
  // to the /nearle/dispatch/preview page via navigate state (the page re-uses
  // them for its Re-Assign button).
  const aiMutationContextRef = useRef(null);
  const rowsPerPage = 100;

  const transportOptions = [
    { label: 'Bike', value: 1 },
    { label: 'Auto', value: 2 }
  ];
  const [selectedMode, setSelectedMode] = useState(null);
  // Riders the operator has marked as absent for today — passed to the AI
  // assign API so its allocation skips them. Optional: the AI run still
  // works with an empty list.
  const [absentRiders, setAbsentRiders] = useState([]);

  // when orders are selected to show popup to stop unwanted reload

  //   usePreventReload(shouldBlock);

  const tuningTypes = [
    {
      tuneid: 1,
      type: 'Balanced',
      value: 'balanced'
    },
    {
      tuneid: 2,
      type: 'Aggressive Speed',
      value: 'aggressive_speed'
    },
    {
      tuneid: 3,
      type: 'Fuel Saver',
      value: 'fuel_saver'
    },
    {
      tuneid: 4,
      type: 'Zone Strict',
      value: 'zone_strict'
    }
  ];

  // to clear the tenant and location autocomplete
  useEffect(() => {
    setTenantid(0);
    setTenantValue(null);
    setLocationid(0);
    setLocationValue(null);
  }, [appId]);
  // to clear the location autocomplete
  useEffect(() => {
    setLocationid(0);
    setLocationValue(null);
  }, [tenantid]);

  // for csv file
  useEffect(() => {
    const filtered = finaldeliveryList.map((item) => ({
      zone_name: item.zone_name,
      ordernotes: item.ordernotes,
      rider: item.rider,
      step: item.step,
      ordertype: item.ordertype,
      orderamount: item.orderamount,
      riderkms: item.riderkms,
      cumulativekms: item.cumulativekms,
      baseprice: item.baseprice,
      minkm: item.minkm,
      priceperkm: item.priceperkm,
      kms: item.kms,
      actualkms: item.actualkms,
      rider_charge: item.rider_charge,
      deliveryamt: item.deliveryamt,
      deliverycharges: item.deliverycharges,
      profit: item.profit
    }));

    setCsvExportData(filtered);

    console.log('csvExportData', filtered);
  }, [finaldeliveryList]);

  // whenever thr delivery details get updated, delivery amt calculated and added
  useEffect(() => {
    if (!deliveryDetails?.length) return;
    const updateDeliveryAmtList = deliveryDetails.map((list) => {
      const cumulativeKms = Number(list.cumulativekms || 0);
      const minKm = Number(list.minkm || 0);
      const basePrice = Number(list.baseprice || 0);
      const pricePerKm = Number(list.priceperkm || 0);

      if (cumulativeKms <= minKm) {
        return {
          ...list,
          deliveryamt: basePrice
        };
      }
      return {
        ...list,
        deliveryamt: (cumulativeKms - minKm) * pricePerKm + basePrice
      };
    });

    setFinalDeliveryList(updateDeliveryAmtList);
    console.log('finaldeliveryList', updateDeliveryAmtList);
  }, [deliveryDetails]);

  // ==============================|| fetchPercentageData ||============================== //

  const {
    data: percentageData,
    isLoading: fetchpercentageIsLoading,
    isError: fetchpercentageIsError,
    error: fetchpercentageError,
    refetch: percentagedataRefetch
  } = useQuery({
    queryKey: ['percentageData', appId],
    queryFn: () => fetchPercentageData(appId), // Ensure appId is passed
    enabled: true
  });

  // ==============================|| getTenants ||============================== //

  const {
    data: tenantlist,
    isLoading: fetchtenantsIsLoading,
    isError: fetchtenantsIsError,
    error: fetchtenantsError
  } = useQuery({
    queryKey: ['tenantlist', appId],
    queryFn: () => getTenants(appId), // Ensure appId is passed
    enabled: appId !== 0 // Ensures query runs only when appId is valid
  });

  // ==============================|| gettenantlocations ||============================== //

  const {
    data: locationlist,
    isLoading: fetchlocationsIsLoading,
    isError: fetchlocationsIsError,
    error: fetchlocationsError
  } = useQuery({
    queryKey: ['gettenantlocations', tenantid],
    queryFn: () => gettenantlocations(tenantid), // Ensure appId is passed
    enabled: tenantid !== 0 // Ensures query runs only when appId is valid
  });
  // ==============================|| fetchPaymentType ||============================== //

  const {
    data: paymentModes = [],
    isLoading: paymentModesLoading
  } = useQuery({
    queryKey: ['paymentmodes'],
    queryFn: fetchPaymentType
  });
  // ==============================|| fetchRidersList ||============================== //

  const {
    data: ridersList = [],
    isLoading: ridersListLoading
  } = useQuery({
    queryKey: ['ridersList', appId], // Unique key for caching & re-fetching
    queryFn: fetchRidersList,
    enabled: appId !== 0 // Ensures query runs only when appId is valid
  });
  // ==============================|| fetchorderscount ||============================== //

  const {
    data: ordersCountData,
    isLoading: fetchorderscountIsLoading,
    isError: fetchorderscountIsError,
    error: fetchorderscountError,
    refetch: orderscountRefetch
  } = useQuery({
    queryKey: ['ordersCount', appId, startdate, enddate, currentStatus, tenantid, locationid],
    queryFn: fetchorderscount,
    refetchOnMount: true,
    refetchOnWindowFocus: true
  });
  // ==============================|| getallriders ||============================== //

  const {
    data: autoRiders
  } = useQuery({
    queryKey: ['getallriders'],
    queryFn: getallriders,
    refetchOnMount: true,
    refetchOnWindowFocus: true
  });

  // ==============================|| getorders ||============================== //
  const {
    data: orderData,
    isLoading: fetchOrdersIsLoading,
    isError: fetchOrdersIsError,
    error: fetchOrdersError,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    refetch: ordersRefetch
  } = useInfiniteQuery({
    queryKey: ['fetchOrders', appId, currentStatus, debouncedSearch, startdate, enddate, rowsPerPage, tenantid, locationid],
    queryFn: fetchOrders,
    getNextPageParam: (lastPage) => lastPage.nextPage ?? undefined,
    refetchOnWindowFocus: true,
    refetchOnMount: true, // 👈 ensures API triggers on page navigation
    refetchOnReconnect: true,
    staleTime: 0
  });

  const rows = orderData?.pages.flatMap((page) => page.rows) || [];

  useEffect(() => {
    if (!hasNextPage) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          fetchNextPage();
        }
      },
      {
        root: document.querySelector('.MuiTableContainer-root'), // 👈 or explicitly TableContainer
        rootMargin: '0px',
        threshold: 1.0
      }
    );
    if (loadMoreRef.current) observer.observe(loadMoreRef.current);
    return () => {
      if (loadMoreRef.current) observer.unobserve(loadMoreRef.current);
    };
  }, [hasNextPage, fetchNextPage]);

  const handleScroll = (event) => {
    const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 50) {
      if (hasNextPage && !isFetchingNextPage) {
        fetchNextPage();
      }
    }
  };

  // ======================================================= || createDeliveryMutation || =======================================================

  const createDeliveryMutation = useMutation({
    // mutationFn: createDeliveries, // Using the separate function
    // 0 -> manual rider assign 1 -> ai rider assign
    mutationFn: aiModeRef.current == 0 ? createOptimisationDeliveries : createAutomationDeliveries,
    onSuccess: (data, variables = []) => {
      console.log('data', data);
      console.log('varialbles', variables);
      OpenToast('Orders Optimised  Successfully', 'success', 2000);
      orderscountRefetch();
      ordersRefetch();
      // notifyRiderMutation.mutate(variables?.riderToken); // Call notifyRider after success
      setAssignLoading(false);
      setCreateloader(false);
      if (aiModeRef.current == 0) {
        setDeliveryDetails(data?.details);
        setZoneData(data?.zones);
        setMetaData(data?.meta);
        setNormalAssignDialog(true);
        // navigate('/nearle/orders/preview', {
        //   state: {
        //     zoneSummary: data?.zone_analysis,
        //     deliverylist: data?.details,
        //     zoneData: data?.zones,
        //     metaData: data?.meta,
        //     riderToken: rider.userfcmtoken,
        //     appId,
        //     aiMode: aiModeRef.current,
        //     reassignOrders
        //   }
        // });
      } else {
        setDeliveryDetails(data?.details);
        setZoneData(data?.zones);
        setMetaData(data?.meta);
        setDispatchPreviewData(data);
        // Route the AI Assign result to the dedicated Preview page (Dispatch
        // view + Reconcile tab + Change Rider). The previous in-page dialog
        // (aiDialog) is left intact but no longer opened — the page replaces
        // it. All inputs needed for Re-Assign / Assign Orders are forwarded.
        const ctx = aiMutationContextRef.current || {};
        navigate('/nearle/dispatch/preview', {
          state: {
            dispatchPreviewData: data,
            aiMode: ctx.aiMode ?? aiModeRef.current,
            selectedMode: ctx.selectedMode || selectedMode,
            deliveryData: ctx.deliveryData || [],
            autoRiders: ctx.autoRiders || autoRiders || [],
            absentRidersPayload: ctx.absentRidersPayload || [],
            rider: ctx.rider || rider,
            appId: ctx.appId ?? appId,
            tenantId: ctx.tenantid ?? tenantid,
            startdate
          }
        });
      }
    },
    onError: (error) => {
      OpenToast(error.message, 'error', 4000);
      setCreateloader(false);
      setAssignLoading(false);
    },
    onSettled: () => {
      assignDialogclose();
      setAssignLoading(false);
      setCreateloader(false);
      setIsLoading(false);
    }
  });
  // ======================================================= || handleManualCreateDelivery || =======================================================

  const handleManualCreateDelivery = () => {
    if (!finaldeliveryList?.length) {
      OpenToast('No deliveries selected', 'error', 3000);
      return;
    }
    createManualDeliveryMutation.mutate({
      deliveries: finaldeliveryList
    });
  };

  // ======================================================= || createManualDeliveryMutation || =======================================================
  const createManualDeliveryMutation = useMutation({
    mutationFn: finalCreatedeliveries,
    onMutate: () => {
      setIsLoading(true);
    },
    onSuccess: (data) => {
      console.log('create data', data);
      OpenToast('Delivery Created Successfully', 'success', 2000);
      navigate('/nearle/deliveries'); // ✅ no delay
      // if (rider?.userfcmtoken) {
      notifyRiderMutation.mutate(rider?.userfcmtoken);
      // }
    },

    onError: (error) => {
      OpenToast(error.message, 'error', 4000);
    },

    onSettled: () => {
      setIsLoading(false);
    }
  });

  // ==============================|| cancelOrder  ||============================== //

  const cancelOrderMutation = useMutation({
    mutationFn: cancelOrder,
    onSuccess: (data) => {
      if (data.status) {
        setCancelDialog(false);
        OpenToast('Order Cancelled Successfully', 'success', 2000);
        orderscountRefetch();
        percentagedataRefetch();
      }
    },
    onError: (error) => {
      OpenToast(error.message, 'error', 2000);
    }
  });

  // ==============================|| cancelMultipleOrder  ||============================== //

  const cancelMultipleOrderMutation = useMutation({
    mutationFn: cancelMultipleOrder,
    onSuccess: (data) => {
      if (data.status) {
        setMultiDeleteDialog(false);
        OpenToast('Order Cancelled Successfully', 'success', 2000);
        ordersRefetch();
        orderscountRefetch();
        percentagedataRefetch();
        setDeliverylist([]);
      }
    },
    onError: (error) => {
      OpenToast(error.message, 'error', 2000);
    }
  });

  // ======================================================= || notifyRiderMutation || =======================================================

  const notifyRiderMutation = useMutation({
    mutationFn: notifyRider, // Using the separate function
    onSuccess: () => {
      OpenToast('Notification sent Successfully', 'success', 2000);
    },
    onError: (error) => {
      OpenToast(error.message, 'error', 2000);
    }
  });

  // ======================================================= || handleCreateDelivery || =======================================================

  const handleCreateDelivery = async (tune) => {
    setIsLoading(true);
    setAssignLoading(true);
    const deliveryData = deliverylist.map((val) => ({
      ...val,
      deliveryid: 0,
      deliverydate: dayjs(val.deliverydate).utc().format('YYYY-MM-DD HH:mm:ss'),
      assigntime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      orderstatus: 'pending',
      orderamount: val.deliverycharge,
      droplat: val.deliverylat,
      droplon: val.deliverylong,
      pickuplat: val.pickuplat,
      pickuplon: val.pickuplong,
      ordernotes: val.ordernotes,
      deliverycharges: val.deliverycharge,
      pickuplocation: val.pickupsuburb,
      deliverylocation: val.deliverysuburb
    }));
    console.log('deliveryData', deliveryData);
    // Normalize the operator's "Absent Riders" picks into the {userid, username}
    // shape the AI assign API expects. The API returns firstname/lastname, so
    // we join them into a single `username` string (with a fallback to the
    // raw `username` field when names are missing).
    const absentRidersPayload = (absentRiders || []).map((r) => ({
      userid: r.userid,
      username:
        `${r.firstname || ''} ${r.lastname || ''}`.trim() ||
        r.username ||
        `Rider ${r.userid}`
    }));

    // Remember the inputs so the Preview page can re-run Re-Assign with the
    // same payload without us having to re-derive it from current Orders state.
    aiMutationContextRef.current = {
      deliveryData,
      absentRidersPayload,
      autoRiders,
      selectedMode,
      aiMode: aiModeRef.current,
      rider,
      appId,
      tenantid
    };

    if (aiModeRef.current == 0) {
      // manual assign
      createDeliveryMutation.mutate({
        deliveries: deliveryData
      });
    } else {
      if (selectedMode && selectedMode?.value == 1) {
        // bike auto assign
        createDeliveryMutation.mutate({
          // mode 1 -> bike , 2 -> auto
          deliveries: selectedMode.value == 1 ? deliveryData : { body: deliveryData },
          hypertuning_params: tune || null,
          selectedMode,
          absent_riders: absentRidersPayload
          // reshuffle: 'joshi'
        });
      } else {
        createDeliveryMutation.mutate({
          // Auto auti assign
          data: {
            orders: deliveryData,
            riders: autoRiders,
            config: {
              pay_type: 'hourly', // options: "hourly", "daily", or "orders"
              base_pay: 300.0,
              strategy: 'multi_trip'
            },
            absent_riders: absentRidersPayload
          },
          selectedMode
        });
      }
    }
  };
  // ======================================================= || createFinalDeliveryMutation || =======================================================

  const createFinalDeliveryMutation = useMutation({
    mutationFn: finalCreatedeliveries, // for optimised delivery create
    onSuccess: (data, variables) => {
      console.log('data', data);
      console.log('varialbles', variables);
      // notifyRiderMutation.mutate(rider.userfcmtoken); // Call notifyRider after success
      OpenToast('Delivery Created Successfully', 'success', 2000);
      setIsLoading(false);
      navigate('/nearle/deliveries');
    },
    onError: (error) => {
      OpenToast(error.message, 'error', 4000);
    },
    onSettled: () => {
      setIsLoading(false);
    }
  });

  // ======================================================= || handleFinalCreateDelivery || =======================================================

  const handleFinalCreateDelivery = async () => {
    // console.log('Final delivery list:', finaldeliveryList);

    setIsLoading(true);
    createFinalDeliveryMutation.mutate({
      deliveries: finaldeliveryList
    });
  };

  const handleChangetab = (e, i) => {
    setPage(0);
    setTabvalue(i);
    if (i === 0) {
      setCurrentStatus('created');
    }
    if (i === 1) {
      setCurrentStatus('pending');
    }
    if (i === 2) {
      setCurrentStatus('delivered');
    }
    if (i === 3) {
      setCurrentStatus('cancelled');
    }
    setSearchword('');
  };

  const assignDialogclose = () => {
    setAssignDialog(false);
    setRider(null);
    setPayment(null);
    setSelectedMode(null);
    setAbsentRiders([]);
  };

  const errorMessage = fetchpercentageIsError
    ? `Error fetching percentages: ${fetchpercentageError?.message}`
    : fetchorderscountIsError
      ? `Error fetching orders Count: ${fetchorderscountError?.message}`
      : fetchOrdersIsError
        ? `Error fetching orders : ${fetchOrdersError?.message}`
        : fetchtenantsIsError
          ? `Error Fetching on Tenants:${fetchtenantsError?.message} `
          : fetchlocationsIsError
            ? `Error Fetching on Tenants Locations:${fetchlocationsError?.message} `
            : null;

  useEffect(() => {
    if (errorMessage) {
      console.log(errorMessage);
      OpenToast(errorMessage, 'error', 3000);
    }
  }, [errorMessage]);

  return (
    <Fragment>
      {(fetchpercentageIsLoading ||
        fetchorderscountIsLoading ||
        fetchOrdersIsLoading ||
        fetchtenantsIsLoading ||
        fetchlocationsIsLoading ||
        createloader) && (
          <>
            <Loader />
            <CircularLoader />
          </>
        )}
      {
        <Backdrop
          sx={{
            color: '#fff',
            zIndex: (theme) => theme.zIndex.drawer + 1
          }}
          open={createloader || fetchOrdersIsLoading} // when loader = true, backdrop covers the page
        >
          <CircularLoader color="inherit" />
        </Backdrop>
      }
      {<Backdrop sx={{ zIndex: 1000 }} open={speedDialOpen} />}
      {/* // ==============================|| SpeedDial ||============================== // */}
      {deliverylist.length > 0 && (
        <SpeedDial
          ariaLabel="Actions"
          icon={
            <Badge badgeContent={deliverylist?.length || ''} color="secondary">
              <SpeedDialIcon />
            </Badge>
          }
          open={speedDialOpen}
          onOpen={() => setSpeedDialOpen(true)}
          onClose={() => setSpeedDialOpen(false)}
          sx={{
            position: 'fixed',
            bottom: 52,
            right: 16,
            '& .MuiFab-primary': {
              bgcolor: '#7b1fa2',
              color: '#fff',
              '&:hover': {
                bgcolor: '#6a1b9a'
              },
              width: 64,
              height: 64
            }
          }}
        >
          <SpeedDialAction
            icon={
              <img
                src={AiImage}
                alt="Assign"
                style={{
                  width: 38,
                  height: 38,
                  objectFit: 'contain',
                  borderRadius: 50
                }}
              />
            }
            tooltipTitle=" Optimisation"
            FabProps={{
              sx: {
                bgcolor: 'primary.main',
                color: '#fff',
                '&:hover': {
                  bgcolor: 'primary.dark'
                },
                width: 64,
                height: 64
              }
            }}
            onClick={() => {
              aiModeRef.current = 1;
              // setAiMode(1);
              setSpeedDialOpen(false);
              setAssignDialog(true);
            }}
          />
          <SpeedDialAction
            icon={<ShoppingCartOutlined style={{ fontSize: 22 }} />}
            tooltipTitle="Manual Assign"
            FabProps={{
              sx: {
                bgcolor: 'success.600',
                color: '#fff',
                '&:hover': {
                  bgcolor: 'success.dark'
                },
                width: 64,
                height: 64
              }
            }}
            onClick={() => {
              aiModeRef.current = 0;
              setSpeedDialOpen(false);
              setAssignDialog(true);
            }}
          />

          <SpeedDialAction
            icon={<DeleteOutlined style={{ fontSize: 22 }} />}
            tooltipTitle="Delete"
            FabProps={{
              sx: {
                bgcolor: '#d32f2f',
                color: '#fff',
                '&:hover': {
                  bgcolor: '#9a0007'
                },
                width: 64,
                height: 64
              }
            }}
            onClick={() => {
              setSpeedDialOpen(false);
              setMultiDeleteDialog(true);
            }}
          />
        </SpeedDial>
      )}
      {/* ============================================= || Header || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mb: { xs: 1.5, md: 2 },
          p: { xs: 1.5, sm: 2, md: 2.5 },
          borderRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          background: `linear-gradient(135deg, ${dtTint(BRAND)} 0%, ${dtTint(BRAND_LIGHT)} 100%)`,
          boxShadow: DT.shadowMd
        }}
      >
        <Stack
          direction={{ xs: 'column', sm: 'row' }}
          alignItems={{ xs: 'flex-start', sm: 'center' }}
          justifyContent="space-between"
          spacing={{ xs: 1.5, sm: 2 }}
        >
          <Stack direction="row" alignItems="center" spacing={{ xs: 1.25, sm: 1.75 }}>
            <Avatar
              sx={{
                width: { xs: 40, sm: 48 },
                height: { xs: 40, sm: 48 },
                bgcolor: BRAND,
                color: '#fff',
                boxShadow: `0 6px 18px ${dtRing(BRAND)}`
              }}
            >
              <MdLocalShipping size={22} />
            </Avatar>
            <Stack>
              <Typography
                variant="h3"
                sx={{
                  fontWeight: 800,
                  color: DT.textPrimary,
                  lineHeight: 1.1,
                  fontSize: { xs: '1.25rem', sm: '1.5rem', md: '1.75rem' }
                }}
              >
                Orders
              </Typography>
              <Stack direction="row" alignItems="center" spacing={0.75} sx={{ mt: 0.5 }}>
                <Box
                  sx={{
                    width: 8,
                    height: 8,
                    borderRadius: '50%',
                    bgcolor: '#10b981',
                    boxShadow: '0 0 0 4px rgba(16,185,129,0.18)'
                  }}
                />
                <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                  Live · {locaName || 'All Zones'} · {datestatus}
                </Typography>
              </Stack>
            </Stack>
          </Stack>
          <LocationAutocomplete
            ref={locationRef}
            locaName={locaName}
            setAppId={setAppId}
            setLocoName={setLocoName}
            setPage={setPage}
            pill
            accentColor={BRAND}
            icon={<MdMyLocation size={14} />}
            placeholder="Select Zone"
            paperComponent={SoftPaper}
            sx={{ width: { xs: '100%', sm: 280 }, zIndex: 100 }}
          />
        </Stack>
      </Paper>

      {/* ============================================= || KPI Cards || ============================================= */}
      <Grid container spacing={{ xs: 1.25, sm: 1.5, md: 2 }} sx={{ mt: '1px' }}>
        {[
          { key: 'created',   label: 'Created Orders',   color: '#0ea5e9', icon: MdLocalShipping,  value: percentageData?.created,         percentage: percentageData?.percentage1 },
          { key: 'pending',   label: 'Pending Orders',   color: '#f59e0b', icon: MdHourglassEmpty, value: percentageData?.uncoveredOrders, percentage: percentageData?.percentage2 },
          { key: 'delivered', label: 'Delivered Orders', color: '#10b981', icon: MdCheckCircle,    value: percentageData?.coveredOrders,   percentage: percentageData?.percentage3 },
          { key: 'cancelled', label: 'Cancelled Orders', color: '#ef4444', icon: MdCancel,         value: percentageData?.cancelled,       percentage: percentageData?.percentage4 }
        ].map((item) => {
          const Icon = item.icon;
          return (
            <Grid item key={item.key} xs={6} sm={6} md={3}>
              <Paper
                elevation={0}
                sx={{
                  position: 'relative',
                  overflow: 'hidden',
                  p: { xs: 1.25, sm: 1.75, md: 2.25 },
                  borderRadius: DT.radiusCard / 8,
                  border: '1px solid',
                  borderColor: DT.borderSubtle,
                  background: '#fff',
                  transition: 'transform 0.2s, box-shadow 0.2s, border-color 0.2s',
                  '&:hover': {
                    transform: 'translateY(-3px)',
                    boxShadow: DT.shadowMd,
                    borderColor: dtEdge(item.color)
                  }
                }}
              >
                <Box
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    height: 3,
                    background: `linear-gradient(90deg, ${item.color} 0%, ${dtSoft(item.color)} 100%)`
                  }}
                />
                <Stack direction="row" alignItems="flex-start" justifyContent="space-between" spacing={1}>
                  <Stack spacing={0.5} sx={{ minWidth: 0, flex: 1 }}>
                    <Typography
                      variant="caption"
                      sx={{
                        color: DT.textSecondary,
                        fontWeight: 700,
                        letterSpacing: 0.4,
                        textTransform: 'uppercase',
                        fontSize: { xs: 10, sm: 11 },
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                      }}
                    >
                      {item.label}
                    </Typography>
                    <Typography
                      sx={{
                        fontWeight: 800,
                        color: DT.textPrimary,
                        lineHeight: 1.1,
                        fontSize: { xs: '1.25rem', sm: '1.5rem', md: '1.75rem' }
                      }}
                    >
                      {fetchpercentageIsLoading ? <Skeleton sx={{ width: 40 }} animation="wave" /> : (item.value ?? 0)}
                    </Typography>
                    {item.percentage != null && (
                      <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 700 }}>
                        {item.percentage}%
                      </Typography>
                    )}
                  </Stack>
                  <Avatar
                    sx={{
                      width: { xs: 36, sm: 42, md: 48 },
                      height: { xs: 36, sm: 42, md: 48 },
                      bgcolor: dtSoft(item.color),
                      color: item.color,
                      boxShadow: `inset 0 0 0 1px ${dtEdge(item.color)}`,
                      flexShrink: 0
                    }}
                  >
                    <Icon size={20} />
                  </Avatar>
                </Stack>
              </Paper>
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Filter Bar (tenant, location, date) || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1.5, md: 2 },
          p: { xs: 1.25, md: 1.75 },
          borderRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          background: '#fff',
          boxShadow: DT.shadowSoft
        }}
      >
        <Grid container spacing={1.25} alignItems="center">
          <Grid item xs={12} sm={6} md={4}>
            <Autocomplete
              options={tenantlist || []}
              value={tenantValue}
              getOptionLabel={(option) => option?.tenantname || ''}
              PaperComponent={SoftPaper}
              onOpen={(event) => {
                if (!appId) {
                  event.preventDefault();
                  OpenToast('Please select  location first!', 'warning', 3000);
                  setTimeout(() => {
                    locationRef.current?.focus();
                  }, 0);
                }
              }}
              onChange={(e, val, reason) => {
                if (reason === 'clear') {
                  setTenantid(0);
                  setTenantValue(null);
                  setLocationid(0);
                  setLocationValue(null);
                } else {
                  setTenantid(val?.tenantid || 0);
                  setTenantValue(val);
                  setLocationid(0);
                  setLocationValue(null);
                }
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  inputRef={tenantRef}
                  placeholder="Select Tenant"
                  size="small"
                  sx={pillFieldSx('#0ea5e9')}
                  InputProps={{
                    ...params.InputProps,
                    startAdornment: (
                      <Stack direction="row" alignItems="center" spacing={0.75} sx={{ pl: 0.5 }}>
                        <DTAccentAvatar color="#0ea5e9" size={22} selected>
                          <MdGroups size={13} />
                        </DTAccentAvatar>
                      </Stack>
                    )
                  }}
                />
              )}
            />
          </Grid>

          <Grid item xs={12} sm={6} md={4}>
            <Autocomplete
              options={locationlist || []}
              getOptionLabel={(option) => (option ? `${option.locationname} (${option.suburb})` : '')}
              value={locationValue}
              PaperComponent={SoftPaper}
              onOpen={(event) => {
                if (!appId && !tenantid) {
                  event.preventDefault();
                  OpenToast('Please select a your Location and Tenant first!', 'warning', 3000);
                  setTimeout(() => {
                    locationRef.current?.focus();
                  }, 0);
                } else if (!tenantid) {
                  event.preventDefault();
                  OpenToast('Please select   Tenant first!', 'warning', 3000);
                  setTimeout(() => {
                    tenantRef.current?.focus();
                  }, 0);
                }
              }}
              onChange={(e, val, reason) => {
                if (reason === 'clear') {
                  setLocationid(0);
                  setLocationValue(null);
                } else {
                  setLocationid(val.locationid || 0);
                  setLocationValue(val);
                }
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  placeholder="Select Location"
                  size="small"
                  sx={pillFieldSx('#10b981')}
                  InputProps={{
                    ...params.InputProps,
                    startAdornment: (
                      <Stack direction="row" alignItems="center" spacing={0.75} sx={{ pl: 0.5 }}>
                        <DTAccentAvatar color="#10b981" size={22} selected>
                          <MdPlace size={13} />
                        </DTAccentAvatar>
                      </Stack>
                    )
                  }}
                />
              )}
            />
          </Grid>

          <Grid item xs={12} sm={12} md={4}>
            <Stack direction="row" spacing={1} alignItems="center" justifyContent={{ xs: 'flex-start', md: 'flex-end' }} flexWrap="wrap">
              <Tooltip title="Date Filter" placement="top">
                <Box
                  onClick={() => setOpen(true)}
                  sx={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: 0.75,
                    px: 1.25,
                    py: 0.75,
                    borderRadius: 999,
                    cursor: 'pointer',
                    bgcolor: dtTint('#f59e0b'),
                    border: `1.5px solid ${dtEdge('#f59e0b')}`,
                    color: '#f59e0b',
                    fontWeight: 800,
                    fontSize: 12,
                    transition: 'all 0.18s',
                    '&:hover': { borderColor: '#f59e0b', boxShadow: `0 0 0 3px ${dtRing('#f59e0b')}` }
                  }}
                >
                  <MdCalendarMonth size={14} />
                  {dayjs(startdate).format('DD/MM/YY')} – {dayjs(enddate).format('DD/MM/YY')}
                </Box>
              </Tooltip>
              <Box
                sx={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 0.5,
                  px: 1,
                  py: 0.5,
                  borderRadius: 999,
                  bgcolor: dtTint(BRAND),
                  border: `1px solid ${dtEdge(BRAND)}`,
                  color: BRAND,
                  fontSize: 11,
                  fontWeight: 800
                }}
              >
                <MdReceiptLong size={12} /> {datestatus}
              </Box>
            </Stack>
          </Grid>
        </Grid>
        {/* ============================================= || filter Dialog | =============================================  */}
        <DateFilterDialog
          open={open}
          onClose={() => setOpen(false)}
          onSelect={(range) => {
            setStartdate(range.startDate);
            setEnddate(range.endDate);
            setDatestatus(range.label);
            console.log('Selected Date Range:', range);
          }}
        />
      </Paper>

      {/* ============================================= || Status Tabs + Search || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1.5, md: 2 },
          p: { xs: 1, md: 1.5 },
          borderTopLeftRadius: DT.radiusCard / 8,
          borderTopRightRadius: DT.radiusCard / 8,
          borderBottomLeftRadius: 0,
          borderBottomRightRadius: 0,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          borderBottom: 0,
          background: '#fff'
        }}
      >
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="space-between"
          gap={1.5}
          sx={{ flexWrap: 'wrap-reverse' }}
        >
          <Stack
            direction="row"
            spacing={0.75}
            sx={{
              flex: 1,
              overflowX: 'auto',
              py: 0.5,
              px: 0.25,
              '&::-webkit-scrollbar': { height: 6 },
              '&::-webkit-scrollbar-thumb': { backgroundColor: DT.borderSubtle, borderRadius: 4 }
            }}
          >
            {ORDERS_STATUS_TABS.map((t) => {
              const Icon = t.icon;
              const active = tabvalue === t.idx;
              const count = ordersCountData?.[t.countKey] ?? 0;
              return (
                <Box
                  key={t.status}
                  onClick={(e) => handleChangetab(e, t.idx)}
                  sx={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: { xs: 0.625, md: 0.875 },
                    pl: 0.5,
                    pr: { xs: 1, md: 1.25 },
                    py: 0.5,
                    flexShrink: 0,
                    cursor: 'pointer',
                    borderRadius: 999,
                    border: `1.5px solid ${active ? t.color : dtEdge(t.color)}`,
                    bgcolor: active ? t.color : dtTint(t.color),
                    color: active ? '#fff' : t.color,
                    fontWeight: 700,
                    boxShadow: active ? `0 6px 18px ${dtRing(t.color)}` : 'none',
                    transition: 'all 0.18s',
                    '&:hover': {
                      borderColor: t.color,
                      boxShadow: active ? `0 6px 18px ${dtRing(t.color)}` : `0 0 0 3px ${dtRing(t.color)}`
                    }
                  }}
                >
                  <Avatar
                    sx={{
                      width: { xs: 22, md: 26 },
                      height: { xs: 22, md: 26 },
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : dtSoft(t.color),
                      color: active ? '#fff' : t.color
                    }}
                  >
                    <Icon size={13} />
                  </Avatar>
                  <Typography
                    variant="caption"
                    sx={{ fontWeight: 800, fontSize: { xs: 11.5, md: 13 }, lineHeight: 1 }}
                  >
                    {t.label}
                  </Typography>
                  <Box
                    sx={{
                      minWidth: { xs: 22, md: 26 },
                      height: { xs: 18, md: 22 },
                      px: 0.625,
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderRadius: 999,
                      fontSize: { xs: 10, md: 11 },
                      fontWeight: 800,
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : '#fff',
                      color: active ? '#fff' : t.color,
                      border: active ? 'none' : `1px solid ${dtEdge(t.color)}`
                    }}
                  >
                    {count}
                  </Box>
                </Box>
              );
            })}
          </Stack>

          <Box sx={{ width: { xs: '100%', sm: 240, lg: 280 }, flex: { xs: '1 1 100%', sm: '0 0 auto' } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={setDebouncedSearch}
              placeholder="Search orders (ctrl+k)"
              sx={{
                m: 0,
                width: '100%',
                borderRadius: 999,
                bgcolor: dtTint(BRAND),
                '& fieldset': { borderColor: dtEdge(BRAND), borderWidth: 1.5 },
                '&:hover fieldset': { borderColor: BRAND },
                '&.Mui-focused fieldset': { borderColor: BRAND, borderWidth: 2 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${dtRing(BRAND)}` }
              }}
            />
          </Box>
        </Stack>
      </Paper>
      {/* ============================================= || Table || =============================================  */}
      <Paper
        elevation={0}
        sx={{
          borderTopLeftRadius: 0,
          borderTopRightRadius: 0,
          borderBottomLeftRadius: DT.radiusCard / 8,
          borderBottomRightRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          overflow: 'hidden',
          background: '#fff'
        }}
      >
        <TableContainer
          ref={containerRef}
          onScroll={handleScroll}
          sx={{
            maxHeight: { xs: 'calc(100vh - 220px)', md: 'calc(100vh - 190px)' },
            overflow: 'auto',
            '&::-webkit-scrollbar': { width: 10, height: 10 },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: dtEdge(BRAND),
              borderRadius: 8,
              '&:hover': { backgroundColor: BRAND }
            },
            '&::-webkit-scrollbar-track': { backgroundColor: DT.surfaceAlt }
          }}
        >
          <Table stickyHeader sx={{ minWidth: { xs: 960, md: 1180 } }}>
            <TableHead>
              <TableRow
                sx={{
                  '& th': {
                    backgroundColor: DT.surfaceAlt,
                    color: DT.textSecondary,
                    fontSize: { xs: 10, md: 11 },
                    fontWeight: 800,
                    letterSpacing: 0.6,
                    textTransform: 'uppercase',
                    whiteSpace: 'nowrap',
                    borderBottom: `1px solid ${DT.borderSubtle}`,
                    py: { xs: 1, md: 1.25 },
                    px: { xs: 1, md: 1.5 }
                  }
                }}
              >
                {currentStatus == 'created' && (
                  <TableCell sx={{ position: 'sticky !important' }}>
                    <Checkbox
                      size="small"
                      sx={{ p: 0.5, color: dtEdge(BRAND), '&.Mui-checked, &.MuiCheckbox-indeterminate': { color: BRAND } }}
                      indeterminate={deliverylist.length > 0 && deliverylist.length !== rows?.length}
                      checked={deliverylist.length === rows?.length}
                      onChange={(e) => {
                        if (!appId) {
                          OpenToast('Please select a location first!', 'warning', 2000);
                          locationRef.current?.focus(); // Auto-focus on the Autocomplete input
                          return;
                        }
                        if (e.target.checked) {
                          const newList = rows?.map((row, index) => ({
                            ...row,
                            sno: index + 1
                          }));
                          setDeliverylist(newList);
                        } else {
                          setDeliverylist([]);
                        }
                      }}
                    />
                  </TableCell>
                )}
                <TableCell>#</TableCell>
                <TableCell>Tenant</TableCell>
                <TableCell>Location</TableCell>
                <TableCell>Pickup</TableCell>
                <TableCell>Drop</TableCell>
                <TableCell align="center">QTY</TableCell>
                <TableCell align="right">COD</TableCell>
                <TableCell align="center">KMS</TableCell>
                <TableCell align="right">Charges</TableCell>
                <TableCell>Notes</TableCell>
                <TableCell>Status</TableCell>
                {currentStatus == 'created' && <TableCell align="right">Actions</TableCell>}
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length === 0 && !fetchOrdersIsLoading && (
                <TableRow>
                  <TableCell colSpan={13} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: dtSoft('#94a3b8'), color: DT.textMuted }}>
                        <MdLocalShipping size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                        No {currentStatus} orders
                      </Typography>
                      <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                        {searchword ? 'Try a different keyword.' : 'Adjust the filters above to load orders.'}
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
              {fetchOrdersIsLoading && <OrdersTableSkeleton col={8} />}
              {rows?.map((row, index) => {
                const isItemSelected = !!deliverylist.find((res) => res.orderheaderid === row.orderheaderid);
                const handleCheckbox = (e) => {
                  if (!appId) {
                    OpenToast('Please select a location first!', 'warning', 2000);
                    locationRef.current?.focus();
                    return;
                  }
                  if (e.target.checked) {
                    setDeliverylist((prev) => [...prev, { ...row, sno: prev.length + 1 }]);
                  } else {
                    setDeliverylist((prev) =>
                      prev.filter((item) => item.orderheaderid !== row.orderheaderid).map((item, i) => ({ ...item, sno: i + 1 }))
                    );
                  }
                };

                return (
                  <TableRow
                    key={row.sno}
                    role="checkbox"
                    tabIndex={-1}
                    sx={{
                      cursor: 'pointer',
                      transition: 'background-color 0.15s',
                      backgroundColor: isItemSelected ? dtTint(BRAND) : 'transparent',
                      '& td': {
                        borderBottom: `1px solid ${DT.divider}`,
                        py: { xs: 1, md: 1.25 },
                        px: { xs: 1, md: 1.5 }
                      },
                      '&:hover': {
                        backgroundColor: isItemSelected ? dtSoft(BRAND) + ' !important' : DT.surfaceAlt
                      }
                    }}
                  >
                    {currentStatus === 'created' && (
                      <TableCell>
                        <Checkbox
                          size="small"
                          sx={{ p: 0.5, color: dtEdge(BRAND), '&.Mui-checked': { color: BRAND } }}
                          onChange={handleCheckbox}
                          checked={isItemSelected}
                        />
                      </TableCell>
                    )}

                    {/* Serial Number */}
                    <TableCell>
                      <Typography>{page * rowsPerPage + index + 1}</Typography>
                    </TableCell>

                    {/* Tenant Info */}
                    <TableCell>
                      <Tooltip title={row.tenantaddress}>
                        <Typography variant="subtitle1" noWrap>
                          {row.tenantname}
                        </Typography>
                        <Typography noWrap variant="body2">
                          {row.tenantsuburb}
                          <br />
                        </Typography>
                        <Typography noWrap variant="body2">
                          {row.applocation}
                        </Typography>
                      </Tooltip>
                    </TableCell>

                    {/* Order Info */}
                    <TableCell align="left">
                      {/* <Tooltip title={row.locationaddress} placement="top"> */}
                      <Typography variant="subtitle1" noWrap>
                        {`${row.locationname}-(${row.locationsuburb})`}
                      </Typography>
                      {/* </Tooltip> */}
                      <Tooltip title="TenantId - OrderId">
                        <Typography variant="body2" noWrap>
                          {row.orderid}
                        </Typography>
                      </Tooltip>
                      <Tooltip title="Pickup Slot">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {dayjs(row.pickupslot).utc().format('DD/MM/YYYY')} {dayjs(row.pickupslot).format('hh:mm A')}
                        </Typography>
                      </Tooltip>
                    </TableCell>

                    {/* Pickup Info */}
                    <TableCell align="left">
                      <Stack direction="column">
                        <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap' }}>
                          {row.pickupcustomer}
                        </Typography>
                        <Typography variant="caption">{row.pickupcontactno}</Typography>
                        <Tooltip title={row.pickupaddress}>
                          <Typography variant="caption">{`${row.pickupsuburb || row.pickupaddress.slice(0, 12) + '.....'}`}</Typography>
                        </Tooltip>
                      </Stack>
                    </TableCell>

                    {/* Delivery Info */}
                    <TableCell align="left">
                      <Stack direction="column">
                        <Typography
                          variant="subtitle1"
                          sx={{
                            maxWidth: 120,
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis'
                          }}
                        >
                          {row.deliverycustomer}
                        </Typography>
                        <Typography variant="caption">{row.deliverycontactno}</Typography>
                        <Tooltip title={row.deliveryaddress} sx={{ whiteSpace: 'nowrap' }}>
                          <Typography variant="caption">{`${row.deliverysuburb || row.deliveryaddress.slice(0, 12) + '.....'}`}</Typography>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                    {/* Quantity */}

                    <TableCell align="center">
                      {row.quantity ? (
                        <Typography variant="subtitle1" color={'error'} sx={{ whiteSpace: 'nowrap' }}>
                          {row.quantity}
                        </Typography>
                      ) : (
                        <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap' }}>
                          {row.quantity}
                        </Typography>
                      )}
                    </TableCell>
                    {/* cod */}
                    <TableCell align="right">
                      {row.collectionamt ? (
                        <Typography variant="subtitle1" color={row.collectionamt ? 'error' : null} sx={{ whiteSpace: 'nowrap' }}>
                          ₹{row.collectionamt.toFixed(2)}
                        </Typography>
                      ) : (
                        <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap' }}>
                          ₹{row.collectionamt.toFixed(2)}
                        </Typography>
                      )}
                    </TableCell>
                    {/* kms */}
                    <TableCell align="center">
                      <Typography variant="subtitle1" color={row.kms ? 'error' : null}>
                        {row.kms}
                      </Typography>
                    </TableCell>
                    {/* Charges */}
                    <TableCell align="right">
                      {row.deliverycharge ? (
                        <Typography variant="subtitle1" color={row.deliverycharge ? 'error' : null} sx={{ whiteSpace: 'nowrap' }}>
                          ₹{row.deliverycharge.toFixed(2)}
                        </Typography>
                      ) : (
                        <Typography variant="subtitle1" sx={{ whiteSpace: 'nowrap' }}>
                          ₹{row.deliverycharge.toFixed(2)}
                        </Typography>
                      )}
                    </TableCell>

                    {/* Notes */}
                    <TableCell align="left">
                      <Typography
                        variant="body1"
                        fontSize="12px"
                        sx={{
                          maxWidth: 120,
                          whiteSpace: 'nowrap',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis'
                        }}
                      >
                        {row.ordernotes}
                      </Typography>
                    </TableCell>

                    {/* Order Status */}
                    <TableCell align="left">
                      {(() => {
                        const meta = ROW_STATUS_META[String(row.orderstatus || '').toLowerCase()] || {
                          label: row.orderstatus || '—',
                          color: BRAND,
                          icon: MdHistoryToggleOff
                        };
                        const StatusIcon = meta.icon;
                        return (
                          <Box
                            sx={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: 0.5,
                              px: 1,
                              py: 0.375,
                              borderRadius: 999,
                              bgcolor: dtTint(meta.color),
                              border: `1px solid ${dtEdge(meta.color)}`,
                              color: meta.color,
                              fontSize: 11,
                              fontWeight: 800,
                              whiteSpace: 'nowrap'
                            }}
                          >
                            <StatusIcon size={12} /> {meta.label}
                          </Box>
                        );
                      })()}
                    </TableCell>

                    {/* Actions */}
                    {row.orderstatus === 'created' && (
                      <TableCell align="center">
                        <Stack flexDirection="row" justifyContent="end">
                          {row.deliverytype === 'C' && (
                            <Tooltip title="Product details">
                              <IconButton
                                color="primary"
                                onClick={() => {
                                  if (productCollapse?.orderid === row.orderid) {
                                    setProductCollapse(null);
                                  } else {
                                    setProductCollapse(row);
                                  }
                                }}
                              >
                                {productCollapse?.orderid === row.orderid ? <KeyboardArrowUpOutlined /> : <KeyboardArrowDownOutlined />}
                              </IconButton>
                            </Tooltip>
                          )}

                          <Tooltip title="To Cancel">
                            <IconButton
                              aria-describedby={`aria-${row.sno}`}
                              disabled={isItemSelected}
                              onClick={() => {
                                setCancelDialog(true);
                                setOrderheaderid(row.orderheaderid);
                              }}
                            >
                              <CloseOutlined
                                style={{
                                  color: isItemSelected ? theme.palette.secondary.main : theme.palette.error.main
                                }}
                              />
                            </IconButton>
                          </Tooltip>
                        </Stack>
                      </TableCell>
                    )}
                  </TableRow>
                );
              })}
              {rows?.length != 0 && (
                <TableRow>
                  <TableCell colSpan={15} rowSpan={3} sx={{ borderBottom: 'none' }}>
                    <div ref={loadMoreRef} style={{ height: 40, textAlign: 'center' }}>
                      {isFetchingNextPage ? (
                        <LoaderWithImage />
                      ) : hasNextPage ? (
                        <LoaderWithImage />
                      ) : (
                        <Typography variant="caption" sx={{ color: DT.textMuted, fontWeight: 600 }}>
                          No more orders
                        </Typography>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </Paper>
      {/* ============================================= || Orders Preview Dialog | =============================================  */}
      <Dialog fullScreen open={assignDialog} TransitionComponent={PopupTransition}>
        {
          <Backdrop
            sx={{
              position: 'absolute',
              color: '#fff',
              zIndex: (theme) => theme.zIndex.modal + 1
            }}
            open={createloader}
          >
            <CircularLoader color="inherit" text="Optimising ... .." />
          </Backdrop>
        }
        <DialogTitle sx={{ bgcolor: theme.palette.primary.lighter }}>
          <Badge badgeContent={deliverylist?.length} color="primary">
            <Chip label={<Typography variant="h3">Preview Orders </Typography>} variant="contained" />
          </Badge>
        </DialogTitle>
        <DialogContent dividers={true}>
          <MainCard content={false}>
            <TableContainer>
              <Table stickyHeader>
                <TableHead>
                  <TableRow>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      #
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      Tenant{' '}
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      order Location
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      Pickup{' '}
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      Delivery
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      Notes
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      Charges
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.lighter
                      }}
                    >
                      KMS
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {deliverylist.map((val, i) => {
                    return (
                      <Fragment key={i}>
                        <TableRow sx={{}}>
                          <TableCell>
                            <Typography> {val.sno}</Typography>
                          </TableCell>
                          <TableCell>
                            <Tooltip title={val.tenantaddress}>
                              <Typography variant="body1" noWrap>
                                {val.tenantname}
                              </Typography>
                              <Typography noWrap sx={{ fontSize: '11px' }}>
                                {val.tenantsuburb}
                                <br />
                              </Typography>

                              <Typography noWrap variant="body2">
                                {val.applocation}
                              </Typography>
                            </Tooltip>
                          </TableCell>
                          <TableCell align="left">
                            <Tooltip title={val.locationaddress} placement="top">
                              <Typography variant="body1" noWrap>
                                {`${val.locationname}-(${val.locationsuburb})`}
                              </Typography>
                            </Tooltip>
                            <Tooltip title="Order Id">
                              <Typography variant="body2" noWrap>
                                {val.orderid}
                              </Typography>
                            </Tooltip>
                            <Stack display={'flex'} flexDirection={'row'} gap={3}>
                              <Tooltip title="Ordered date">
                                <Typography noWrap sx={{ fontSize: '12px' }}>
                                  {dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
                                </Typography>
                                <Typography noWrap sx={{ fontSize: '11px' }}>
                                  {dayjs(val.orderdate).utc().format('hh:mm A')}
                                </Typography>
                              </Tooltip>
                              -
                              <Tooltip title="Delivery date">
                                <Typography noWrap sx={{ fontSize: '12px' }}>
                                  {dayjs(val.deliverydate).utc().format('DD/MM/YYYY')}
                                </Typography>

                                <Typography noWrap sx={{ fontSize: '11px' }}>
                                  {dayjs(val.deliverydate).utc().format('hh:mm A')}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </TableCell>
                          <TableCell align="left">
                            <Stack direction={'row'} spacing={1}>
                              <Stack direction="column">
                                <Typography variant="caption">{val.pickupcustomer}</Typography>
                                <Typography variant="caption">{val.pickupcontactno}</Typography>
                                <Tooltip title={val.pickupaddress}>
                                  <Typography variant="caption">{val.pickupsuburb || val.pickupaddress.slice(0, 20)}</Typography>
                                </Tooltip>
                              </Stack>
                            </Stack>
                          </TableCell>
                          <TableCell align="left">
                            <Stack direction={'row'} spacing={1}>
                              <Stack direction="column">
                                <Typography variant="caption">{val.deliverycustomer}</Typography>
                                <Typography variant="caption">{val.deliverycontactno}</Typography>
                                <Tooltip title={val.deliveryaddress}>
                                  <Typography variant="caption">{val.deliverysuburb || val.deliveryaddress.slice(0, 20)}</Typography>
                                </Tooltip>
                              </Stack>
                            </Stack>
                          </TableCell>
                          <TableCell align="left">{val.ordernotes}</TableCell>
                          <TableCell align="left">₹ {val.deliverycharge.toFixed(2)}</TableCell>
                          <TableCell align="left">{val.kms}</TableCell>
                        </TableRow>
                      </Fragment>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </DialogContent>
        <DialogActions sx={{ bgcolor: theme.palette.secondary.light }}>
          <Grid container sx={{}}>
            <Grid item xs={12}>
              <Stack sx={{ mt: 2, mr: 2 }} direction="row" justifyContent="flex-end" flexWrap={'wrap'} gap={2} spacing={5}>
                <Button
                  sx={{ width: '130px' }}
                  color="secondary"
                  variant="contained"
                  onClick={() => {
                    assignDialogclose();
                  }}
                  startIcon={<CloseOutlined />}
                >
                  Close
                </Button>
                {aiModeRef.current == 1 && (
                  <Autocomplete
                    options={transportOptions}
                    getOptionLabel={(option) => option.label}
                    value={selectedMode}
                    onChange={(event, newValue) => {
                      setSelectedMode(newValue);
                      console.log('Selected value:', newValue?.value); // 1 or 2
                    }}
                    renderInput={(params) => (
                      <TextField
                        sx={{
                          width: 200,
                          border: '1px solid ',
                          borderColor: 'primary.main'
                        }}
                        {...params}
                        placeholder="Select Transport"
                      />
                    )}
                    isOptionEqualToValue={(option, value) => option.value === value.value}
                  />
                )}

                {/* Absent Riders multi-select — optional. Operator picks the
                    riders who are off today; the AI assign API receives their
                    {userid, username} under `absent_riders` and skips them
                    during allocation. Leaving it empty is valid: the AI run
                    proceeds against every rider in the location. */}
                {aiModeRef.current == 1 && (
                  <Autocomplete
                    multiple
                    fullWidth={false}
                    options={ridersList || []}
                    loading={ridersListLoading}
                    disableCloseOnSelect
                    limitTags={2}
                    value={absentRiders}
                    onChange={(event, newValue) => setAbsentRiders(newValue)}
                    getOptionLabel={(option) => {
                      const name = `${option.firstname || ''} ${option.lastname || ''}`.trim();
                      return name || `Rider #${option.userid}`;
                    }}
                    isOptionEqualToValue={(option, value) => option.userid === value.userid}
                    PaperComponent={(paperProps) => (
                      <Paper
                        {...paperProps}
                        sx={{
                          mt: 0.75,
                          borderRadius: 2,
                          boxShadow: '0 14px 40px rgba(15, 23, 42, 0.18)',
                          border: '1px solid',
                          borderColor: 'divider',
                          overflow: 'hidden'
                        }}
                      />
                    )}
                    ListboxProps={{ sx: { py: 0, maxHeight: 340 } }}
                    noOptionsText={
                      <Stack alignItems="center" py={2} spacing={1}>
                        <MdEventBusy size={26} color="#94a3b8" />
                        <Typography variant="caption" color="text.secondary">
                          No riders to show for this location
                        </Typography>
                      </Stack>
                    }
                    renderTags={(value, getTagProps) =>
                      value.map((option, index) => {
                        const name =
                          `${option.firstname || ''} ${option.lastname || ''}`.trim() ||
                          `Rider #${option.userid}`;
                        const initials =
                          (name.match(/\b\w/g) || []).slice(0, 2).join('').toUpperCase() || '?';
                        const tagProps = getTagProps({ index });
                        return (
                          <Chip
                            {...tagProps}
                            key={option.userid}
                            size="small"
                            avatar={
                              <Avatar
                                sx={{
                                  bgcolor: '#fed7aa',
                                  color: '#9a3412',
                                  fontSize: 10,
                                  fontWeight: 800
                                }}
                              >
                                {initials}
                              </Avatar>
                            }
                            label={name}
                            sx={{
                              height: 26,
                              bgcolor: '#fff7ed',
                              color: '#9a3412',
                              border: '1px solid',
                              borderColor: '#fdba74',
                              fontWeight: 600,
                              fontSize: 12,
                              '& .MuiChip-label': { px: 0.75 },
                              '& .MuiChip-deleteIcon': {
                                color: '#c2410c',
                                fontSize: 16,
                                '&:hover': { color: '#7c2d12' }
                              }
                            }}
                          />
                        );
                      })
                    }
                    renderOption={(props, option, { selected }) => {
                      const name = `${option.firstname || ''} ${option.lastname || ''}`.trim();
                      const initials =
                        (name.match(/\b\w/g) || []).slice(0, 2).join('').toUpperCase() || '?';
                      return (
                        <li
                          {...props}
                          key={option.userid}
                          style={{
                            display: 'flex',
                            alignItems: 'center',
                            gap: 12,
                            padding: '8px 12px',
                            borderBottom: '1px solid #f1f5f9',
                            backgroundColor: selected ? '#fff7ed' : 'transparent'
                          }}
                        >
                          <Checkbox
                            size="small"
                            checked={selected}
                            sx={{
                              p: 0.5,
                              color: '#fb923c',
                              '&.Mui-checked': { color: '#ea580c' }
                            }}
                          />
                          <Avatar
                            sx={{
                              width: 34,
                              height: 34,
                              bgcolor: selected ? '#fb923c' : '#f1f5f9',
                              color: selected ? '#fff' : '#475569',
                              fontSize: 12,
                              fontWeight: 800,
                              transition: 'background-color 0.15s, color 0.15s'
                            }}
                          >
                            {initials}
                          </Avatar>
                          <Stack direction="column" spacing={0} flex={1} minWidth={0}>
                            <Typography
                              variant="body2"
                              fontWeight={700}
                              color="#0f172a"
                              noWrap
                            >
                              {name || `Rider #${option.userid}`}
                            </Typography>
                            <Typography variant="caption" color="text.secondary" noWrap>
                              ID #{option.userid}
                              {option.contactno ? ` · ${option.contactno}` : ''}
                            </Typography>
                          </Stack>
                          {selected && (
                            <Chip
                              size="small"
                              label="Absent"
                              sx={{
                                height: 18,
                                fontSize: 9,
                                fontWeight: 800,
                                letterSpacing: 0.3,
                                bgcolor: '#ea580c',
                                color: '#fff',
                                '& .MuiChip-label': { px: 0.75 }
                              }}
                            />
                          )}
                        </li>
                      );
                    }}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label="Absent Riders"
                        placeholder={absentRiders.length ? '' : 'Pick riders unavailable today'}
                        InputLabelProps={{ shrink: true }}
                        InputProps={{
                          ...params.InputProps,
                          startAdornment: (
                            <Stack
                              direction="row"
                              alignItems="center"
                              spacing={0.75}
                              sx={{ pl: 0.5, mr: 0.25 }}
                            >
                              <MdPersonOff size={18} color="#ea580c" />
                              {absentRiders.length > 0 && (
                                <Chip
                                  size="small"
                                  label={absentRiders.length}
                                  sx={{
                                    height: 18,
                                    minWidth: 22,
                                    fontSize: 10,
                                    fontWeight: 800,
                                    bgcolor: '#ea580c',
                                    color: '#fff',
                                    '& .MuiChip-label': { px: 0.5 }
                                  }}
                                />
                              )}
                              {params.InputProps.startAdornment}
                            </Stack>
                          )
                        }}
                        sx={{
                          minWidth: 300,
                          maxWidth: 440,
                          '& .MuiOutlinedInput-root': {
                            borderRadius: 2,
                            bgcolor: '#fffbf5',
                            transition: 'border-color 0.15s, box-shadow 0.15s',
                            '& fieldset': {
                              borderColor: '#fdba74',
                              borderWidth: 1.5
                            },
                            '&:hover fieldset': { borderColor: '#fb923c' },
                            '&.Mui-focused': {
                              boxShadow: '0 0 0 3px rgba(251, 146, 60, 0.18)'
                            },
                            '&.Mui-focused fieldset': {
                              borderColor: '#ea580c',
                              borderWidth: 2
                            }
                          },
                          '& .MuiInputLabel-root': {
                            fontWeight: 700,
                            fontSize: 13,
                            color: '#9a3412',
                            '&.Mui-focused': { color: '#9a3412' }
                          }
                        }}
                      />
                    )}
                    sx={{
                      '& .MuiAutocomplete-tag': { my: 0.25 },
                      '& .MuiAutocomplete-endAdornment': { right: 8 }
                    }}
                  />
                )}

                <Button
                  color={'primary'}
                  disabled={!selectedMode && aiModeRef.current == 1}
                  variant="contained"
                  startIcon={
                    aiModeRef.current == 1 && (
                      <img
                        src={AiImage}
                        alt="Assign"
                        style={{
                          width: 32,
                          height: 32,
                          objectFit: 'contain',
                          borderRadius: 50
                        }}
                      />
                    )
                  }
                  onClick={() => {
                    setCreateloader(true);
                    handleCreateDelivery();
                  }}
                >
                  {assignLoading ? 'Optimising...' : aiModeRef.current == 0 ? 'Optimise Orders' : 'AI Optimise Orders'}
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
      {/* ============================================= || Normal Assign Orders | =============================================  */}
      <Dialog fullScreen open={normalAssignDialog} TransitionComponent={PopupTransition}>
        <DialogTitle>
          <Stack>
            <Stack direction="row" alignItems="center" spacing={1} sx={{ ml: 1 }}>
              <Tooltip title="Back to orders" placement="top">
                <IconButton
                  onClick={() => setNormalAssignDialog(false)}
                  sx={{
                    backgroundColor: 'action.hover',
                    color: 'text.primary',
                    '&:hover': {
                      backgroundColor: 'action.selected'
                    }
                  }}
                >
                  <HiOutlineArrowLeft size={22} />
                </IconButton>
              </Tooltip>
              <Typography sx={{ m: 2 }} variant="h3">
                Assign Orders
              </Typography>
            </Stack>
          </Stack>
        </DialogTitle>
        <Divider />
        <DialogContent>
          <MainCard content={false}>
            {(paymentModesLoading || ridersListLoading || isLoading) && (
              <>
                <Loader />
                <CircularLoader />
              </>
            )}
            {
              <Backdrop
                sx={{
                  color: '#fff',
                  zIndex: (theme) => theme.zIndex.drawer + 1
                }}
                open={paymentModesLoading || ridersListLoading || isLoading} // when loader = true, backdrop covers the page
              >
                <CircularLoader color="inherit" />
              </Backdrop>
            }

            <TableContainer>
              <Table stickyHeader>
                <TableHead>
                  <TableRow sx={{ backgroundColor: 'red' }}>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      #
                    </TableCell>
                    {aiMode == 1 && (
                      <TableCell
                        sx={{
                          position: 'sticky !important',
                          backgroundColor: theme.palette.secondary.light
                        }}
                      >
                        Zone{' '}
                      </TableCell>
                    )}
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Tenant{' '}
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      order Location
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Pickup{' '}
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Delivery
                    </TableCell>
                    <TableCell
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Notes
                    </TableCell>
                    {aiMode == 1 && (
                      <TableCell
                        sx={{
                          position: 'sticky !important',
                          backgroundColor: theme.palette.secondary.light
                        }}
                      >
                        Rider
                      </TableCell>
                    )}
                    <TableCell
                      align="center"
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Type
                    </TableCell>
                    <TableCell
                      align="center"
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      Charges
                    </TableCell>
                    <TableCell
                      align="center"
                      sx={{
                        position: 'sticky !important',
                        backgroundColor: theme.palette.secondary.light
                      }}
                    >
                      KMS
                    </TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {finaldeliveryList?.length == 0 && (
                    <TableRow>
                      <TableCell colSpan={10}>
                        <Empty />
                      </TableCell>
                    </TableRow>
                  )}
                  {finaldeliveryList?.map((val, index) => {
                    return (
                      <TableRow key={index} sx={{}}>
                        <TableCell>
                          <Typography> {index + 1}</Typography>
                        </TableCell>
                        <TableCell>
                          <Tooltip title={val.tenantaddress}>
                            <Typography variant="body1" noWrap>
                              {val.tenantname}
                            </Typography>
                            <Typography noWrap sx={{ fontSize: '11px' }}>
                              {val.tenantsuburb}
                              <br />
                            </Typography>

                            <Typography noWrap variant="body2">
                              {val.applocation}
                            </Typography>
                          </Tooltip>
                        </TableCell>
                        <TableCell align="left">
                          <Tooltip title={val.locationaddress} placement="top">
                            <Typography variant="body1" noWrap>
                              {`${val.locationname}-(${val.locationsuburb})`}
                            </Typography>
                          </Tooltip>
                          <Tooltip title="Order Id">
                            <Typography variant="body2" noWrap>
                              {val.orderid}
                            </Typography>
                          </Tooltip>
                          <Stack display={'flex'} flexDirection={'row'} gap={3}>
                            <Tooltip title="Ordered date">
                              <Typography noWrap sx={{ fontSize: '12px' }}>
                                {dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
                              </Typography>
                              <Typography noWrap sx={{ fontSize: '11px' }}>
                                {dayjs(val.orderdate).utc().format('hh:mm A')}
                              </Typography>
                            </Tooltip>
                            -
                            <Tooltip title="Delivery date">
                              <Typography noWrap sx={{ fontSize: '12px' }}>
                                {dayjs(val.deliverydate).utc().format('DD/MM/YYYY')}
                              </Typography>

                              <Typography noWrap sx={{ fontSize: '11px' }}>
                                {dayjs(val.deliverydate).utc().format('hh:mm A')}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{val.pickupcustomer}</Typography>
                              <Typography variant="caption">{val.pickupcontactno}</Typography>
                              <Tooltip title={val.pickupaddress}>
                                <Typography variant="caption">{val.pickupsuburb || val.pickupaddress.slice(0, 20)}</Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{val.deliverycustomer}</Typography>
                              <Typography variant="caption">{val.deliverycontactno}</Typography>
                              <Tooltip title={val.deliveryaddress}>
                                <Typography variant="caption">{val.deliverysuburb || val.deliveryaddress.slice(0, 20)}</Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">{val.ordernotes}</TableCell>
                        {/* {aiMode == 1 && (
                          <TableCell align="left">
                            <Typography sx={{ whiteSpace: 'nowrap' }}>{val.username}</Typography>
                            <Typography>ID : {val.userid}</Typography>
                          </TableCell>
                        )} */}
                        <TableCell align="center">
                          <Chip
                            size="small"
                            label={val.ordertype}
                            color={val.ordertype == 'Economy' ? 'success' : val.ordertype == 'Risky' ? 'error' : 'primary'}
                            variant="light"
                          />
                        </TableCell>
                        <TableCell align="center">
                          <Stack display={'flex'} flexDirection={'column'} gap={1} sx={{ cursor: 'pointer' }}>
                            <Tooltip title="Charges" placement="top">
                              <Chip size="small" label={`₹ ${val.deliverycharge.toFixed(2)} `} color="error" variant="light" />
                            </Tooltip>
                            <Tooltip title="Amount" placement="left">
                              <Chip size="small" label={`₹ ${val.deliveryamt.toFixed(2)} `} color="success" variant="light" />
                            </Tooltip>
                          </Stack>
                        </TableCell>
                        <TableCell align="center">
                          <Stack display={'flex'} flexDirection={'column'} gap={1} sx={{ cursor: 'pointer' }}>
                            <Tooltip title="KMS" placement="top">
                              <Chip size="small" label={`${val.kms} km`} color="error" variant="light" />
                            </Tooltip>
                            <Tooltip title="Cumulative Kms" placement="right">
                              <Chip size="small" label={`${val.cumulativekms} km`} color="success" variant="light" />
                            </Tooltip>
                          </Stack>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
            <Divider />
          </MainCard>
        </DialogContent>
        <Divider />
        <DialogActions sx={{ flexDirection: 'column', alignItems: 'stretch', p: 2, gap: 2 }}>
          {/* Top Inputs Section */}
          <Grid container spacing={2}>
            <Grid item xs={12} sm={6}>
              <Autocomplete
                options={paymentModes}
                fullWidth
                renderInput={(params) => <TextField {...params} label="Choose Payment" />}
                onChange={(event, newValue, reason) => {
                  if (reason === 'clear') {
                    setPayment(null);
                    return;
                  }

                  if (newValue) {
                    setPayment(newValue);

                    const newList = finaldeliveryList?.map((list) => ({
                      ...list,
                      paymenttype: newValue.apptypeid || 42
                    }));

                    setFinalDeliveryList(newList);
                  }
                }}
              />
            </Grid>

            <Grid item xs={12} sm={6}>
              <Autocomplete
                options={ridersList}
                fullWidth
                renderInput={(params) => <TextField {...params} label="Choose Rider" />}
                onChange={(event, newValue, reason) => {
                  if (reason === 'clear') {
                    setRider(null);
                    return;
                  }

                  if (newValue) {
                    setRider(newValue);

                    const newList = finaldeliveryList?.map((list) => ({
                      ...list,
                      userid: newValue.userid,
                      fuelcharge: newValue.fuelcharge || 0,
                      userfcmtoken: newValue.userfcmtoken
                    }));

                    setFinalDeliveryList(newList);
                  }
                }}
              />
            </Grid>
          </Grid>

          {/* Buttons Section */}
          <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ pt: 1, my: 2 }}>
            <Button variant="outlined" color="secondary" startIcon={<ArrowBackIcon />} onClick={() => setNormalAssignDialog(false)}>
              Back
            </Button>

            <Button variant="contained" disabled={!rider || !payment} onClick={handleManualCreateDelivery}>
              Assign Orders
            </Button>
          </Stack>
        </DialogActions>
      </Dialog>
      {/* ============================================= || AI optimisation Assign Orders | =============================================  */}
      <Dialog
        open={aiDialog}
        fullScreen
        TransitionComponent={PopupTransition}
        PaperProps={{ sx: { display: 'flex', flexDirection: 'column', overflow: 'hidden' } }}
      >
        {
          <Backdrop
            sx={{
              position: 'absolute',
              color: '#fff',
              zIndex: (theme) => theme.zIndex.modal + 1
            }}
            open={isLoading}
          >
            <CircularLoader color="inherit" />
          </Backdrop>
        }
        <DialogTitle sx={{ py: 1.25 }}>
          <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{}}>
            <Stack direction="row" alignItems="center" spacing={1}>
              <Tooltip title="Back to orders" placement="top">
                <IconButton
                  onClick={() => navigate('/nearle/orders')}
                  sx={{
                    bgcolor: 'action.hover',
                    '&:hover': { bgcolor: 'action.selected' }
                  }}
                >
                  <HiOutlineArrowLeft size={20} />
                </IconButton>
              </Tooltip>
              <Typography variant="h3" fontWeight={600}>
                Assign Orders
              </Typography>
            </Stack>
            <Stack direction="row" alignItems="center" spacing={1}>
              <Autocomplete
                options={tuningTypes || []}
                getOptionLabel={(option) => option.type}
                sx={{ minWidth: 250, maxWidth: 600, flex: 1 }}
                renderInput={(params) => <TextField {...params} label="Hyper Tuning" />}
                onChange={(e, val, reason) => {
                  if (reason === 'clear') {
                    handleCreateDelivery(null);
                  } else {
                    console.log('val', val);
                    handleCreateDelivery(val.value);
                  }
                }}
              />
              {/* <Autocomplete
                multiple
                id="checkboxes-tags-demo"
                options={tuningTypes}
                disableCloseOnSelect
                getOptionLabel={(option) => option.type}
                renderOption={(props, option, { selected }) => {
                  const { id, ...optionProps } = props;
                  const SelectionIcon = selected ? CheckBoxIcon : CheckBoxOutlineBlankIcon;

                  return (
                    <li key={id} {...optionProps}>
                      <SelectionIcon fontSize="small" style={{ marginRight: 8, padding: 9, boxSizing: 'content-box' }} />
                      {option.type}
                    </li>
                  );
                }}
                style={{ width: 400 }}
                renderInput={(params) => (
                  <TextField
                    {...params}
                    sx={{
                      '& .MuiInputBase-input': {
                        lineHeight: '1.5'
                      }
                    }}
                    label="Hyper Tuning"
                  />
                )}
              /> */}
              <Button
                variant="contained"
                color="primary"
                startIcon={<IoReload />}
                onClick={() => {
                  setIsLoading(true);
                  handleCreateDelivery('reshuffle');
                }}
              >
                Re-Assign
              </Button>
              <CSVExport
                data={csvExportData}
                filename={`Orders_Detail_${dayjs().format('YYYY-MM-DD_HHmmss')}.csv`}
                label=" CSV"
                style={{ m: 1 }}
              />
            </Stack>
          </Stack>
        </DialogTitle>
        <DialogContent sx={{ p: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden', flex: 1 }}>
          {dispatchPreviewData && <Dispatch data={dispatchPreviewData} embedded />}
        </DialogContent>
        <DialogActions sx={{ px: 2, py: 1.25 }}>
          <Stack direction="row" gap={2} alignItems="center" justifyContent="end">
            <Button
              variant="contained"
              color="secondary"
              startIcon={<ArrowBackIcon />}
              onClick={() => {
                // navigate('/nearle/orders');
                setAiDialog(false);
              }}
            >
              Back
            </Button>
            <Button variant="contained" onClick={handleFinalCreateDelivery}>
              Assign Orders
            </Button>
          </Stack>
        </DialogActions>
      </Dialog>
      {/* ========================================= || cancel order Dialog || ========================================= */}
      <Dialog open={cancelDialog} onClose={() => handleClose()} maxWidth="xs">
        <DialogContent sx={{ mt: 2, my: 1 }}>
          <Stack alignItems="center" spacing={3.5}>
            <Avatar color="error" sx={{ width: 72, height: 72, fontSize: '1.75rem' }}>
              <DeleteFilled />
            </Avatar>

            <Stack spacing={2}>
              <Typography variant="h4" align="center">
                Are you sure you want to cancel this order?
              </Typography>
            </Stack>

            <Stack direction="row" spacing={2} sx={{ width: 1 }}>
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  cancelOrderMutation.mutate(orderheaderid);
                  // cancelridernotification();
                }}
                autoFocus
              >
                Yes, Cancel
              </Button>
              <Button
                fullWidth
                onClick={() => {
                  setCancelDialog(false);
                }}
                color="secondary"
                variant="outlined"
              >
                No
              </Button>
            </Stack>
          </Stack>
        </DialogContent>
      </Dialog>
      {/* ========================================= || Multiple cancel order Dialog || ========================================= */}
      <Dialog open={multiDeleteDialog} onClose={() => setMultiDeleteDialog(false)} maxWidth="xs">
        <DialogContent sx={{ mt: 2, my: 1 }}>
          <Stack alignItems="center" spacing={3.5}>
            <Avatar color="error" sx={{ width: 72, height: 72, fontSize: '1.75rem' }}>
              <DeleteFilled />
            </Avatar>

            <Stack spacing={2}>
              <Typography variant="h4" align="center">
                Are you sure, you want to cancel multiple orders?
              </Typography>
            </Stack>

            <Stack direction="row" spacing={2} sx={{ width: 1 }}>
              <Button
                fullWidth
                onClick={() => {
                  setMultiDeleteDialog(false);
                }}
                color="secondary"
                variant="outlined"
              >
                No
              </Button>
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  cancelMultipleOrderMutation.mutate(deliverylist);
                  // cancelMultipleOrderMutation.mutate(orderheaderid);
                  // cancelridernotification();
                }}
                autoFocus
              >
                Yes, Cancel
              </Button>
            </Stack>
          </Stack>
        </DialogContent>
      </Dialog>
    </Fragment>
  );
};

export default Orders;
