import { React, useState, useEffect, useRef } from 'react';
import TitleCard from 'pages/titleCard';
import axios from 'axios';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { Empty } from 'antd';
import { useTheme } from '@mui/material/styles';
import MapWithRoute from './mapWithRoute';
import { FaCircleCheck } from 'react-icons/fa6';
import CircularLoader from 'components/CircularLoader';
import DownloadOutlinedIcon from '@mui/icons-material/DownloadOutlined';

// material-ui
import {
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Dialog,
  Typography,
  Stack,
  Tooltip,
  Chip,
  Autocomplete,
  Badge,
  TextField,
  Backdrop,
  Button,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  DialogTitle,
  Box,
  Skeleton
} from '@mui/material';
import { CloseCircleFilled, EnvironmentFilled, EnvironmentOutlined } from '@ant-design/icons';
import { CalendarMonth } from '@mui/icons-material';
import { fetchDeliveries, getriderbydelivery, gettenantlocations, getTenants } from 'pages/api/api';
import MainCard from 'components/MainCard';
import { CSVExport } from 'components/third-party/ReactTable';
import Loader from 'components/Loader';
import { enqueueSnackbar } from 'notistack';
import DateFilterDialog from 'components/DateFilterDialog';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import LoaderWithImage from 'components/nearle_components/LoaderWithImage';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import dayjs from 'dayjs';
import { OpenToast } from 'components/third-party/OpenToast';
import TableLoader from 'components/nearle_components/TableLoader';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

const opentoast = (message, variant, time) => {
  enqueueSnackbar(message, {
    variant: variant,
    anchorOrigin: { vertical: 'top', horizontal: 'right' },
    autoHideDuration: time ? time : 1500
  });
};

const headCells = [
  {
    id: 'sno',
    disablePadding: false,
    label: '#'
  },
  {
    id: 'map',
    disablePadding: false,
    label: '^'
  },
  {
    id: 'tenantname',
    disablePadding: false,
    label: 'Client'
  },

  {
    id: 'Pickup loco',
    disablePadding: false,
    label: 'Pickup'
  },
  {
    id: 'Delivery loco',
    disablePadding: false,
    label: 'Drop'
  },
  {
    id: 'order status',
    disablePadding: false,
    label: 'status'
  },
  {
    id: 'assigned',
    disablePadding: false,
    label: 'assigned'
  },
  {
    id: 'Accepted',
    disablePadding: false,
    label: 'Accepted'
  },
  {
    id: 'arrived',
    disablePadding: false,
    label: 'arrived'
  },
  {
    id: 'picked',
    disablePadding: false,
    label: 'picked'
  },
  {
    id: 'active',
    disablePadding: false,
    label: 'active'
  },

  {
    id: 'Delivered',
    disablePadding: false,
    label: 'Delivered'
  },
  {
    id: 'cancelled',
    disablePadding: false,
    label: 'cancelled'
  },

  {
    id: ' notes',
    disablePadding: false,
    label: 'NOTES'
  },

  {
    id: 'kms',
    disablePadding: false,
    label: 'KMS',
    numeric: 'center'
  },

  {
    id: 'charges',
    numeric: 'center',
    label: 'Charges',
    disablePadding: false
  }
];

// ==============================|| MUI TABLE - ENHANCED ||============================== //

export default function OrdersDetails() {
  const theme = useTheme();
  const csvRef = useRef(null);
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const locationRef = useRef(null);
  const tenantRef = useRef(null);
  const textFieldRef = useRef(null);
  const userid = localStorage.getItem('userid');
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(50);
  const [locaName, setLocoName] = useState('All');
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [open, setOpen] = useState(false);
  const [mapOpen, setMapOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [appId, setAppId] = useState(0);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [riderCoordinates, setRiderCoordinates] = useState([]);
  const [riderStart, setRiderStart] = useState();
  const [riderEnd, setRiderEnd] = useState();
  const [mapTenant, setMapTenant] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [logsLoading, setLogsLoading] = useState(false);
  let [total, settotal] = useState(0);
  let [deliveredLenght, setDeliveredLenght] = useState(0);
  let [pendingLenght, setPendingLenght] = useState(0);
  let [cancelLenght, setCancelLenght] = useState(0);
  let [assignLenght, setAssignLenght] = useState(0);
  let [pickedLenght, setPickedLenght] = useState(0);
  let [activeLenght, setActiveLenght] = useState(0);
  let [arrivesLenght, setArrivedLenght] = useState(0);
  let [skippedLenght, setSkippedLenght] = useState(0);
  const [statusCount, setStatusCount] = useState(0);
  const [currentStatus, setCurrentStatus] = useState('All');
  const [locationid, setLocationid] = useState(0);
  const [tenantid, setTenantid] = useState(0);
  const [tenantValue, setTenantValue] = useState(null);
  const [locationValue, setLocationValue] = useState(null);
  const [selectedRider, setSelectedRider] = useState();
  const [riderId, setRiderId] = useState();
  const [riderValue, setRiderValue] = useState(null);
  const [reportDialog, setReportDialog] = useState(false);

  const status = [
    { id: 0, status: 'All', statusLow: 'All', count: total },
    { id: 1, status: 'Pending', statusLow: 'pending', count: pendingLenght },
    { id: 2, status: 'Accepted', statusLow: 'accepted', count: assignLenght },
    { id: 3, status: 'Arrived', statusLow: 'arrived', count: arrivesLenght },
    { id: 4, status: 'Picked', statusLow: 'picked', count: pickedLenght },
    { id: 5, status: 'Active', statusLow: 'active', count: activeLenght },
    { id: 6, status: 'Delivered', statusLow: 'delivered', count: deliveredLenght },
    { id: 7, status: 'Skipped', statusLow: 'skipped', count: skippedLenght },
    { id: 8, status: 'Cancelled', statusLow: 'cancelled', count: cancelLenght }
  ];

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

  // Function to calculate distance between two coordinates using Haversine formula
  function calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // Radius of the Earth in kilometers
    const dLat = (lat2 - lat1) * (Math.PI / 180);
    const dLon = (lon2 - lon1) * (Math.PI / 180);
    const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // Distance in kilometers
    return distance;
  }

  // Function to calculate total distance traveled along the route
  function calculateTotalDistance(routeCoordinates) {
    let totalDistance = 0;
    for (let i = 0; i < routeCoordinates.length - 1; i++) {
      const { lat: lat1, lng: lon1 } = routeCoordinates[i];
      const { lat: lat2, lng: lon2 } = routeCoordinates[i + 1];
      const distance = calculateDistance(lat1, lon1, lat2, lon2);
      console.log('distance', distance);
      totalDistance += distance;
    }
    return totalDistance;
  }

  const getdeliverylogs = async (id) => {
    // setLogsLoading(true);
    console.log('deliveryid', id);
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL3}/deliveries/getdeliverylogs/?deliveryid=${id}`);
      console.log('getdeliverylogs', res.data.details);
      const datas = res.data.details;
      if (datas.length != 0) {
        setRiderStart(datas[0].logdate);
        setRiderEnd(datas[datas.length - 1].logdate);
        const coData = datas.map((data) => ({ lat: data.latitude, lng: data.longitude }));
        console.log('coData', coData);
        setRiderCoordinates(coData);
        const totalDistance = calculateTotalDistance(coData);
        // setRiderKms(totalDistance);
        console.log('Total distance traveled:', totalDistance, 'km');
        setMapOpen(true);
      } else if (datas == null || !datas) {
        opentoast('No Logs Found ', 'error', 2000);
      }
    } catch (error) {
      console.log('getdeliverylogs', error);
    } finally {
      // setLogsLoading(false);
    }
  };

  // ==============================|| fetchorderdetails (orders)||============================== //
  // const fetchorderdetails = async () => {
  //   setIsLoading(true);
  //   try {
  //     const response = await axios.get(
  //       appId == 0
  //         ? currentStatus == 'All'
  //           ? `${process.env.REACT_APP_URL2}/deliveries/getdeliveries/?appuserid=${userid}&fromdate=${startdate}&todate=${enddate}&pageno=${
  //               page + 1
  //             }&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
  //           : `${
  //               process.env.REACT_APP_URL2
  //             }/deliveries/getdeliveries/?appuserid=${userid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
  //               page + 1
  //             }&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
  //         : currentStatus == 'All'
  //         ? `${
  //             process.env.REACT_APP_URL2
  //           }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&applocationid=${appId}&pageno=${
  //             page + 1
  //           }&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
  //         : `${
  //             process.env.REACT_APP_URL2
  //           }/deliveries/getdeliveries/?fromdate=${startdate}&todate=${enddate}&applocationid=${appId}&status=${currentStatus}&pageno=${
  //             page + 1
  //           }&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
  //     );
  //     setRows(response.data.details || []);
  //     setIsLoading(false);
  //   } catch (error) {
  //     console.log('fetchorderdetails', error.message);
  //     setIsLoading(false);
  //   }
  // };

  // useEffect(() => {
  //   fetchorderdetails();
  // }, [appId, startdate, enddate, page, rowsPerPage, currentStatus]);

  const {
    data: deliveriesData,
    isLoading: fetchDeliveriesIsLoading,
    isError: fetchDeliveriesIsError,
    error: fetchDeliveriesError,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage
  } = useInfiniteQuery({
    queryKey: [
      'fetchdeliveries',
      appId,
      userid,
      currentStatus,
      startdate,
      enddate,
      rowsPerPage,
      debouncedSearch,
      tenantid,
      locationid,
      selectedRider?.userid || 0
    ],
    queryFn: fetchDeliveries,
    getNextPageParam: (lastPage) => lastPage.nextPage ?? undefined,
    refetchOnWindowFocus: true,
    refetchOnMount: true, // 👈 ensures API triggers on page navigation
    refetchOnReconnect: true
  });
  const rows = deliveriesData?.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();
      }
    }
  };
  // ==============================|| 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
  });
  // ==============================|| getRiders ||============================== //

  const {
    data: ridersList,
    isLoading: getriderbydeliveryIsLoading,
    isError: getriderbydeliveryIsError,
    error: getriderbydeliveryError
  } = useQuery({
    queryKey: ['getriderbydelivery', startdate, enddate, appId, tenantid, locationid],
    queryFn: () => getriderbydelivery(startdate, enddate, appId, tenantid, locationid),
    enabled: appId != 0
  });
  // ==============================|| 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
  });
  /* ============================================= || fetchcount | ============================================= */
  const fetchcount = async () => {
    setIsLoading(true);
    try {
      await axios
        .get(
          appId == 0
            ? `${process.env.REACT_APP_URL}/deliveries/deliverysummary/?fromdate=${startdate}&todate=${enddate}`
            : `${
                process.env.REACT_APP_URL
              }/deliveries/deliverysummary/?applocationid=${appId}&tenantid=${tenantid}&locationid=${locationid}&fromdate=${startdate}&todate=${enddate}&userid=${
                selectedRider?.userid || 0
              }`
        )
        .then((res) => {
          console.log('fetchcountres', res.data.details);
          settotal(res.data.details.total);
          currentStatus == 'All' && setStatusCount(res.data.details.total);
          setPendingLenght(res.data.details.pending);
          setAssignLenght(res.data.details.accepted);
          setArrivedLenght(res.data.details.arrived);
          setPickedLenght(res.data.details.picked);
          setActiveLenght(res.data.details.active);
          setDeliveredLenght(res.data.details.delivered);
          setSkippedLenght(res.data.details.skipped);
          setCancelLenght(res.data.details.cancelled);
        })
        .catch((err) => {
          console.log(err);
          enqueueSnackbar(err.message, {
            variant: 'error',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
          });
        });
    } catch (err) {
      console.log(err);
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(() => {
    fetchcount();
  }, [appId, startdate, enddate, currentStatus, tenantid, locationid, selectedRider]);

  // to download ex format filtered data
  const csvData = rows?.map((order) => ({
    tenantname: order.tenantname,
    tenantcity: order.tenantcity,
    tenantcontactno: order.tenantcontactno,
    rider: order.ridername,
    orderid: order.orderid,
    paymenttype: order.paymenttype == 64 ? 'Pay Later' : order.paymenttype == 42 ? 'Pay on Delivery' : 'Digital',
    deliverydate: order.deliverydate,
    orderstatus: order.orderstatus,
    ordernotes: order.ordernotes,
    kms: order.kms,
    cumulativekms: order.cumulativekms,
    assigntime: order.assigntime,
    starttime: order.starttime,
    arrivaltime: order.arrivaltime,
    pickuptime: order.pickuptime,
    deliverytime: order.deliverytime,
    canceltime: order.canceltime,
    deliverycharge: order.deliverycharges,
    deliveryamt: order.deliveryamt,
    pickupcustomer: order.pickupcustomer,
    pickupcontactno: order.pickupcontactno,
    Pickupaddress: order.pickupaddress,
    pickupsuburb: order.pickupsuburb,
    pickupcity: order.applocation,
    pickuplat: order.pickuplat,
    pickuplong: order.pickuplon,
    deliverycustomer: order.deliverycustomer,
    deliverycontactno: order.deliverycontactno,
    deliveryaddress: order.deliveryaddress,
    deliverysuburb: order.locationsuburb,
    deliverylat: order.deliverylat,
    deliverylong: order.deliverylong,
    locationname: order.locationname,
    locationsuburb: order.pickuplocation,
    deliverylocation: order.deliverylocation,
    locationcontactno: order.locationcontactno
  }));
  console.log('csvData', csvData);

  function formatDate(dateString) {
    const date = dayjs(dateString);
    const formattedDate = date.format('DD/MM/YYYY ');
    return formattedDate;
  }
  function formatTime(dateString) {
    const date = dayjs(dateString);
    const formattedDate = date.format(' hh:mm A');
    return formattedDate;
  }

  const errormessage = fetchDeliveriesIsError
    ? `An error has occurred: (fetchDeliveries) ${fetchDeliveriesError.message}`
    : fetchtenantsIsError
    ? `An error has occurred: (getTenants) ${fetchtenantsError.message}`
    : fetchlocationsIsError
    ? `An error has occurred: (gettenantlocations) ${fetchlocationsError.message}`
    : getriderbydeliveryIsError
    ? `An error has occurred: (getriderbydelivery) ${getriderbydeliveryError.message}`
    : null;

  useEffect(() => {
    if (errormessage) {
      console.log('errormessage', errormessage);
      opentoast(errormessage, 'warning', 2000);
    }
  }, [errormessage]);
  return (
    <>
      {(isLoading ||
        fetchtenantsIsLoading ||
        fetchlocationsIsLoading ||
        logsLoading ||
        getriderbydeliveryIsLoading ||
        isFetchingNextPage) && (
        <div>
          <Loader />
          {/* <CircularLoader /> */}
        </div>
      )}
      {fetchDeliveriesIsLoading && (
        <Backdrop
          sx={{
            color: '#fff',
            zIndex: (theme) => theme.zIndex.drawer + 1
          }}
          open={fetchDeliveriesIsLoading} // when loader = true, backdrop covers the page
        >
          {/* <CircularLoader color="inherit" /> */}
        </Backdrop>
      )}
      <TitleCard
        title="Orders Details"
        secondary={
          <Stack display={'flex'} flexDirection={'row'} alignItems={'center '} gap={3} flexWrap={'wrap'}>
            <LocationAutocomplete
              ref={locationRef}
              locaName={locaName}
              setAppId={setAppId}
              setLocoName={setLocoName}
              setPage={setPage}
              sx={{ minWidth: 250, maxWidth: 1000, flex: 1 }}
            />
            <Autocomplete
              options={tenantlist || []}
              value={tenantValue}
              sx={{ minWidth: 250, maxWidth: 1000, flex: 1 }}
              onOpen={(event) => {
                if (!appId) {
                  event.preventDefault();
                  OpenToast('Please select a your app 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(val.locationid);
                  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: 1000, 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 a your  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" />}
            />
          </Stack>
        }
      />
      <MainCard
        content={false}
        title={
          <Stack sx={{ m: 2 }} gap={3}>
            <Stack direction="row" alignItems={'center'} gap={2} flexWrap={'wrap'} sx={{}}>
              {startdate && enddate && (
                <Stack direction="row" alignItems={'center'} gap={2} flexWrap={'wrap'}>
                  <Badge
                    badgeContent={!searchword ? statusCount : 0}
                    max={`${total}`}
                    color="primary"
                    sx={{
                      bgcolor: '#f3e5f5',
                      p: 0.2,
                      borderRadius: '3px',
                      color: '#7b1fa2'
                    }}
                  >{`Orders-${datestatus}`}</Badge>
                  <Tooltip title="Date Filter" placement="top">
                    <Chip
                      label={
                        <Typography noWrap color="secondary">
                          {dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
                        </Typography>
                      }
                      variant="combined"
                      color="warning"
                      size="small"
                      deleteIcon={<CalendarMonth style={{ fontSize: 18 }} />}
                      onDelete={() => {
                        setOpen(true);
                      }}
                      onClick={() => setOpen(true)}
                      sx={{ cursor: 'pointer' }}
                    />
                  </Tooltip>
                </Stack>
              )}
              <Button
                variant="outlined"
                size="small"
                startIcon={<DownloadOutlinedIcon />}
                onClick={() => {
                  setReportDialog(true);
                  setTimeout(() => {
                    setRowsPerPage('');
                  }, 0);
                }}
              >
                Export Report
              </Button>
            </Stack>
            <Stack display={'flex'} flexDirection={'row'} gap={2} alignItems={'center'} sx={{}} flexWrap={'wrap'}>
              <Autocomplete
                id="combo-box-demo"
                label={currentStatus}
                options={status}
                getOptionLabel={(option) => `${option.status}`}
                sx={{ minWidth: 250, maxWidth: 1000, flex: 1 }}
                onChange={(event, value, reason) => {
                  if (reason === 'clear') {
                    setCurrentStatus('All');
                    setStatusCount(status[0].count);
                  } else {
                    console.log('status', value);
                    setCurrentStatus(value.statusLow);
                    setStatusCount(value.count);
                  }
                }}
                renderInput={(params) => <TextField {...params} label={'Select Status'} />}
              />
              <Autocomplete
                id="combo-box-demo"
                value={riderValue}
                options={ridersList || []}
                getOptionLabel={(option) => `${option.firstname} ${option.lastname}`}
                sx={{ minWidth: 250, maxWidth: 1000, flex: 1 }}
                onOpen={() => {
                  if (!appId) {
                    OpenToast('Select App Location First', 'warning', 2000);
                  }
                }}
                onChange={(event, value, reason) => {
                  if (reason === 'clear') {
                    setSelectedRider(null);
                    setRiderId(0);
                    setRiderValue(null);
                  } else {
                    setSelectedRider(value);
                    setRiderId(value.userid);
                    setRiderValue(value);
                  }
                }}
                renderInput={(params) => <TextField {...params} label={'Select Rider'} />}
              />
              <DebounceSearchBar
                value={searchword}
                onChange={setSearchword}
                onDebouncedChange={setDebouncedSearch}
                sx={{ minWidth: 250, maxWidth: 1000, flex: 1 }}
              />
            </Stack>
          </Stack>
        }
      >
        <TableContainer
          ref={containerRef}
          onScroll={handleScroll}
          sx={{
            maxHeight: 'calc(100vh - 200px)',
            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 aria-label="sticky table">
            <TableHead
              sx={{
                '& th': {
                  borderTop: `1px solid ${theme.palette.divider}`,
                  borderBottom: `2px solid ${theme.palette.divider} !important`
                }
              }}
            >
              <TableRow sx={{ width: '100%' }}>
                {headCells.map((column) => (
                  <TableCell sx={{ position: 'sticky !important', width: '100%' }} key={column.id}>
                    {column.label}
                  </TableCell>
                ))}
              </TableRow>
            </TableHead>
            <TableBody>
              {fetchDeliveriesIsLoading ? (
                <TableLoader rows={16} columns={30} height={15} />
              ) : rows?.length == 0 ? (
                <TableRow>
                  <TableCell colSpan={15} sx={{ '&:hover': { bgcolor: 'white' } }}>
                    <Empty description="No Orders Found" />
                  </TableCell>
                </TableRow>
              ) : (
                rows?.map((row, index) => {
                  return (
                    <TableRow key={row.name}>
                      <TableCell sx={{ width: '10px' }}> {page * rowsPerPage + index + 1}</TableCell>
                      <TableCell
                        sx={{ width: '10px', cursor: 'pointer' }}
                        onClick={() => {
                          if (row.orderstatus == 'delivered') {
                            console.log('row', row);
                            getdeliverylogs(row.deliveryid);
                            setMapTenant(row);
                            setIsLoading(true);
                            setTimeout(() => {
                              setIsLoading(false);
                            }, 500);
                          } else {
                            return null;
                          }
                        }}
                      >
                        {row.orderstatus == 'delivered' ? (
                          <EnvironmentFilled style={{ color: theme.palette.primary.main }} />
                        ) : (
                          <EnvironmentOutlined style={{ color: theme.palette.secondary.main }} />
                        )}
                      </TableCell>
                      {/* ================================================ || Client || ================================================ */}
                      <TableCell
                        sx={{
                          textAlign: 'start',
                          whiteSpace: 'nowrap'
                        }}
                      >
                        {row.tenantname}
                        <Tooltip title={'OrderId'}>
                          <Typography variant="body2" noWrap sx={{ cursor: 'pointer' }}>
                            {row.orderid}
                          </Typography>
                        </Tooltip>
                        <Typography noWrap variant="body2">
                          {dayjs(row.deliverydate).utc().format('DD/MM/YYYY')}
                        </Typography>
                        <Typography noWrap variant="body2">
                          {dayjs(row.deliverydate).utc().format('hh:mm A')}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Pickup || ================================================ */}

                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1}>
                          <Stack direction="column">
                            <Typography noWrap>{row.pickupcustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.pickupcontactno}
                            </Typography>
                            <Tooltip title={row.Pickupaddress || row.pickupsuburb}>
                              <Typography
                                noWrap
                                variant="caption"
                                color="textSecondary"
                                sx={{ cursor: 'pointer', textOverflow: 'ellipsis' }}
                              >
                                {` ${row.pickupsuburb || row.Pickupaddress.slice(0, 20) + '...'}`}
                              </Typography>
                            </Tooltip>
                            <Typography noWrap variant="caption" color="textSecondary">
                              {row.applocation}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>
                      {/* ================================================ || Drop || ================================================ */}

                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1}>
                          <Stack direction="column">
                            <Typography sx={{ whiteSpace: 'nowrap' }}>{row.deliverycustomer}</Typography>
                            <Typography variant="caption" color="textSecondary">
                              {row.deliverycontactno}
                            </Typography>
                            <Tooltip title={row.deliveryaddress}>
                              <Typography variant="caption" color="textSecondary" sx={{ cursor: 'pointer' }}>
                                {/* {row.pickupaddress.slice(0, 20)} */}
                                {`${row.deliverysuburb || row.deliveryaddress.slice(0, 20) + '...'}`}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      {/* ================================================ || Status || ================================================ */}

                      <TableCell align="left">
                        <Stack direction="row" sx={{ mb: 1 }}>
                          {row.orderstatus === 'created' && <Chip label="Created" color="primary" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'pending' && <Chip label="Pending" color="warning" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'accepted' && (
                            <Chip label="Accepted" size="small" sx={{ bgcolor: theme.palette.chip.accept, color: 'white', minWidth: 80 }} />
                          )}
                          {row.orderstatus === 'arrived' && (
                            <Chip label="Arrived" size="small" sx={{ bgcolor: theme.palette.chip.arrive, color: 'white', minWidth: 80 }} />
                          )}
                          {row.orderstatus === 'picked' && <Chip label="Picked" color="info" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'active' && <Chip label="Active" color="info" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'delivered' && <Chip label="Delivered" color="success" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'skipped' && <Chip label="Skipped" color="secondary" size="small" sx={{ minWidth: 80 }} />}
                          {row.orderstatus === 'cancelled' && <Chip label="Cancelled" color="error" size="small" sx={{ minWidth: 80 }} />}
                        </Stack>
                        <Tooltip title={row.ridername}>
                          <Typography variant="subtitle2" display="block" sx={{ cursor: 'pointer', whiteSpace: 'nowrap' }}>
                            {row.ridername}
                          </Typography>
                          <Typography variant="subtitle2" display="block" sx={{ cursor: 'pointer', whiteSpace: 'nowrap' }}>
                            ID : {row.userid}
                          </Typography>
                        </Tooltip>
                      </TableCell>
                      {/* ================================================ || Assigned || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.assigntime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.assigntime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.assigntime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.assigntime)
                          )}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Accepted || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.acceptedtime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.acceptedtime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.acceptedtime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.acceptedtime)
                          )}
                        </Typography>
                      </TableCell>

                      {/* ================================================ || Arrived || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.arrivaltime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.arrivaltime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.arrivaltime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.arrivaltime)
                          )}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Picked || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.pickuptime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.pickuptime)
                          )}
                        </Typography>
                        <Stack direction={'row'}>
                          <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                            {row.pickuptime === '' ? (
                              <Skeleton animation={false} variant="text" width={60} height={18} />
                            ) : (
                              formatTime(row.pickuptime)
                            )}
                          </Typography>
                          {row.deliverystatus === 'active' && (
                            <FaCircleCheck fontSize={'large'} style={{ color: 'green', marginLeft: '8px' }} />
                          )}
                        </Stack>
                      </TableCell>

                      {/* ================================================ || Active || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.starttime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.starttime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.starttime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.starttime)
                          )}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Delivered || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.deliverytime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.deliverytime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.deliverytime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.deliverytime)
                          )}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Cancelled || ================================================ */}

                      <TableCell align="left">
                        <Typography noWrap sx={{ fontSize: '12px' }}>
                          {row.canceltime === '' ? (
                            <Skeleton animation={false} variant="text" width={80} height={14} />
                          ) : (
                            formatDate(row.canceltime)
                          )}
                        </Typography>
                        <Typography noWrap sx={{ fontSize: '13px' }} variant="h5">
                          {row.canceltime === '' ? (
                            <Skeleton animation={false} variant="text" width={60} height={18} />
                          ) : (
                            formatTime(row.canceltime)
                          )}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Notes || ================================================ */}

                      <TableCell align="left">
                        <Typography variant="caption">
                          {row.ordernotes || <Skeleton animation={false} variant="text" width={40} height={18} />}
                        </Typography>
                      </TableCell>
                      {/* ================================================ || Kms || ================================================ */}

                      <TableCell align="center">
                        <Stack direction={'column'} spacing={1}>
                          <Tooltip title=" KMS" placement="top">
                            <Chip
                              label={row.deliverystatus === 'cancelled' || row.kms == '' ? 0 : row.kms}
                              size="small"
                              variant="light"
                              color="error"
                              sx={{
                                minWidth: 80,
                                border: '1px solid  #e96969',
                                cursor: 'pointer'
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="Actual KMS" placement="left">
                            <Chip
                              label={row.cumulativekms}
                              size="small"
                              color="success"
                              variant="light"
                              onClick={() => {}}
                              sx={{
                                minWidth: 80,
                                border: '1px solid #76ff03 ',
                                cursor: 'pointer'
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="Rider KMS">
                            <Chip
                              label={row.previouskms || (row.deliverystatus == 'cancelled' ? '0.00' : row.kms)}
                              size="small"
                              color="info"
                              variant="light"
                              onClick={() => {}}
                              sx={{
                                minWidth: 80,
                                border: '1px solid #03a9f4 ',
                                cursor: 'pointer'
                              }}
                            />
                          </Tooltip>
                        </Stack>
                      </TableCell>
                      {/* ================================================ || Charges || ================================================ */}

                      <TableCell align="center">
                        <Stack direction={'column'} spacing={1}>
                          <Tooltip title=" Delivery Charge" placement="top">
                            <Chip
                              label={
                                row.orderstatus === 'cancelled' || row.deliverycharges == '' ? `₹ ${0}.00` : `₹ ${row.deliverycharges}.00`
                              }
                              size="small"
                              variant="light"
                              color="error"
                              sx={{
                                minWidth: 80,
                                border: '1px solid  #e96969',
                                cursor: 'pointer'
                              }}
                            />
                          </Tooltip>
                          <Tooltip title="Delivery Amount">
                            <Chip
                              label={row.deliveryamt == '' ? `₹ ${0}.00` : `₹ ${row.deliveryamt}.00`}
                              size="small"
                              color="success"
                              variant="light"
                              sx={{
                                minWidth: 80,
                                border: '1px solid #76ff03 ',
                                cursor: 'pointer'
                              }}
                            />
                          </Tooltip>
                        </Stack>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
          <Divider />
          {rows?.length !== 0 && (
            <Stack justifyContent="center" alignItems="center" sx={{ width: '100%', py: 2 }}>
              <Stack ref={loadMoreRef} style={{ textAlign: 'center', width: '100%' }}>
                {isFetchingNextPage ? <LoaderWithImage /> : hasNextPage ? <LoaderWithImage /> : 'No More Orders Details'}
              </Stack>
            </Stack>
          )}
        </TableContainer>
      </MainCard>
      {/* ============================================= || Report Download Dialog | =============================================  */}
      <Dialog open={reportDialog} onClose={() => setReportDialog(false)} fullWidth maxWidth={'sm'}>
        <DialogTitle sx={{ bgcolor: 'primary.main', color: 'white' }}>
          <Typography variant="h3">Export Report</Typography>
        </DialogTitle>
        <DialogContent>
          {fetchDeliveriesIsLoading && <CircularLoader />}
          <List gap={2} sx={{ width: '100%' }}>
            <ListItem
              sx={{ bgcolor: 'primary.lighter' }}
              secondaryAction={<Chip size="small" label={locaName || 'None'} color={locaName ? 'primary' : 'secondary'} />}
            >
              <Typography variant="h5" fontWeight={500}>
                App Location
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'secondary.lighter' }}
              secondaryAction={
                <Chip size="small" label={tenantValue?.tenantname || 'None'} color={tenantValue?.tenantname ? 'primary' : 'secondary'} />
              }
            >
              <Typography variant="h5" fontWeight={500}>
                Tenant
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'primary.lighter' }}
              secondaryAction={
                <Chip
                  size="small"
                  label={locationValue?.locationname || 'None'}
                  color={locationValue?.locationname ? 'primary' : 'secondary'}
                />
              }
            >
              <Typography variant="h5" fontWeight={500}>
                Business Location
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'secondary.lighter' }}
              secondaryAction={<Chip size="small" label={currentStatus || 'None'} color={currentStatus ? 'primary' : 'secondary'} />}
            >
              <Typography variant="h5" fontWeight={500}>
                Status
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'primary.lighter' }}
              secondaryAction={
                <Chip
                  size="small"
                  label={riderValue ? `${riderValue.firstname} ${riderValue.lastname}` : 'None'}
                  color={riderValue ? 'primary' : 'secondary'}
                />
              }
            >
              <Typography variant="h5" fontWeight={500}>
                Rider
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'secondary.lighter' }}
              secondaryAction={<Chip size="small" label={searchword || 'None'} color={searchword ? 'primary' : 'secondary'} />}
            >
              <Typography variant="h5" fontWeight={500}>
                Keyword
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'primary.lighter' }}
              secondaryAction={<Chip size="small" label={startdate || 'None'} color={startdate ? 'primary' : 'secondary'} />}
            >
              <Typography variant="h5" fontWeight={500}>
                Start Date
              </Typography>
            </ListItem>

            <ListItem
              sx={{ bgcolor: 'secondary.lighter' }}
              secondaryAction={<Chip size="small" label={enddate || 'None'} color={enddate ? 'primary' : 'secondary'} />}
            >
              <Typography variant="h5" fontWeight={500}>
                End Date
              </Typography>
            </ListItem>
          </List>
        </DialogContent>
        <DialogActions sx={{ width: '100%', bgcolor: 'secondary.lighter' }}>
          {/* Visible Button */}
          <Button
            color={'error'}
            variant="contained"
            startIcon={<CloseCircleFilled />}
            onClick={() => {
              setReportDialog(false);
            }}
            sx={{}}
          >
            Close
          </Button>
          <CSVExport
            data={csvData}
            filename={`Orders_Detail_${dayjs().format('YYYY-MM-DD_HHmmss')}.csv`}
            label="Download CSV"
            style={{ m: 1 }}
            btnLoading={fetchDeliveriesIsLoading}
            onClick={() => {
              setTimeout(() => setReportDialog(false), 0);
            }}
          />
        </DialogActions>
      </Dialog>
      {/* ============================================= || 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);
        }}
      />
      {/* ============================================= || map dialog | =============================================  */}
      <Dialog
        open={mapOpen}
        onClose={() => {
          setMapOpen(false);
        }}
        fullScreen
        fullWidth
      >
        {riderCoordinates && (
          <div>
            <MapWithRoute
              coordinates={riderCoordinates}
              additionalProps={{ riderStart, riderEnd }}
              order={mapTenant}
              setMapOpen={setMapOpen}
            />
          </div>
        )}
        {/* {riderCoordinates && (
          <div>
            <MapWithRouteGoogle
              coordinates={riderCoordinates}
              additionalProps={{ riderStart, riderEnd }}
              order={mapTenant}
              setMapOpen={setMapOpen}
            />
          </div>
        )} */}
      </Dialog>
    </>
  );
}
