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 } 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 { DashboardFilled, OpenAIFilled } from '@ant-design/icons';
import { MdDirectionsBike } from 'react-icons/md';
import { FaMapLocationDot } from 'react-icons/fa6';
import { HiOutlineArrowLeft } from 'react-icons/hi';
import { GiProfit } from 'react-icons/gi';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
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
} 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 usePreventReload from 'hooks/usePreventReload';

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 [deliverylist, setDeliverylist] = useState([]);
  const [zoneSummary, setZoneSummary] = useState(null);
  const [deliveryDetails, setDeliveryDetails] = useState([]);
  const [zoneData, setZoneData] = useState(null);
  const [metaData, setMetaData] = useState(null);
  const [reassignOrders, setReassignOrders] = useState([]);
  const [aiMode, setAiMode] = useState(0);
  const [csvExportData, setCsvExportData] = useState([]);
  const [finaldeliveryList, setFinalDeliveryList] = useState([]);

  const aiModeRef = useRef(0);
  const rowsPerPage = 100;

  const transportOptions = [
    { label: 'Bike', value: 1 },
    { label: 'Auto', value: 2 }
  ];
  const [selectedMode, setSelectedMode] = useState(null);

  // when orders are selected to show popup to stop unwanted reload
  const shouldBlock = deliverylist.length > 0;
  //   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,
    isError: paymentModesError,
    error: paymentModesErrorMessage
  } = useQuery({
    queryKey: ['paymentmodes'],
    queryFn: fetchPaymentType
  });
  // ==============================|| fetchRidersList ||============================== //

  const {
    data: ridersList = [],
    isLoading: ridersListLoading,
    isError: ridersListError,
    error: ridersListErrorMessage,
    refetch: ridersListRefetch
  } = 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,
    isLoading: getallridersIsLoading,
    isError: fgetallriderscountIsError,
    error: getallridersError,
    refetch: getallridersRefetch
  } = 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) {
        setZoneSummary(data?.zone_analysis);
        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 {
        setZoneSummary(data?.zone_analysis);
        setDeliveryDetails(data?.details);
        setZoneData(data?.zones);
        setMetaData(data?.meta);
        setAiDialog(true);
        // navigate('/nearle/orders/optimisedpreview', {
        //   state: {
        //     zoneSummary: data?.zone_analysis,
        //     deliverylist: data?.details, // to deliveryDetails
        //     zoneData: data?.zones,
        //     metaData: data?.meta,
        //     riderToken: rider.userfcmtoken,
        //     appId,
        //     aiMode: aiModeRef.current,
        //     reassignOrders
        //   }
        // });
      }
    },
    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
    }));
    setReassignOrders(deliveryData);
    console.log('deliveryData', deliveryData);
    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
          // 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'
            }
          },
          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);
  };

  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>
      )}
      {/* ============================================= || titlecard | =============================================  */}
      <TitleCard title="Orders">
        <LocationAutocomplete
          ref={locationRef}
          locaName={locaName}
          setAppId={setAppId}
          setLocoName={setLocoName}
          setPage={setPage}
          sx={{ width: { xs: '100%', custom450: 300 }, zIndex: '100' }}
        />
      </TitleCard>
      {/* ============================================= || Hovercard | =============================================  */}
      <Grid container spacing={2} sx={{ mt: '1px' }}>
        {[
          {
            label: 'Created orders',
            value: percentageData?.created,
            percentage: percentageData?.percentage1,
            color: theme.palette.info.main
          },
          {
            label: 'Pending orders',
            value: percentageData?.uncoveredOrders,
            percentage: percentageData?.percentage2,
            color: theme.palette.warning.main
          },
          {
            label: 'Delivered orders',
            value: percentageData?.coveredOrders,
            percentage: percentageData?.percentage3,
            color: theme.palette.success.main
          },
          {
            label: 'Cancelled Orders',
            value: percentageData?.cancelled,
            percentage: percentageData?.percentage4,
            color: theme.palette.error.main
          }
        ].map((item, index) => (
          <Grid item key={index} xs={12} custom400={6} sm={3} sx={{ cursor: 'pointer' }}>
            <HoverSocialCard
              primary={item.label}
              secondary={fetchpercentageIsLoading ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : item.value}
              percentage={item.percentage?.toString()}
              color={item.color}
            />
          </Grid>
        ))}
      </Grid>
      {/* ============================================= || orderFilter | =============================================  */}
      <Stack direction="row" justifyContent="space-between" alignItems="center" gap={2} sx={{ flexWrap: 'wrap', my: 2 }}>
        {/* Order Status Chips */}
        <Stack direction="row" spacing={2} alignItems={'center'} sx={{ flexWrap: 'wrap' }}>
          {startdate && enddate ? (
            <Stack
              direction="row"
              spacing={1.5}
              flexWrap="wrap"
              useFlexGap
              sx={{
                rowGap: 1.5, // vertical spacing when wrapped
                columnGap: 1.5,
                alignItems: 'center',
                justifyContent: {
                  xs: 'flex-start',
                  sm: 'flex-start',
                  md: 'flex-start'
                }
              }}
            >
              <Chip
                avatar={<VscArchive fontSize="20px" style={{ color: 'red' }} />}
                label={`Orders-${datestatus}`}
                color="error"
                variant="combined"
              />

              <Chip
                avatar={
                  <Avatar sx={{ backgroundColor: 'transparent' }}>
                    <MdOutlineDateRange fontSize="24px" style={{ color: '#fbc02d' }} />
                  </Avatar>
                }
                label={
                  <Typography noWrap color="secondary" fontSize="0.8rem">
                    {`${dayjs(startdate).format('DD/MM/YYYY')} - ${dayjs(enddate).format('DD/MM/YYYY')}`}
                  </Typography>
                }
                color="warning"
                variant="combined"
                onClick={() => setOpen(true)}
                sx={{ cursor: 'pointer' }}
              />

              <Chip
                avatar={
                  <Avatar sx={{ backgroundColor: 'transparent' }}>
                    <PiMapPinLineDuotone fontSize="24px" style={{ color: '#00bcd4' }} />
                  </Avatar>
                }
                label={locaName}
                color="info"
                variant="combined"
              />
            </Stack>
          ) : (
            <Chip label="Orders-All" color="primary" variant="light" size="small" />
          )}
        </Stack>

        <Stack
          display={'flex'}
          flexDirection={'row'}
          alignItems={'center'}
          flexWrap={'wrap'}
          gap={2}
          sx={{ width: { xs: '100%', md: 'auto' } }}
        >
          {/* ==================================================== || Tenant Autocomplete || ====================================================  */}
          <Autocomplete
            options={tenantlist || []}
            value={tenantValue}
            sx={{ minWidth: 250, maxWidth: 600, flex: 1 }}
            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} label="Select Tenant" />}
          />
          {/* ==================================================== || Location Autocomplete || ====================================================  */}
          <Autocomplete
            options={locationlist || []}
            getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
            value={locationValue}
            sx={{ minWidth: 250, maxWidth: 600, flex: 1 }}
            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} label="Select Location" />}
          />

          {/* ============================================= || 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);
            }}
          />
        </Stack>
      </Stack>
      {/* ============================================= || Tabs || =============================================  */}
      <Stack
        display={'flex'}
        flexDirection={'row'}
        justifyContent={'space-between'}
        alignItems={'center'}
        flexWrap={'wrap-reverse'}
        gap={2}
        sx={{
          border: '1px solid ',
          borderBottom: 0,
          borderColor: 'bg.main',
          p: 1.5
        }}
      >
        <Tabs
          value={tabvalue}
          onChange={handleChangetab}
          variant="scrollable"
          // eslint-disable-next-line react-hooks/rules-of-hooks
          scrollButtons={useMediaQuery(theme.breakpoints.down('custom650')) ? true : false}
          allowScrollButtonsMobile
        >
          <Tab
            label="Created"
            icon={
              <Chip
                label={ordersCountData?.created || 0}
                color="primary"
                variant="light"
                sx={{ minWidth: 32, justifyContent: 'center' }}
                size="small"
              />
            }
            iconPosition="end"
          />
          <Tab
            label="Pending"
            icon={
              <Chip
                label={ordersCountData?.pending || 0}
                color="primary"
                variant="light"
                sx={{ minWidth: 32, justifyContent: 'center' }}
                size="small"
              />
            }
            iconPosition="end"
          />
          <Tab
            label="Delivered"
            icon={
              <Chip
                label={ordersCountData?.delivered || 0}
                color="primary"
                variant="light"
                sx={{ minWidth: 32, justifyContent: 'center' }}
                size="small"
              />
            }
            iconPosition="end"
          />
          <Tab
            label="Cancelled"
            icon={
              <Chip
                label={ordersCountData?.cancelled || 0}
                color="primary"
                variant="light"
                sx={{ minWidth: 32, justifyContent: 'center' }}
                size="small"
              />
            }
            iconPosition="end"
          />
        </Tabs>
        <DebounceSearchBar
          value={searchword}
          onChange={setSearchword}
          onDebouncedChange={setDebouncedSearch}
          sx={{ width: { xs: '100%', custom1000: 275 }, m: 0 }}
        />
      </Stack>
      {/* ============================================= || Table || =============================================  */}
      <MainCard content={false}>
        <TableContainer
          ref={containerRef}
          onScroll={handleScroll}
          sx={{
            maxHeight: 'calc(100vh - 90px)',
            overflow: 'auto',
            '&::-webkit-scrollbar': {
              width: '12px', // scroll bar width
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: theme.palette.primary.main, // thumb color
              borderRadius: '8px',
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-thumb:hover': {
              backgroundColor: theme.palette.primary.dark, // hover color
              cursor: 'pointer'
            },
            '&::-webkit-scrollbar-track': {
              backgroundColor: theme.palette.primary.lighter,
              cursor: 'pointer'
            }
          }}
        >
          <Table stickyHeader>
            <TableHead>
              <TableRow>
                {currentStatus == 'created' && (
                  <TableCell
                    sx={{
                      position: 'sticky !important',
                      backgroundColor: theme.palette.secondary.light
                    }}
                  >
                    <Checkbox
                      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
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  #{' '}
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  Tenant{' '}
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  {' '}
                  Location
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  {' '}
                  Pickup{' '}
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  {' '}
                  Drop{' '}
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  {' '}
                  QTY{' '}
                </TableCell>
                <TableCell
                  align="right"
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  COD
                </TableCell>
                <TableCell
                  align="center"
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  KMS
                </TableCell>
                <TableCell
                  align="right"
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  Charges
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  {' '}
                  Notes{' '}
                </TableCell>
                <TableCell
                  sx={{
                    position: 'sticky !important',
                    backgroundColor: theme.palette.secondary.light
                  }}
                >
                  status{' '}
                </TableCell>
                {currentStatus == 'created' && (
                  <TableCell
                    sx={{
                      position: 'sticky !important',
                      backgroundColor: theme.palette.secondary.light
                    }}
                  >
                    Actions
                  </TableCell>
                )}
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length === 0 && !fetchOrdersIsLoading && (
                <TableRow>
                  <TableCell colSpan={13}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty
                        description={`No  ${currentStatus} Orders`}
                        styles={{
                          description: { color: theme.palette.error.main }
                        }}
                      />
                    </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',
                      backgroundColor: isItemSelected ? '#e1bee7' : '',
                      '&:hover': {
                        backgroundColor: isItemSelected ? '#e1bee7 !important' : ''
                      }
                    }}
                  >
                    {currentStatus === 'created' && (
                      <TableCell>
                        <Checkbox
                          sx={{
                            backgroundColor: isItemSelected ? '#e1bee7' : '',
                            '&:hover': {
                              backgroundColor: isItemSelected ? '#e1bee7 !important' : ''
                            }
                          }}
                          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">
                      <Chip
                        label={row.orderstatus}
                        color={
                          row.orderstatus === 'pending'
                            ? 'warning'
                            : row.orderstatus === 'modified' ||
                              row.orderstatus === 'confirmed' ||
                              row.orderstatus === 'delivered' ||
                              row.orderstatus === 'accepted'
                            ? 'success'
                            : row.orderstatus === 'cancelled'
                            ? 'error'
                            : row.orderstatus === 'processing'
                            ? 'primary'
                            : 'primary'
                        }
                        size="small"
                        variant="light"
                      />
                    </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}>
                    <div ref={loadMoreRef} style={{ height: 40, textAlign: 'center' }}>
                      {isFetchingNextPage ? <LoaderWithImage /> : hasNextPage ? <LoaderWithImage /> : 'No More Orders'}
                    </div>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      </MainCard>
      {/* ============================================= || 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}
                  />
                )}

                <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}>
        {
          <Backdrop
            sx={{
              position: 'absolute',
              color: '#fff',
              zIndex: (theme) => theme.zIndex.modal + 1
            }}
            open={isLoading}
          >
            <CircularLoader color="inherit" />
          </Backdrop>
        }
        <DialogTitle>
          <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>
          <Stack sx={{ my: 2 }}>
            <Grid container spacing={2}>
              <Grid item xs={6} sm={6} md={3}>
                <HoverSocialCard
                  secondary={metaData?.total_orders}
                  primary={'Orders'}
                  percentage={<DashboardFilled />}
                  color={theme.palette.success.main}
                  sx={{ cursor: 'pointer' }}
                />
              </Grid>
              <Grid item xs={6} sm={6} md={3}>
                <HoverSocialCard
                  secondary={metaData?.utilized_riders}
                  primary={'Riders'}
                  percentage={<MdDirectionsBike />}
                  color={theme.palette.warning.main}
                />
              </Grid>
              <Grid item xs={6} sm={6} md={3}>
                <HoverSocialCard
                  secondary={zoneData?.length}
                  primary={'Zones'}
                  percentage={<FaMapLocationDot />}
                  color={theme.palette.info.main}
                />
              </Grid>
              <Grid item xs={6} sm={6} md={3}>
                <HoverSocialCard
                  secondary={metaData?.total_profit}
                  primary={'Profit'}
                  percentage={<GiProfit />}
                  color={theme.palette.error.main}
                />
              </Grid>
            </Grid>
          </Stack>
        </DialogTitle>
        <DialogContent>
          <MainCard content={false}>
            {zoneData?.map((zone, index) => {
              const riders = zone?.riders.flatMap((rider) => rider);
              const orders = zone?.riders?.flatMap((rider) => rider.orders);

              return (
                <Accordion
                  key={index}
                  // expanded={true}
                >
                  <AccordionSummary>
                    <Stack direction="row" alignItems="center" spacing={2} sx={{ m: 2 }}>
                      <Typography variant="h5" fontWeight={1000}>
                        Zone {index + 1} :
                      </Typography>
                      <Chip label={zone.zone_name} color="primary" variant="light" size="small" sx={{ minWidth: 100 }} />
                      <Tooltip title={`Orders`} placement="top">
                        <Badge badgeContent={zone.total_orders} color="secondary">
                          <DashboardOutlined style={{ fontSize: 20 }} />
                        </Badge>
                      </Tooltip>
                      <Tooltip title={`Riders`} placement="top">
                        <Badge color="secondary" badgeContent={zone.active_riders_count}>
                          <DirectionsBikeOutlinedIcon style={{ fontSize: 20 }} />
                        </Badge>
                      </Tooltip>
                    </Stack>
                  </AccordionSummary>
                  <AccordionDetails>
                    <TableContainer sx={{ p: 0, m: 0 }}>
                      <Table stickyHeader>
                        <TableHead>
                          <TableRow>
                            <TableCell>#</TableCell>
                            {/* <TableCell>Tenant</TableCell> */}
                            <TableCell>Order Location</TableCell>
                            <TableCell>Pickup</TableCell>
                            <TableCell>Delivery</TableCell>
                            <TableCell>Notes</TableCell>
                            <TableCell>Rider</TableCell>
                            <TableCell align="center">Type</TableCell>
                            <TableCell align="center">Profit</TableCell>
                            <TableCell align="center">Charges</TableCell>
                            <TableCell align="center">KMS</TableCell>
                          </TableRow>
                        </TableHead>

                        <TableBody>
                          {orders.map((val, i) => (
                            <Fragment key={i}>
                              <TableRow sx={{}}>
                                <TableCell>
                                  <Typography> {i + 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} sx={{ cursor: 'pointer' }}>
                                    <Tooltip title="Pickup Time">
                                      <Typography noWrap sx={{ fontSize: '12px' }}>
                                        {dayjs(val.pickupslot).format('DD/MM/YYYY')}
                                      </Typography>
                                      <Chip
                                        size="small"
                                        label={dayjs(val.pickupslot).format('hh:mm A')}
                                        variant="light"
                                        sx={{
                                          color: '#0a803b',
                                          bgcolor: '#c3f3c7'
                                        }}
                                      />
                                    </Tooltip>
                                    <ArrowRightAltOutlined />
                                    <Tooltip title="Estimated Delivery time">
                                      <Typography noWrap sx={{ fontSize: '12px' }}>
                                        {dayjs(val.expectedDeliveryTime).format('DD/MM/YYYY')}
                                      </Typography>
                                      <Chip
                                        size="small"
                                        label={dayjs(val.expectedDeliveryTime).format('hh:mm A')}
                                        variant="light"
                                        sx={{
                                          color: '#DD2C00',
                                          background: '#FBE9E7'
                                        }}
                                      />
                                    </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 sx={{ cursor: 'pointer' }} 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 sx={{ cursor: 'pointer' }} variant="caption">
                                          {val.deliverysuburb || val.deliveryaddress.slice(0, 20)}
                                        </Typography>
                                      </Tooltip>
                                    </Stack>
                                  </Stack>
                                </TableCell>
                                <TableCell align="left">
                                  <Typography variant="caption" sx={{ whiteSpace: 'nowrap' }}>
                                    {val.ordernotes}
                                  </Typography>
                                </TableCell>

                                <TableCell align="left">
                                  <Typography variant="caption" sx={{ whiteSpace: 'nowrap' }}>
                                    {val.rider}
                                  </Typography>
                                  <br />
                                  <Typography variant="caption">ID : {val.userid}</Typography>
                                </TableCell>

                                <TableCell align="center">
                                  <Chip
                                    size="small"
                                    label={val.ordertype}
                                    icon={
                                      val.ordertype === 'Economy' ? (
                                        <EnergySavingsLeafIcon />
                                      ) : val.ordertype === 'Risky' ? (
                                        <WarningIcon />
                                      ) : (
                                        <BoltIcon />
                                      )
                                    }
                                    color={val.ordertype === 'Economy' ? 'success' : val.ordertype === 'Risky' ? 'error' : 'primary'}
                                    variant="light"
                                  />
                                </TableCell>
                                <TableCell align="center">
                                  <Chip
                                    size="small"
                                    label={`₹ ${parseFloat(val?.profit).toFixed(2)}`}
                                    variant="light"
                                    sx={{
                                      color: '#009688',
                                      bgcolor: '#b2dfdb'
                                    }}
                                  />
                                </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)} `}
                                        variant="light"
                                        sx={{
                                          color: '#0074e7',
                                          bgcolor: '#cce3fa'
                                        }}
                                      />
                                    </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>
                            </Fragment>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                  </AccordionDetails>
                </Accordion>
              );
            })}
          </MainCard>
        </DialogContent>
        <DialogActions>
          <Stack display={'flex'} flexDirection={'row'} gap={2} alignItems={'center'} justifyContent={'end'} sx={{ p: 2 }}>
            <Button
              sx={{}}
              variant="contained"
              color="secondary"
              startIcon={<ArrowBackIcon />}
              onClick={() => {
                // navigate('/nearle/orders');
                setAiDialog(false);
              }}
            >
              Back
            </Button>
            <Button sx={{ my: 2 }} 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;
