import { enqueueSnackbar } from 'notistack';
import { DeleteFilled } from '@ant-design/icons';
import { useState, useEffect, Fragment, useRef } from 'react';
import { Empty } from 'antd';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import axios from 'axios';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import ClearIcon from '@mui/icons-material/Clear';
import { MdOutlineDateRange } from 'react-icons/md';
import { MdOutlineDeliveryDining } from 'react-icons/md';
import { useQuery, useMutation } from '@tanstack/react-query';
import {
  Avatar,
  Box,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  Chip,
  Typography,
  Table,
  TableCell,
  TableBody,
  TableHead,
  Collapse,
  Dialog,
  TableRow,
  DialogContent,
  DialogTitle,
  Tooltip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Skeleton,
  DialogActions,
  Popper,
  ClickAwayListener,
  Checkbox,
  Autocomplete,
  TextField,
  FormLabel,
  TablePagination,
  TableContainer,
  TableSortLabel
} from '@mui/material';
import MainCard from 'components/MainCard';
import { SearchOutlined, MoreOutlined, CloseOutlined } from '@ant-design/icons';
import { PopupTransition } from 'components/@extended/Transitions';
import {
  addDays,
  addMonths,
  addWeeks,
  // addYears,
  endOfMonth,
  endOfWeek,
  // endOfYear,
  startOfMonth,
  startOfWeek
  // startOfYear,
} from 'date-fns';
import { DateRangePicker } from 'mui-daterange-picker';
import * as React from 'react';
import { visuallyHidden } from '@mui/utils';
import Loader from 'components/Loader';
import { FilterList, KeyboardArrowDownOutlined, KeyboardArrowUpOutlined } from '@mui/icons-material';
import CircularLoader from 'components/nearle_components/CircularLoader';

import {
  cancelDeliveryAPI,
  changeRiderAPI,
  fetchCountAPI,
  fetchDeliveries,
  fetchPercentageAPI,
  notifyRider,
  updateDeliveryAPI,
  getorderdetails,
  getAllUsers
} from '../api/api';
import Titlecard from 'components/nearle_components/Titlecard';
import OpenToast from 'components/nearle_components/OpenToast';

// ================================================= || deliveries (initial point)|| =================================================
const Deliveries = () => {
  const [deliverylist, setDeliverylist] = useState([]);
  const [dialogopen, setDialogopen] = useState(false);
  const textFieldRef = useRef(null);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [tabstatus, setTabstatus] = useState('Pending');
  const theme = useTheme();
  const [tabvalue, setTabvalue] = useState(0);
  const [open, setOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [searchword, setSearchword] = useState('');
  const [kms, setKms] = useState('');
  const [actualkms, setActualkms] = useState('');
  const [deliveryamount, setDeliveryamount] = useState('');
  const [notes, setNotes] = useState('');
  const [currentorder, setCurrentorder] = useState({});
  const [deliverylat, setDeliverylat] = useState('');
  const [deliverylong, setDeliverylong] = useState('');
  const [currentStatus, setCurrentStatus] = useState('pending');
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [totalCount, setTotalCount] = React.useState();
  const [productCollapse, setProductCollapse] = useState(null);
  const [orderHeaderid, setOrderHeaderId] = useState(null);

  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  /* ============================================= || opentoast || ============================================= */

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



  // ==============================|| getorderdetails ||============================== //

  const { data: orderdetails, } = useQuery({
    queryKey: ['orderdetails', orderHeaderid],
    queryFn: () => getorderdetails(orderHeaderid),
    enabled: !!orderHeaderid // ✅ prevent initial fetch when undefined
  });

  const dialogclose = () => {
    setDialogopen(false);
  };

  // ======================================================= || headCells || =======================================================

  const headCells = [
    {
      id: 'sno',
      disablePadding: true,
      label: 'S NO'
    },

    {
      id: 'tenantname1',
      numeric: false,
      disablePadding: false,
      label: 'CLIENT'
    },
    {
      id: 'orderid',
      numeric: false,
      disablePadding: false,
      label: 'ORDER ID'
    },
    {
      id: 'eventname',
      disablePadding: false,
      label: 'Pickup'
    },
    {
      id: 'eventname4',
      disablePadding: false,
      label: 'Delivery'
    },
    {
      id: 'ordervalue',
      disablePadding: false,
      label: 'RIDER'
    },

    {
      id: 'itemcount2',
      disablePadding: false,
      label: 'KMS'
    },
 
    {
      id: 'itemcount4',
      disablePadding: false,
      label: 'AMOUNT'
    },
    {
      id: 'orderstatus',
      disablePadding: false,
      label: 'STATUS'
    },
    {
      id: 'itemcount',
      disablePadding: false,
      label: 'NOTES'
    }
 
  ];

  // ======================================================= || EnhancedTableHead || =======================================================

  function EnhancedTableHead(props) {
    const { order, orderBy, onRequestSort } = props;
    const createSortHandler = (property) => (event) => {
      onRequestSort(event, property);
    };

    return (
      <TableHead>
        <TableRow>
          {tabstatus == 'Created' && (
            <TableCell>
              <Checkbox
                indeterminate={deliverylist.length > 0 && deliverylist.length != rows.length}
                onChange={(e) => {
                  if (e.target.checked) {
                    setDeliverylist([...rows]);
                  } else {
                    setDeliverylist([]);
                  }
                }}
                checked={deliverylist.length == rows.length}
              />
            </TableCell>
          )}
          {headCells.map((headCell) => (
            <TableCell
              key={headCell.id}
              align={headCell.numeric ? 'right' : 'left'}
              padding={headCell.disablePadding ? 'none' : 'normal'}
              sortDirection={orderBy === headCell.id ? order : false}
            >
              <TableSortLabel
                active={orderBy === headCell.id}
                direction={orderBy === headCell.id ? order : 'asc'}
                onClick={createSortHandler(headCell.id)}
              >
                {headCell.label}
                {orderBy === headCell.id ? (
                  <Box component="span" sx={visuallyHidden}>
                    {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                  </Box>
                ) : null}
              </TableSortLabel>
            </TableCell>
          ))}
          <TableCell align="right">Action</TableCell>
        </TableRow>
      </TableHead>
    );
  }
  // ======================================================= || EnhancedTable || =======================================================

  function EnhancedTable() {


    const [selectedRow, setSelectedRow] = useState({});
    const [loading1, setLoading1] = useState(false);
    const [open, setOpen] = useState(false);
    const [anchorEl, setAnchorEl] = React.useState(null);
    const [open2, setOpen2] = useState('');
    const [cancelDeliveryOpen, setCancelDeliveryOpen] = useState(false);
    const [changeDialogOpen, setChangeDialogOpen] = useState(false);
    const [cancelFeed, setCancelFeed] = useState('');
    const [selectedRider, setSelectedRider] = useState(null);

    const handleClickAway = () => {
      setOpen2('');
    };

    // =========================================== ||  cancelDelivery || ===========================================

    const { mutate: cancelDelivery, isLoading: cancelDeliveryLoading } = useMutation({
      mutationFn: ({ selectedRow, cancelFeed }) => cancelDeliveryAPI(selectedRow, cancelFeed),
      onSuccess: () => {
        opentoast('Delivery Cancelled Successfully', 'success');
        setCancelDeliveryOpen(false);
        fetchCountRefetch(); // Refresh count data
        fetchDeliveriesRefetch(); // Refresh deliveries
      },
      onError: (error) => {
        opentoast(error.message, 'error');
      }
    });

    // ==============================|| cancelridernotification  ||============================== //

    const cancelridernotification = async () => {
      console.log('cancelridernotification', selectedRow);

      const response = await axios.post(`${process.env.REACT_APP_URL}/utils/notifyuser`, {
        token: selectedRow.userfcmtoken,
        notification: {
          title: 'NearleXpress',
          body: `${selectedRow.orderid} have been Cancelled`,
          sound: 'ring',
          image: ''
        },
        data: {
          type: 'cancel'
        }
      });
      return response.data;
    };

    // =========================================== ||  notifyrider || ===========================================

    const notifyRiderMutation = useMutation({
      mutationFn: notifyRider, // Using the separate function
      onSuccess: () => {
        enqueueSnackbar('Notification sent Successfully', {
          variant: 'success',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 3000
        });
      },
      onError: (error) => {
        enqueueSnackbar(error.message, {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 3000
        });
      }
    });

    // =========================================== ||  changerider || ===========================================
    const changeRiderMutation = useMutation({
      mutationFn: ({ selectedRider, selectedRow }) => changeRiderAPI(selectedRider, selectedRow),
      onSuccess: (res) => {
        setLoading1(false);
        setChangeDialogOpen(false);
        if (res.data.message === 'Success') {
          opentoast('Rider Changed Successfully', 'success');
        }
        fetchCountRefetch(); // Refresh count data
        fetchDeliveriesRefetch(); // Refresh deliveries
        if (!selectedRider.userfcmtoken) {
          OpenToast('Failed,Rider FCM Unavailable', 'error', 3000);
        } else {
          notifyRiderMutation.mutate(selectedRider.userfcmtoken);
        }
      },
      onError: (err) => {
        console.log(err);
        opentoast(err.message, 'error');
        setLoading1(false);
      }
    });



    const handleChangePage = (event, newPage) => {
      setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
      setRowsPerPage(parseInt(event.target.value, 10));
      setPage(0);
    };





    const errorMessage =  fetchDeliveriesIsError
      ? `Error fetching percentages: ${fetchDeliveriesError?.message}`
      : fetchPercentageIsError
      ? `Error fetching percentages: ${fetchPercentageError?.message}`
      : fetchCountIsError
      ? `Error fetching percentages: ${fetchCountError?.message}`
      : ridersListIsError
      ? `Error fetching percentages: ${ridersListError?.message}`
      : null;

    if (errorMessage) {
      opentoast(errorMessage,'error',2000)
    }

    return (
      <>
        <Box sx={{ width: '100%' }}>
          <TableContainer sx={{ width: '100%', borderBottom: 1, borderColor: 'divider' }}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>S.No </TableCell>
                  <TableCell>Tenant </TableCell>
                  <TableCell>Order ID </TableCell>
                  <TableCell> Pickup</TableCell>
                  <TableCell>Delivery </TableCell>
                  <TableCell>Rider </TableCell>
                  <TableCell>KMS </TableCell>
                  <TableCell>Amount </TableCell>
                  <TableCell>Status </TableCell>
                  <TableCell>Notes </TableCell>
                  <TableCell> Action</TableCell>
                </TableRow>
              </TableHead>
              {loading1 && (
                <>
                  <TableBody>
                    {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item) => (
                      <TableRow key={item}>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          {/* <Skeleton animation="wave" /> */}
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                        <TableCell>
                          <Skeleton animation="wave" />
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </>
              )}
              <TableBody>
                {rows.length == 0 && !loading1 && (
                  <>
                    <TableCell colSpan={11}>
                      <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                        <Empty />
                      </Stack>
                    </TableCell>
                  </>
                )}

                {rows.map((row, index) => {
                  return (
                    <>
                      <TableRow
                        role="checkbox"
                        tabIndex={-1}
                        key={row.sno}
                        sx={{
                          cursor: 'pointer',
                          // backgroundColor: (expandopen === row.sno) ? '#f5f5f5' : ''
                          backgroundColor: deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid) ? '#e1bee7' : '',
                          '&:hover': {
                            backgroundColor: deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid)
                              ? '#e1bee7 !important'
                              : ''
                          }
                        }}
                      >
                        {tabstatus == 'Created' && (
                          <TableCell
                        
                          >
                            <Checkbox
                              onChange={(e) => {
                                if (e.target.checked) {
                                  let arr = deliverylist;
                                  arr.push({ ...row, sno: deliverylist.length + 1 });

                                  setDeliverylist([...arr]);
                                } else {
                                  let res = deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid);
                                  if (res) {
                                    let arr = deliverylist;
                                    let res = deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid);
                                    arr.splice(res.sno - 1, 1);
                                    arr.map((val, i) => {
                                      val.sno = i + 1;
                                    });
                                    setDeliverylist([...arr]);
                                  }
                                }
                                console.log('list', deliverylist);
                              }}
                              checked={deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid)}
                            />
                          </TableCell>
                        )}

                        <TableCell>
                          {/* <Typography> {row.sno}</Typography> */}
                          <Typography> {page * rowsPerPage + index + 1}</Typography>
                        </TableCell>
                        <TableCell>
                          <Typography variant="subtitle1">{row.tenantname}</Typography>

                          <Tooltip title="tenanid-deliveryid">
                            <Typography variant="caption" color={'secondary'}>{`${row.tenantid}-${row.deliveryid}`}</Typography>
                          </Tooltip>
                          <Tooltip title="App Location">
                            <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                              {row.applocation}
                            </Typography>
                          </Tooltip>
                        </TableCell>
                        <TableCell align="left">
                          <Typography variant="body2" noWrap>
                            {row.orderid}
                          </Typography>
                          <Typography noWrap sx={{ fontSize: '11px' }}>
                            {dayjs(row.deliverydate).utc().format('DD/MM/YYYY')}
                          </Typography>
                          <Tooltip title="delivery date" placement="top-start">
                            <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                              {dayjs(row.deliverydate).utc().format('hh:mm A')}
                            </Typography>
                          </Tooltip>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{row.pickupcustomer}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {row.pickupcontactno}
                              </Typography>
                              <Tooltip title={row.Pickupaddress}>
                                <Typography variant="caption" color="textSecondary">
                                  {row.pickuplocation}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{row.deliverycustomer}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {row.deliverycontactno}
                              </Typography>
                              <Tooltip title={row.deliveryaddress}>
                                <Typography variant="caption" color="textSecondary">
                                  {row.deliverylocation || row.deliveryaddress.slice(0, 20)}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>

                        <TableCell>{row.ridername}</TableCell>
                        <TableCell>
                          <Stack direction={'column'} spacing={1}>
                            <Tooltip title=" KMS" placement="top">
                              <Chip label={row.kms || 0} size="small" variant="light" color="error" />
                            </Tooltip>
                            <Tooltip title="Actual KMS">
                              <Chip label={row.actualkms || 0} size="small" color="success" variant="light" />
                            </Tooltip>
                          </Stack>
                        </TableCell>

                        <TableCell align="left">
                          {' '}
                          <Stack direction={'column'} spacing={1}>
                            <Tooltip title=" Delivery Charge" placement="top">
                              <Chip label={`₹ ${row.deliverycharges}.00` || 0} size="small" variant="light" color="error" />
                            </Tooltip>
                            <Tooltip title="Delivery Amount">
                              <Chip label={`₹ ${row.deliveryamt}.00` || 0} size="small" color="success" variant="light" />
                            </Tooltip>
                          </Stack>
                        </TableCell>

                        <TableCell align="left">
                          <Stack direction="row">
                            {row.orderstatus === 'pending' && <Chip label="Pending" color="warning" size="small" />}
                            {row.orderstatus === 'modified' && <Chip label="Confirmed" color="success" size="small" />}
                            {row.orderstatus === 'cancelled' && <Chip label="Cancelled" color="error" size="small" />}
                            {row.orderstatus === 'delivered' && <Chip label="Completed" color="success" size="small" />}
                            {row.orderstatus === 'processing' && <Chip label="Processing" color="primary" size="small" />}
                            {row.orderstatus === 'ready' && <Chip label="Accepted" color="info" size="small" />}
                            {row.orderstatus === 'confirmed' && <Chip label="Confirmed" color="success" size="small" />}
                            {row.orderstatus === 'active' && <Chip label="Active" color="info" size="small" />}
                            {row.orderstatus === 'closed' && <Chip label="Closed" color="info" size="small" />}
                            {row.orderstatus === 'created' && <Chip label="Created" color="primary" size="small" />}
                            {row.orderstatus === 'picked' && <Chip label="Picked" color="info" size="small" />}
                            {row.orderstatus === 'accepted' && (
                              <Chip label="Accepted" size="small" sx={{ bgcolor: theme.palette.chip.accept, color: 'white' }} />
                            )}
                            {row.orderstatus === 'arrived' && (
                              <Chip label="Arrived" size="small" sx={{ bgcolor: theme.palette.chip.arrive, color: 'white' }} />
                            )}
                          </Stack>
                        </TableCell>
                        <TableCell align="left">{row.ordernotes}</TableCell>
                        <TableCell>
                          <Stack display={'flex'} flexDirection={'row'} justifyContent={'end'}>
                            {row.deliverytype == 'C' && (
                              <Tooltip title="Product details" placement="top">
                                <IconButton
                                  color="primary"
                                  onClick={() => {
                                    if (productCollapse?.orderid === row.orderid) {
                                      setProductCollapse(null); // Collapse if already open
                                      setOrderHeaderId(null);
                                    } else {
                                      setProductCollapse(row); // Open if different
                                      setOrderHeaderId(row.orderheaderid); // Open if different
                                    }
                                  }}
                                >
                                  {productCollapse?.orderid === row.orderid ? <KeyboardArrowUpOutlined /> : <KeyboardArrowDownOutlined />}
                                </IconButton>
                              </Tooltip>
                            )}
                            {row.orderstatus == 'created' && deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid) && (
                              <>
                                {/* <Tooltip title='Accept'> */}
                                <IconButton
                                  // disabled
                                  aria-describedby={`aria-${row.sno}`}
                                  onClick={(e) => {
                                    console.log('to update', row);
                                    e.stopPropagation();
                                    setAnchorEl(e.currentTarget);
                                    // setOpen2(row.sno);
                                    setOpen2(index + 1);
                                  }}
                                >
                                  <MoreOutlined />
                                </IconButton>
                                <Popper
                                  id={`aria-${row.sno}`}
                                  open={open2 == index + 1}
                                  anchorEl={anchorEl}
                                  placement="bottom-end"
                                  sx={{
                                    zIndex: 5000,
                                    p: 0
                                  }}
                                >
                                  <Box
                                    sx={{ backgroundColor: '#fff', px: 2, py: 1, cursor: 'pointer', boxShadow: theme.customShadows.z1 }}
                                    onClick={() => {
                                      setDialogopen(true);
                                      // setOpen1(true)
                                      handleClickAway();
                                    }}
                                  >
                                    <ClickAwayListener onClickAway={handleClickAway}>
                                      <Typography>Assign</Typography>
                                    </ClickAwayListener>
                                  </Box>
                                </Popper>
                                {/* </Tooltip> */}
                              </>
                            )}
                            {row.orderstatus == 'created' && (
                              <Tooltip title="Cancel">
                                <IconButton
                                  disabled
                                  // disabled={(row.orderstatus != 'created')}
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    setOpen(true);
                                    // navigate(`/details`, {
                                    //   state: {
                                    //     orderheaderid: row.orderheaderid,
                                    //     tenanid: row.tenanid
                                    //   }
                                    // })
                                  }}
                                >
                                  {/* <EyeTwoTone twoToneColor={theme.palette.secondary.main} /> */}
                                  <CloseOutlined
                                    style={{
                                      color: theme.palette.error.main
                                    }}
                                    //  twoToneColor={theme.palette.primary.main}
                                  />
                                </IconButton>
                              </Tooltip>
                            )}
                            {row.orderstatus != 'cancelled' && (
                              <>
                                <IconButton
                                  aria-describedby={`aria-${row.sno}`}
                                  onClick={(e) => {
                                    setAnchorEl(e.currentTarget);

                                    setOpen2(row.sno);
                                    setSelectedRow(row);
                                    console.log('selectedrow', row);
                                  }}
                                >
                                  <MoreOutlined />
                                </IconButton>
                                <Popper
                                  id={`aria-${row.sno}`}
                                  // open={open2 == index + 1}
                                  open={open2 == row.sno}
                                  anchorEl={anchorEl}
                                  placement="bottom-end"
                                  sx={{
                                    zIndex: 5000,
                                    p: 0
                                  }}
                                >
                                  {/* =============================== || Notify Rider|| =============================== */}

                                  {row.orderstatus !== 'delivered' && (
                                    <Box
                                      sx={{
                                        backgroundColor: '#fff',
                                        px: 2,
                                        py: 1,
                                        cursor: 'pointer',
                                        boxShadow: theme.customShadows.z1,
                                        '&:hover': {
                                          backgroundColor: '#eee'
                                        }
                                      }}
                                      onClick={() => {
                                        if (!row.userfcmtoken) {
                                          OpenToast('Failed,Rider FCM Unavailable', 'error', 3000);
                                        } else {
                                          notifyRiderMutation.mutate(row.userfcmtoken);
                                        }
                                        handleClickAway();
                                      }}
                                    >
                                      <ClickAwayListener onClickAway={handleClickAway}>
                                        <Typography>Notify Rider</Typography>
                                      </ClickAwayListener>
                                    </Box>
                                  )}
                                  {/* =============================== || change rider || =============================== */}

                                  {row.orderstatus === 'pending' || row.orderstatus === 'accepted' || row.orderstatus === 'arrived' ? (
                                    <Box
                                      sx={{
                                        backgroundColor: '#fff',
                                        px: 2,
                                        py: 1,
                                        cursor: 'pointer',
                                        boxShadow: theme.customShadows.z1,
                                        '&:hover': {
                                          backgroundColor: '#eee'
                                        }
                                      }}
                                      onClick={() => {
                                        setChangeDialogOpen(true);
                                        setSelectedRow(row);
                                      }}
                                    >
                                      <Typography> Change Rider</Typography>
                                    </Box>
                                  ) : null}

                                  {/* =============================== || Update Delivery Status || =============================== */}

                                  <Box
                                    sx={{
                                      backgroundColor: '#fff',
                                      px: 2,
                                      py: 1,
                                      cursor: 'pointer',
                                      boxShadow: theme.customShadows.z1,
                                      '&:hover': {
                                        backgroundColor: '#eee'
                                      }
                                    }}
                                    onClick={() => {
                                      setKms(row.kms);
                                      setActualkms(row.actualkms);
                                      setDeliverylat(row.droplat);
                                      setDeliverylong(row.droplon);
                                      setNotes(row.notes);
                                      setDeliveryamount(row.deliveryamount);
                                      setCurrentorder(row);

                                      setDialogopen(true);

                                      handleClickAway();
                                    }}
                                  >
                                    <ClickAwayListener onClickAway={handleClickAway}>
                                      <Typography>Update Delivery Status</Typography>
                                    </ClickAwayListener>
                                  </Box>

                                  {/* =============================== || Cancel Delivery || =============================== */}
                                  {row.orderstatus !== 'cancelled' && row.orderstatus !== 'delivered' && (
                                    <Box
                                      sx={{
                                        backgroundColor: '#fff',
                                        px: 2,
                                        py: 1,
                                        cursor: 'pointer',
                                        boxShadow: theme.customShadows.z1,
                                        '&:hover': {
                                          backgroundColor: '#eee'
                                        }
                                      }}
                                      onClick={() => {
                                        // alert('called');
                                        setCancelDeliveryOpen(true);
                                        // console.log('Cancel rider', selectedRow);
                                      }}
                                    >
                                      <>
                                        <Typography>Cancel Delivery </Typography>
                                      </>
                                    </Box>
                                  )}
                                </Popper>
                              </>
                            )}{' '}
                          </Stack>
                        </TableCell>
                      </TableRow>
                      {productCollapse?.orderid === row?.orderid && (
                        <TableRow>
                          <TableCell
                            colSpan={11}
                            sx={{
                              p: 0,
                              border: 0,
                              '&:hover': {
                                backgroundColor: 'white' // or use 'inherit'
                              }
                            }}
                          >
                            <Collapse in={true} timeout="auto" unmountOnExit>
                              <Box
                                sx={{
                                  width: '100%',
                                  border: `1px solid ${theme.palette.divider}`,
                                  // backgroundColor: theme.palette.primary.lighter,
                                  px: 2,
                                  py: 2
                                }}
                              >
                                <Table size="small" sx={{ minWidth: 800 }}>
                                  <TableHead>
                                    <TableRow
                                      sx={{
                                        '&:hover': {
                                          backgroundColor: 'transparent !important'
                                        }
                                      }}
                                    >
                                      <TableCell sx={{ fontWeight: 600 }}>S.No</TableCell>
                                      <TableCell sx={{ fontWeight: 600 }}>Product Name</TableCell>
                                      <TableCell sx={{ fontWeight: 600 }}>Description</TableCell>
                                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                                        Quantity
                                      </TableCell>
                                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                                        Cost
                                      </TableCell>
                                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                                        Price
                                      </TableCell>
                                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                                        Tax
                                      </TableCell>
                                      <TableCell align="right" sx={{ fontWeight: 600 }}>
                                        Amount
                                      </TableCell>
                                    </TableRow>
                                  </TableHead>

                                  <TableBody>
                                    {orderdetails?.details?.map((product, index) => (
                                      <TableRow
                                        key={index}
                                        sx={{
                                          '&:hover': {
                                            backgroundColor: 'transparent !important'
                                          }
                                        }}
                                      >
                                        <TableCell>{index + 1}</TableCell>
                                        <TableCell>
                                          <Stack direction="row" spacing={1} alignItems="center">
                                            <img
                                              src={product?.productimage || 'https://via.placeholder.com/40'} // fallback image
                                              alt={product?.productname}
                                              style={{
                                                width: 40,
                                                height: 40,
                                                objectFit: 'cover',
                                                borderRadius: 4
                                              }}
                                            />
                                            <Typography variant="body2" noWrap>
                                              {product?.productname || 'Unnamed'}
                                            </Typography>
                                          </Stack>
                                        </TableCell>
                                        <TableCell>{product?.productdescription || '-'}</TableCell>
                                        <TableCell align="right">{product?.orderqty || 0}</TableCell>
                                        <TableCell align="right">₹ {product?.price || 0}</TableCell>
                                        <TableCell align="right">₹ {(product?.productsumprice).toFixed(2) || 0}</TableCell>
                                        <TableCell align="right">₹ {(product?.taxamount).toFixed(2) || 0}</TableCell>
                                        <TableCell align="right">
                                          ₹ {(product?.productsumprice + product?.taxamount).toFixed(2) || 0}
                                        </TableCell>
                                      </TableRow>
                                    ))}
                                    <TableRow
                                      sx={{
                                        '&:hover': {
                                          backgroundColor: 'transparent !important'
                                        }
                                      }}
                                    >
                                      <TableCell align="right" colSpan={7} sx={{}}>
                                        Total Amount :
                                      </TableCell>
                                      <TableCell align="right" sx={{}}>
                                        ₹ {orderdetails?.pricedetails?.orderamount.toFixed(2)}
                                      </TableCell>
                                    </TableRow>
                                  </TableBody>
                                </Table>
                              </Box>
                            </Collapse>
                          </TableCell>
                        </TableRow>
                      )}
                    </>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions={[5, 10, 50, 100, 1000]}
            component="div"
            // count={rows.length}
            count={totalCount}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
          {/* =============================== || cancel dialog || =============================== */}
          <Dialog open={cancelDeliveryOpen} onClose={() => setCancelDeliveryOpen(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="h5" align="center">
                    Are you sure you want to cancel this delivery?
                  </Typography>
                </Stack>
                <TextField
                  fullWidth
                  label="Enter Feedback"
                  multiline
                  maxRows={4}
                  onChange={(e) => {
                    setCancelFeed(e.target.value);
                  }}
                />
                <Stack direction="row" spacing={2} sx={{ width: 1 }}>
                  <Button
                    // disabled={cancelFeed == '' ? true : false}
                    fullWidth
                    color="error"
                    variant="contained"
                    onClick={() => {
                      {
                        cancelFeed == '' ? opentoast('Enter FeedBack', 'error') : cancelDelivery({ selectedRow, cancelFeed });
                      }
                      cancelridernotification();
                    }}
                    autoFocus
                    sx={{ border: '1px solid red' }}
                  >
                    Yes, Cancel
                  </Button>
                  <Button
                    fullWidth
                    onClick={() => {
                      setCancelDeliveryOpen(false);
                    }}
                    color="secondary"
                    variant="outlined"
                  >
                    No
                  </Button>
                </Stack>
              </Stack>
            </DialogContent>
          </Dialog>
          {/* =============================== || change dialog || =============================== */}
          <Dialog
            open={changeDialogOpen}
            onClose={() => setChangeDialogOpen(false)}
            maxWidth="sm"
            fullWidth
            TransitionComponent={PopupTransition}
          >
            <DialogTitle sx={{ bgcolor: theme.palette.primary.main }}>
              <Typography variant="h3" sx={{ color: 'white' }}>
                Change Rider
              </Typography>
            </DialogTitle>
            <DialogContent dividers>
              <Grid container spacing={2}>
                <Grid item xs={12} sx={{ m: 2 }}>
                  <Autocomplete
                    fullWidth
                    options={ridersList}
                    getOptionLabel={(option) => `${option.firstname} (${option.contactno})`}
                    renderInput={(params) => <TextField {...params} label="Choose Rider" />}
                    onChange={(e, value) => {
                      setSelectedRider(value);
                      console.log('selected rider', value);
                    }}
                  />
                </Grid>
              </Grid>
            </DialogContent>
            <DialogActions>
              <Stack direction={'row'} spacing={3}>
                <Button
                  variant="outlined"
                  color="secondary"
                  onClick={() => {
                    setChangeDialogOpen(false);
                  }}
                >
                  Cancel
                </Button>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => {
                    setLoading1(true);
                    changeRiderMutation.mutate({ selectedRider, selectedRow });
                  }}
                >
                  Change Rider
                </Button>
              </Stack>
            </DialogActions>
          </Dialog>
        </Box>
      </>
    );
  }

  const handleChangetab = (e, i) => {
    setPage(0);
    setTabvalue(i);
    setRowsPerPage(10);
    if (i === 0) {
      setTabstatus('Pending');
      setCurrentStatus('pending');
      setTotalCount(countData?.uncoveredLength);
    }
    if (i === 1) {
      setTabstatus('Assigned');
      setCurrentStatus('accepted');
      setTotalCount(countData?.assignedLength);
    }
    if (i === 2) {
      setTabstatus('Arrived');
      setCurrentStatus('arrived');
      setTotalCount(countData?.arrivedLength);
    }
    if (i === 3) {
      setTabstatus('Picked');
      setCurrentStatus('picked');
      setTotalCount(countData?.pickedLength);
    }
    if (i === 4) {
      setTabstatus('Active');
      setCurrentStatus('active');
      setTotalCount(countData?.activeLength);
    }
    if (i === 5) {
      setTabstatus('Delivered');
      setCurrentStatus('delivered');
      setTotalCount(countData?.coveredLength);
    }

    if (i === 6) {
      setTabstatus('Cancelled');
      setCurrentStatus('cancelled');
      setTotalCount(countData?.cancelLength);
    }
    console.log(i);
    setSearchword('');
  };

  const okclicked = () => {
    setOpen(false);
  };



  /* ============================================= || fetchDeliveries | ============================================= */

  const {
    data: rows = [], // Default to empty array if no data
    isLoading: fetchDeliveriesIsLoading,
    isError: fetchDeliveriesIsError,
    error: fetchDeliveriesError,
    refetch: fetchDeliveriesRefetch
  } = useQuery({
    queryKey: ['fetchdeliveries',   currentStatus, startdate, enddate, page, rowsPerPage, searchword],
    queryFn: () => fetchDeliveries( currentStatus, startdate, enddate, page, rowsPerPage, searchword)
  });

  /* ============================================= || fetchPercentageAPI | ============================================= */

  const {
    data: percentageData,
    isLoading: fetchPercentageIsLoading,
    isError: fetchPercentageIsError,
    error: fetchPercentageError,
  } = useQuery({
    queryKey: ['fetchpercentageaPI'],
    queryFn: fetchPercentageAPI
  });
  useEffect(() => {
    if (percentageData) {
      console.log('percentageData', percentageData);
    }
  }, [percentageData]);

  /* ============================================= || fetchcount | ============================================= */
  const {
    data: countData = {}, // Default to empty object
    isLoading: fetchCountIsLoading,
    isError: fetchCountIsError,
    error: fetchCountError,
    refetch: fetchCountRefetch
  } = useQuery({
    queryKey: ['fetchCountData', startdate, enddate, tabstatus],
    queryFn: () => fetchCountAPI(startdate, enddate)
  });
  useEffect(() => {
    if (tabvalue === 0 && countData) {
      setTotalCount(countData.uncoveredLength);
    }
  }, [countData]);

  // ==============================|| fetchRidersList ||============================== //
  const {
    data: ridersList = [],
    isLoading: ridersListLoading,
    isError: ridersListIsError,
  } = useQuery({
    queryKey: ['ridersList', 3], // 3=> role id for riders
    queryFn: ({ queryKey }) => getAllUsers(queryKey)
  });

  /* ============================================= || updatedelivery | ============================================= */

  const updateDeliveryMutation = useMutation({
    mutationFn: (orderData) => updateDeliveryAPI(orderData),
    onSuccess: (res) => {
      console.log(res);
      if (res.data.status) {
        opentoast('Updated Successfully', 'success');
        setDeliveryamount('');
        setNotes('');
        setDialogopen(false);
        fetchDeliveriesRefetch();
        fetchCountRefetch();
      }
    },
    onError: (err) => {
      console.log(err);
      opentoast(err.message, 'success');
    }
  });

  return (
    <>
      {(fetchCountIsLoading || fetchPercentageIsLoading || fetchDeliveriesIsLoading ) && (
        <>
          <Loader /> <CircularLoader />
        </>
      )}

      {/* ============================================= || titlecard | =============================================  */}
      <Titlecard title="Deliveries"></Titlecard>
      {/* ============================================= || hoverCard | =============================================  */}
      <Grid container spacing={2} sx={{}}>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Pending orders"
            secondary={
              percentageData?.uncoveredOrders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : percentageData?.uncoveredOrders
            }
            percentage={percentageData?.percentage1}
            color={theme.palette.warning.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Accepted orders"
            secondary={
              percentageData?.assignedOrders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : percentageData?.assignedOrders
            }
            percentage={percentageData?.percentage2.toString()}
            color={theme.palette.info.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Picked orders"
            secondary={
              percentageData?.pickedOrders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : percentageData?.pickedOrders
            }
            percentage={percentageData?.percentage3.toString()}
            color={theme.palette.primary.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3} sx={{ cursor: 'pointer' }}>
          <HoverSocialCard
            primary="Delivered orders"
            secondary={
              percentageData?.coveredOrders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : percentageData?.coveredOrders
            }
            percentage={percentageData?.percentage4.toString()}
            color={theme.palette.success.main}
          />
        </Grid>
      </Grid>
      {/* ============================================= || orderFilter | =============================================  */}
      <Stack
        direction="row"
        flexWrap="wrap" // ✅ allow wrapping
        alignItems="center" // optional, for vertical alignment  justifyContent={'space-between'}
        justifyContent={'space-between'}
        marginY={2}
      >
        {startdate && enddate && (
          <Stack
            direction="row"
            flexWrap="wrap" // ✅ allow wrapping
            gap={1.5} // ✅ space between items when wrapped
            alignItems="center" // optional, for vertical alignment
          >
            <Chip
              avatar={
                <Avatar sx={{ backgroundColor: 'transparent' }}>
                  <MdOutlineDeliveryDining fontSize="30px" style={{ color: 'red' }} />
                </Avatar>
              }
              label={`Deliveries-${datestatus}`}
              color="error"
              variant="combined"
            />

            <Chip
              avatar={
                <Avatar sx={{ backgroundColor: 'transparent' }}>
                  <MdOutlineDateRange fontSize="30px" style={{ color: '#fbc02d' }} />
                </Avatar>
              }
              label={
                <Typography noWrap color="secondary">
                  {dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
                </Typography>
              }
              variant="combined"
              color="warning"
              sx={{ maxWidth: '100%' }} // to avoid overflow
            />
          </Stack>
        )}
        {(!startdate || !enddate) && (
          <Stack direction="row" spacing={2}>
            <Chip label="Orders-All" color="primary" variant="light" size="small" />
          </Stack>
        )}

        <Tooltip title="Order Filter">
          <IconButton
            color="secondary"
            variant="light"
            sx={{ color: 'text.primary', bgcolor: 'grey.200', display: {} }}
            aria-haspopup="true"
            onClick={() => setOpen(true)}
          >
            <FilterList />
          </IconButton>
        </Tooltip>
      </Stack>

      <Box sx={{ overflow: 'auto', border: 1, borderColor: 'grey.200', borderRadius: 2, backgroundColor: '#fff', minHeight: 350 }}>
        <Stack
          alignItems="center"
          justifyContent="space-between"
          direction="row"
          sx={{
            p: 2,
            width: '100%'
          }}
        >
          {/* =============================== || Tabs || =============================== */}
          <Tabs value={tabvalue} onChange={handleChangetab} variant="scrollable" scrollButtons="auto" sx={{ ml: -2 }}>
            <Tab
              label="Assigned"
              icon={<Chip label={countData?.uncoveredLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />
            <Tab
              label="Accepted"
              icon={<Chip label={countData?.assignedLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />
            <Tab
              label="Arrived"
              icon={<Chip label={countData?.arrivedLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />

            <Tab
              label="Picked"
              icon={<Chip label={countData?.pickedLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />
            <Tab
              label="Active"
              icon={<Chip label={countData?.activeLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />

            <Tab
              label="Delivered"
              icon={<Chip label={countData?.coveredLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />

            <Tab
              label="Cancelled"
              icon={<Chip label={countData?.cancelLength || 0} color="primary" variant="light" size="small" />}
              iconPosition="end"
            />
          </Tabs>
          {/* ============================================= || searchOutlined | =============================================  */}
          <FormControl sx={{ minWidth: 250, display: {} }}>
            <OutlinedInput
              inputRef={textFieldRef}
              id="header-search"
              aria-describedby="header-search-text"
              inputProps={{
                'aria-label': 'weight'
              }}
              placeholder="Search (ctrl+k)"
              value={searchword}
              onChange={(e) => {
                setSearchword(e.target.value);
              }}
              autoComplete="off"
              startAdornment={
                <InputAdornment position="start" sx={{ mr: -0.5 }}>
                  <SearchOutlined />
                </InputAdornment>
              }
              endAdornment={
                <IconButton
                  sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                  onClick={() => {
                    setSearchword('');
                    fetchDeliveriesRefetch();
                  }}
                >
                  <ClearIcon style={{ fontSize: 'medium', color: '#65387A' }} />
                </IconButton>
              }
            />
          </FormControl>
        </Stack>
        {/* ============================================= || EnhancedTable | =============================================  */}
        <Box sx={{ width: '100%', display: 'table', tableLayout: 'fixed' }}>
          <EnhancedTable />
        </Box>
      </Box>
      {/* =============================== || Date filter Dialog || =============================== */}
      <Dialog open={open}>
        <DialogTitle align="left">
          <Typography variant="h4">Select Filter Options</Typography>
        </DialogTitle>
        <DialogContent sx={{ width: '100%' }} className="datedialog">
          <DateRangePicker
            open={open}
            toggle={() => setOpen(!open)}
            id="daterange1"
            onChange={(range) => {
              if (range.label === 'All') {
                setStartdate('');
                setEnddate('');

                setOpen(false);
              } else {
                setStartdate(dayjs(range.startDate).format('YYYY-MM-DD'));
                setEnddate(dayjs(range.endDate).format('YYYY-MM-DD'));
                if (range.label) {
                  setDatestatus(range.label);
                } else {
                  setDatestatus('');
                }
              }
              console.log(range);
            }}
            definedRanges={[
              {
                label: 'Today',
                startDate: new Date(),
                endDate: new Date()
              },
              {
                label: 'Yesterday',
                startDate: addDays(new Date(), -1),
                endDate: addDays(new Date(), -1)
              },
              {
                label: 'Tomorrow',
                startDate: addDays(new Date(), +1),
                endDate: addDays(new Date(), +1)
              },
              {
                label: 'This Week',
                startDate: startOfWeek(new Date()),
                endDate: endOfWeek(new Date())
              },
              {
                label: 'Last Week',
                startDate: startOfWeek(addWeeks(new Date(), -1)),
                endDate: endOfWeek(addWeeks(new Date(), -1))
              },
              {
                label: 'Last 7 Days',
                startDate: addWeeks(new Date(), -1),
                endDate: new Date()
              },
              {
                label: 'This Month',
                startDate: startOfMonth(new Date()),
                endDate: endOfMonth(new Date())
              },
              {
                label: 'Last Month',
                startDate: startOfMonth(addMonths(new Date(), -1)),
                endDate: endOfMonth(addMonths(new Date(), -1))
              }
              // {
              //   label: 'All',
              //   startDate: new Date(),
              //   endDate: addDays(new Date(), -1),
              // },
            ]}
          />
        </DialogContent>
        <Stack direction="row" justifyContent="flex-end" sx={{ width: '100%', p: 2 }}>
          <Button variant="contained" size="small" onClick={okclicked}>
            ok
          </Button>
        </Stack>
      </Dialog>
      {/* =============================== || Update Delivery Dialog || =============================== */}
      <Dialog fullWidth={true} open={dialogopen} onClose={dialogclose} scroll={'paper'} maxWidth="sm" TransitionComponent={PopupTransition}>
        <DialogTitle
          sx={{
            bgcolor: '#662582',
            color: '#fff'
          }}
        >
          Update Delivery Status
        </DialogTitle>
        <DialogContent dividers={true}>
          <MainCard sx={{ height: '100%' }}>
            <Grid container spacing={2.5}>
              <Grid item xs={12} sm={6}>
                <FormLabel>Kms</FormLabel>
                <TextField
                  fullWidth
                  value={kms}
                  type="number"
                  onChange={(e) => {
                    setKms(e.target.value);
                    console.log(e);
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Actual Kms</FormLabel>
                <TextField value={actualkms} type="number" onChange={(e) => setActualkms(e.target.value)} fullWidth />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Delivery lat</FormLabel>
                <TextField
                  fullWidth
                  type="number"
                  value={deliverylat}
                  onChange={(e) => {
                    setDeliverylat(e.target.value);
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <FormLabel>Delivery Long</FormLabel>
                <TextField
                  value={deliverylong}
                  type="number"
                  onChange={(e) => {
                    setDeliverylong(e.target.value);
                  }}
                  fullWidth
                />
              </Grid>

              <Grid item xs={12}>
                <FormLabel>Amount</FormLabel>

                <TextField fullWidth type="number" value={deliveryamount} onChange={(e) => setDeliveryamount(e.target.value)} />
              </Grid>
              <Grid item xs={12}>
                <FormLabel>Notes</FormLabel>

                <TextField value={notes} fullWidth onChange={(e) => setNotes(e.target.value)} />
              </Grid>
            </Grid>
          </MainCard>
        </DialogContent>
        <DialogActions>
          <Grid container>
            <Grid item xs={12}>
              <Stack direction={'row'} justifyContent={'flex-end'} spacing={2} sx={{ p: 2 }}>
                <Button
                  variant="contained"
                  onClick={() => {
                    dialogclose();
                  }}
                  color="error"
                >
                  Close
                </Button>{' '}
                {/* <Button
                    variant="contained"
                    onClick={() => {
                      updatedelivery();
                    }}
                  >
                    Update
                  </Button> */}
                <Button
                  variant="contained"
                  onClick={() => {
                    if (!kms) {
                      opentoast('Fill Kms', 'warning');
                    } else if (!actualkms) {
                      opentoast('Fill Actual Kms', 'warning');
                    } else if (!deliverylat) {
                      opentoast('Fill Delivery Latitude', 'warning');
                    } else if (!deliverylong) {
                      opentoast('Fill Delivery Longitude', 'warning');
                    } else if (!deliveryamount) {
                      opentoast('Fill Delivery Amount', 'warning');
                    } else {
                      updateDeliveryMutation.mutate({
                        deliveryid: currentorder.deliveryid,
                        orderheaderid: currentorder.orderheaderid,
                        orderstatus: 'delivered',
                        deliverytime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                        deliverylat,
                        deliverylong,
                        kms,
                        actualkms,
                        deliveryamt: parseFloat(deliveryamount),
                        notes
                      });
                    }
                  }}
                >
                  Update
                </Button>
              </Stack>
            </Grid>
          </Grid>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default Deliveries;
