import * as React from 'react';
import { enqueueSnackbar } from 'notistack';
import { DeleteFilled } from '@ant-design/icons';
import { useState, useEffect, Fragment, useRef } from 'react';
import { Empty } from 'antd';
import axios from 'axios';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import { useDebounce } from 'use-debounce';
import { HiHandThumbDown, HiHandThumbUp } from 'react-icons/hi2';
import LoadingIcons from 'react-loading-icons';
import { DashboardOutlined } from '@ant-design/icons';
import { PlusCircleOutlined } from '@ant-design/icons';
import { useQueryClient } from '@tanstack/react-query';
import { PopupTransition } from 'components/@extended/Transitions';
import { MdOutlineDateRange } from 'react-icons/md';
import { AiOutlineDashboard } from 'react-icons/ai';

import {
  Avatar,
  Box,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  Chip,
  Typography,
  Table,
  TableCell,
  TableBody,
  TableHead,
  Collapse,
  Dialog,
  TableRow,
  DialogContent,
  DialogTitle,
  Tooltip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  useMediaQuery,
  Checkbox,
  DialogActions,
  Autocomplete,
  TextField
} from '@mui/material';

import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import ClearIcon from '@mui/icons-material/Clear';
import { addDays, addMonths, addWeeks, endOfMonth, endOfWeek, startOfMonth, startOfWeek } from 'date-fns';
import { DateRangePicker } from 'mui-daterange-picker';
import { useNavigate } from 'react-router';
import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import Loader from 'components/Loader';
import { FilterList, KeyboardArrowDownOutlined, KeyboardArrowUpOutlined } from '@mui/icons-material';

import {
  cancelOrder,
  createDeliveries,
  fetchPaymentType,
  fetchRidersList,
  getAllUsers,
  getorderdetails,
  getOrdersSummary,
  notifyRider,
  tenantgetorders
} from '../api/api';
import { useMutation, useQuery } from '@tanstack/react-query';
import Titlecard from 'components/nearle_components/Titlecard';
import CircularLoader from 'components/nearle_components/CircularLoader';

import dayjs from 'dayjs';
import MainCard from 'components/MainCard';
import OpenToast from 'components/nearle_components/OpenToast';
import FloatingCart from 'components/cards/e-commerce/FloatingCart';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

const Orders = () => {
  const theme = useTheme();
  const queryClient = useQueryClient();
  const [orderHeaderid, setOrderHeaderId] = useState(null);
  const [productCollapse, setProductCollapse] = useState(null);
  const isBelowCustom500 = useMediaQuery(theme.breakpoints.down('custom500'));
  const isBelowCustom400 = useMediaQuery(theme.breakpoints.down('custom400'));
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [tabvalue, setTabvalue] = useState(0);
  let navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [currentStatus, setCurrentStatus] = useState('created');
  const [deliverylist, setDeliverylist] = useState([]);
  const [deleteDialog, setdeleteDialog] = useState(false);
  const [assignDialog, setAssignDialog] = useState(false);
  const [assignLoading, setAssignLoading] = useState(false);
  const [payment, setPayment] = useState({});
  const [rider, setRider] = useState({});
  const [searchword, setSearchword] = useState('');
  const [debouncedSearchword] = useDebounce(searchword, 500);

  useEffect(() => {
    console.log('deliverylist', deliverylist);
  }, [deliverylist]);

  const textFieldRef = useRef(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);
    };
  }, []);

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

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

  const { data: orderdetails } = useQuery({
    queryKey: ['orderdetails', orderHeaderid],
    queryFn: () => getorderdetails(orderHeaderid),
    enabled: !!orderHeaderid
  });

  const {
    data: rows,
    isLoading: tenantgetordersIsloading,
    isFetching: tenantgetordersIsFetching,
    refetch: tenantgetordersRefetch
  } = useQuery({
    queryKey: ['tenant-orders', currentStatus, startdate, enddate, page, rowsPerPage, debouncedSearchword],
    queryFn: tenantgetorders,
    refetchOnWindowFocus: true
  });

  const {
    data: ordersPercent,
    isLoading: orderpercentIsloading,
    isFetching: orderpercentIsFetching,
    refetch: orderpercentRefetch
  } = useQuery({
    queryKey: ['orderpercent'],
    queryFn: getOrdersSummary,
    refetchOnWindowFocus: true,
    staleTime: 0
  });

  const {
    data: ordersCount,
    isLoading: ordercountIsloading,
    isFetching: ordercountIsFetching,
    refetch: ordercountRefetch
  } = useQuery({
    queryKey: ['ordercount', startdate, enddate, tabvalue],
    queryFn: getOrdersSummary,
    refetchOnWindowFocus: true
  });

  const {
    data: paymentModes = [],
    isLoading: paymentModesLoading,
    isError: paymentModesError,
    error: paymentModesErrorMessage,
    refetch: refetchPaymentModes
  } = useQuery({
    queryKey: ['paymentmodes'],
    queryFn: fetchPaymentType
  });

  const {
    data: ridersList = [],
    isLoading: ridersListLoading,
    isError: ridersListError,
    error: ridersListErrorMessage,
    refetch: refetchRidersList
  } = useQuery({
    queryKey: ['ridersList', 3], // 3=> role id for riders
    queryFn: ({ queryKey }) => getAllUsers(queryKey)
  });

  const notifyRiderMutation = useMutation({
    mutationFn: notifyRider,
    onSuccess: (data) => {
      OpenToast('Notification sent successfully', 'success', 2000);
    },
    onError: (error) => {
      OpenToast(`Notification failed: ${error.message}`, 'error', 2000);
    }
  });

  const createDeliveryMutation = useMutation({
    mutationFn: createDeliveries, // Using the separate function
    onSuccess: (data, variables) => {
      OpenToast('Delivery Created Successfully', 'success', 2000);
      setDeliverylist([]);
      setAssignLoading(false);
      tenantgetordersRefetch();
      orderpercentRefetch();
      ordercountRefetch();
      notifyRiderMutation.mutate(variables.riderToken); // Call notifyRider after success
    },
    onError: (error) => {
      OpenToast(error.message, 'success', 2000);
      setAssignLoading(false);
    },
    onSettled: () => {
      setAssignLoading(false);
      setAssignDialog(false);
    }
  });

  const { mutate: cancelorder } = useMutation({
    mutationFn: cancelOrder,
    onSuccess: (data) => {
      if (data.status) {
        OpenToast(data.message, 'success', 1500);
        setdeleteDialog(false);
        setOrderHeaderId(null);
        tenantgetordersRefetch();
        orderpercentRefetch();
        ordercountRefetch();
      }
    },
    onError: (error) => {
      console.error('Cancel order error:', error);
      OpenToast(error.message, 'error', 1500);
    }
  });

  const handleCreateDelivery = async () => {
    setAssignLoading(true);
    if (!rider.userid) {
      OpenToast('Choose Rider', 'error', 2000);
      setAssignLoading(false);
      return;
    }
    if (!payment?.typename) {
      OpenToast('Choose Payment Type', 'error', 2000);
      setAssignLoading(false);
      return;
    }
    const deliveryData = deliverylist.map((val) => ({
      deliveryid: 0,
      applocationid: val.applocationid,
      tenantid: val.tenantid,
      locationid: val.locationid,
      configid: val.configid,
      moduleid: val.moduleid,
      userid: rider.userid,
      orderheaderid: val.orderheaderid,
      categoryid: val.categoryid,
      subcategoryid: val.subcategoryid,
      orderid: val.orderid,
      deliverydate: dayjs(val.deliverydate).utc().format('YYYY-MM-DD HH:mm:ss'),
      assigntime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      orderstatus: 'pending',
      orderamount: val.deliverycharge,
      itemcount: val.itemcount,
      customerid: val.customerid,
      deliveryaddress: val.deliveryaddress,
      deliverylocationid: val.deliverylocationid,
      droplat: val.deliverylat,
      droplon: val.deliverylong,
      pickupaddress: val.pickupaddress,
      pickuplat: val.pickuplat,
      pickuplon: val.pickuplong,
      ordernotes: val.ordernotes,
      paymenttype: payment?.apptypeid || '',
      kms: val.kms,
      deliverycharges: val.deliverycharge,
      partnerid: val.partnerid,
      pickupcustomer: val.pickupcustomer,
      pickupcontactno: val.pickupcontactno,
      deliverycustomerid: val.deliverycustomerid,
      deliverycontactno: val.deliverycontactno,
      pickuplocationid: val.pickuplocationid,
      pickuplocation: val.pickupsuburb,
      deliverylocation: val.deliverysuburb,
      deliverycustomer: val.deliverycustomer,
      deliverytype: val.deliverytype
    }));
    createDeliveryMutation.mutate({ deliveries: deliveryData, riderToken: rider.userfcmtoken });
  };

  useEffect(() => {
    const handleFocus = () => {
      queryClient.invalidateQueries({ queryKey: ['tenant-orders'] });
      queryClient.invalidateQueries({ queryKey: ['orderpercent'] });
      queryClient.invalidateQueries({ queryKey: ['ordercount'] });
    };
    window.addEventListener('focus', handleFocus);
    return () => window.removeEventListener('focus', handleFocus);
  }, []);

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

  const headCells = [
    {
      id: 'sno',
      disablePadding: false,
      numeric: false,
      label: 'S NO'
    },
    {
      id: 'orderid',
      disablePadding: false,
      numeric: false,
      label: 'ORDER ID'
    },
    {
      id: 'eventname',
      disablePadding: false,
      numeric: false,
      label: 'Pickup'
    },
    {
      id: 'eventname4',
      disablePadding: false,
      numeric: false,
      label: 'Delivery'
    },

    {
      id: 'itemcount',
      disablePadding: false,
      numeric: false,
      label: 'NOTES'
    },
    {
      id: 'orderstatus',
      disablePadding: false,
      numeric: false,
      label: 'STATUS'
    }
  ];

  return (
    <>
      {(tenantgetordersIsloading || orderpercentIsloading || ordercountIsloading) && <Loader />}
      {(tenantgetordersIsloading || orderpercentIsloading || ordercountIsloading) && <CircularLoader />}
      {/* {(tenantgetordersIsFetching || orderpercentIsFetching || ordercountIsFetching) && <CircularLoader />} */}
      <Titlecard title={'Orders'}>
        {isBelowCustom400 ? (
          <Tooltip title={'Create Order'}>
            <IconButton
              disabled
              title="kannan"
              sx={{
                backgroundColor: 'primary.main',
                color: 'white',
                '&:hover': {
                  backgroundColor: 'primary.main'
                }
              }}
              onClick={() => {
                navigate('/orders/create');
              }}
            >
              <PlusCircleOutlined />
            </IconButton>
          </Tooltip>
        ) : (
          <Chip
            disabled
            icon={<PlusCircleOutlined style={{ fontSize: 18 }} />}
            label={'Create Order'}
            variant="filled"
            size="medium"
            color="primary"
            onClick={() => {
              navigate('/orders/create');
            }}
            sx={{
              px: isBelowCustom500 ? 1.5 : 2,
              py: 1,
              height: 38,
              fontWeight: 500,
              fontSize: '0.875rem',
              borderRadius: '8px',
              cursor: 'pointer'
            }}
          />
        )}
      </Titlecard>{' '}
      {/* // ==============================|| HoverSocialCard ||============================== // */}
      <Grid container rowSpacing={4.5} columnSpacing={2.75} sx={{}}>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Created Orders"
            secondary={ordersPercent?.created || 0}
            color={theme.palette.primary.main}
            iconPrimary={DashboardOutlined}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Pending orders"
            secondary={ordersPercent?.pending || 0}
            color={theme.palette.warning.main}
            iconPrimary={LoadingIcons.ThreeDots}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Delivered orders"
            secondary={ordersPercent?.delivered || 0}
            color={theme.palette.success.main}
            iconPrimary={HiHandThumbUp}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Cancelled Orders"
            secondary={ordersPercent?.cancelled || 0}
            color={theme.palette.error.main}
            iconPrimary={HiHandThumbDown}
          />
        </Grid>
      </Grid>
      {/* // ==============================|| Date Filter row ||============================== // */}
      <Stack
        direction={'row'}
        justifyContent={'space-between'}
        alignItems={'center'}
        sx={{ my: 1.5, backgroundColor: 'white', borderColor: 'grey.200', p: 1 }}
      >
        {startdate && enddate && (
          <Stack direction={{ xs: 'column', custom400: 'row' }} spacing={2}>
            <Chip
              avatar={
                <Avatar sx={{ backgroundColor: 'transparent' }}>
                  <AiOutlineDashboard fontSize="30px" style={{ color: 'red' }} />
                </Avatar>
              }
              label={`Orders-${datestatus ? 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"
            />
          </Stack>
        )}
        {(!startdate || !enddate) && (
          <>
            <Stack direction="row" spacing={2}>
              <Chip label="Orders-All" color="primary" variant="light" />
            </Stack>
          </>
        )}

        <Tooltip title="Order Filter">
          <IconButton
            color="secondary"
            variant="light"
            sx={{ color: 'text.primary', bgcolor: 'grey.200', display: { xs: 'flex', md: 'flex' } }}
            aria-haspopup="true"
            onClick={() => setOpen(true)}
          >
            <FilterList />
          </IconButton>
        </Tooltip>
      </Stack>
      {/* // ==============================|| Table ||============================== // */}
      <MainCard
        headerstyle={{ px: 0, py: 3, overflowX: 'auto' }}
        contentSX={{ p: 0 }}
        title={
          <Stack
            direction={{ xs: 'column', custom700: 'row' }}
            alignItems={{ xs: 'stretch', custom700: 'center' }}
            spacing={2}
            sx={{ mx: 2 }}
          >
            {/* Tabs box */}
            <Box
              sx={{
                flexGrow: 1,
                overflowX: 'auto',
                whiteSpace: 'nowrap',
                display: 'flex'
              }}
            >
              <Tabs
                value={tabvalue}
                onChange={handleChangetab}
                variant="scrollable"
                scrollButtons="auto"
                allowScrollButtonsMobile
                sx={{
                  minWidth: 'fit-content'
                }}
              >
                <Tab
                  label="Created"
                  icon={
                    <Chip
                      label={ordersCount?.created || 0}
                      color="primary"
                      variant="light"
                      sx={{ minWidth: 40, justifyContent: 'center' }}
                    />
                  }
                  iconPosition="end"
                />
                <Tab
                  label="Pending"
                  icon={
                    <Chip
                      label={ordersCount?.pending || 0}
                      color="primary"
                      variant="light"
                      sx={{ minWidth: 40, justifyContent: 'center' }}
                    />
                  }
                  iconPosition="end"
                />
                <Tab
                  label="Delivered"
                  icon={
                    <Chip
                      label={ordersCount?.delivered || 0}
                      color="primary"
                      variant="light"
                      sx={{ minWidth: 40, justifyContent: 'center' }}
                    />
                  }
                  iconPosition="end"
                />
                <Tab
                  label="Cancelled"
                  icon={
                    <Chip
                      label={ordersCount?.cancelled || 0}
                      color="primary"
                      variant="light"
                      sx={{ minWidth: 40, justifyContent: 'center' }}
                    />
                  }
                  iconPosition="end"
                />
              </Tabs>
            </Box>

            {/* Search input */}
            <FormControl
              sx={{
                flexShrink: 1,
                width: { xs: '100%', custom700: 'auto' }
              }}
            >
              <OutlinedInput
                inputRef={textFieldRef}
                id="header-search"
                aria-describedby="header-search-text"
                placeholder="Search (ctrl+k)"
                autoComplete="off"
                value={searchword}
                onChange={(e) => setSearchword(e.target.value)}
                startAdornment={
                  <InputAdornment position="start" sx={{ mr: -0.5 }}>
                    <SearchOutlined sx={{ color: theme.palette.primary.main }} />
                  </InputAdornment>
                }
                endAdornment={
                  <Tooltip title="Clear">
                    <IconButton
                      sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                      onClick={() => {
                        setSearchword('');
                      }}
                    >
                      <ClearIcon sx={{ color: theme.palette.primary.main }} />
                    </IconButton>
                  </Tooltip>
                }
              />
            </FormControl>
          </Stack>
        }
      >
        {deliverylist.length > 0 && <FloatingCart count={deliverylist.length} onClick={() => setAssignDialog(true)} />}
        <TableContainer sx={{ width: '100%', borderBottom: 1, borderColor: 'divider' }}>
          <Table sx={{ tableLayout: 'auto', width: '100%' }} aria-label="collapsible table" size={'medium'}>
            <TableHead>
              <TableRow>
                {currentStatus == 'created' && (
                  <TableCell padding="checkbox">
                    <Checkbox
                      sx={{ cursor: 'pointer' }}
                      checked={rows?.length > 0 && deliverylist.length === rows.length}
                      indeterminate={deliverylist.length > 0 && deliverylist.length < rows.length}
                      onChange={(e) => {
                        if (e.target.checked) {
                          const newList = rows.map((row, index) => ({ ...row, sno: index + 1 }));
                          setDeliverylist(newList);
                        } else {
                          setDeliverylist([]);
                        }
                      }}
                    />
                  </TableCell>
                )}
                {headCells.map((headCell) => (
                  <TableCell
                    key={headCell.id}
                    align={headCell.numeric ? 'right' : 'left'}
                    padding={headCell.disablePadding ? 'none' : 'normal'}
                  >
                    {headCell.label}
                  </TableCell>
                ))}
                {currentStatus == 'created' && <TableCell align="right">Actions</TableCell>}
              </TableRow>
            </TableHead>
            <TableBody>
              {rows?.length == 0 && (
                <>
                  <TableCell colSpan={8}>
                    <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                      <Empty description={'No orders '} />
                    </Stack>
                  </TableCell>
                </>
              )}

              {rows?.map((row, index) => {
                return (
                  <>
                    <TableRow
                      key={index}
                      sx={{
                        cursor: 'pointer',
                        backgroundColor: deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid) ? '#e1bee7' : '',
                        '&:hover': {
                          backgroundColor: deliverylist.find((res1) => res1.orderheaderid == row.orderheaderid) ? '#e1bee7 !important' : ''
                        }
                      }}
                    >
                      {currentStatus == 'created' && (
                        <TableCell padding="checkbox">
                          <Checkbox
                            sx={{
                              backgroundColor: deliverylist.some((res1) => res1.orderheaderid === row.orderheaderid) ? '#e1bee7' : '',
                              '&:hover': {
                                backgroundColor: deliverylist.some((res1) => res1.orderheaderid === row.orderheaderid)
                                  ? '#e1bee7 !important'
                                  : ''
                              }
                            }}
                            checked={deliverylist.some((res1) => res1.orderheaderid === row.orderheaderid)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                const updated = [...deliverylist, { ...row, sno: deliverylist.length + 1 }];
                                setDeliverylist(updated);
                              } else {
                                const filtered = deliverylist.filter((item) => item.orderheaderid !== row.orderheaderid);
                                const reIndexed = filtered.map((val, i) => ({ ...val, sno: i + 1 }));
                                setDeliverylist(reIndexed);
                              }
                            }}
                          />
                        </TableCell>
                      )}
                      <TableCell padding="none">
                        <Typography> {page * rowsPerPage + index + 1}</Typography>
                      </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>
                        <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                          {dayjs(row.deliverydate).utc().format('hh:mm A')}
                        </Typography>
                      </TableCell>

                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1} display={'flex'} alignItems="center">
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          ></Avatar>
                          <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.pickupaddress.slice(0, 20)} */}
                                {row.pickupsuburb || row.pickupaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">
                        <Stack direction={'row'} spacing={1} display={'flex'} alignItems="center">
                          <Avatar
                            alt=""
                            size="sm"
                            sx={{
                              width: '25px',
                              height: '25px'
                            }}
                          ></Avatar>
                          <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.pickupaddress.slice(0, 20)} */}
                                {row.deliverysuburb || row.deliveryaddress.slice(0, 20)}
                              </Typography>
                            </Tooltip>
                          </Stack>
                        </Stack>
                      </TableCell>
                      <TableCell align="left">{row.ordernotes}</TableCell>
                      {/* <TableCell align="left"><Chip label={row.itemcount} color="primary" variant="light" size="small" /></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="primary" 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="Picked" color="info" size="small" />}
                          {row.orderstatus === 'closed' && <Chip label="Closed" color="info" size="small" />}
                          {row.orderstatus === 'created' && <Chip label="Created" color="secondary" size="small" />}
                        </Stack>
                      </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);
                                    setOrderHeaderId(null);
                                  } else {
                                    setProductCollapse(row);
                                    setOrderHeaderId(row.orderheaderid);
                                  }
                                }}
                              >
                                {productCollapse?.orderid === row.orderid ? <KeyboardArrowUpOutlined /> : <KeyboardArrowDownOutlined />}
                              </IconButton>
                            </Tooltip>
                          )}
                          {row.orderstatus == 'created' && (
                            <>
                              <Tooltip title="Cancel">
                                <IconButton
                                  disabled={deliverylist.length > 0}
                                  onClick={(e) => {
                                    e.stopPropagation();
                                    setOrderHeaderId(row.orderheaderid);
                                    setdeleteDialog(true);
                                  }}
                                >
                                  <CloseOutlined
                                    style={{
                                      color: deliverylist.length > 0 ? theme.palette.secondary.main : theme.palette.error.main
                                    }}
                                  />
                                </IconButton>
                              </Tooltip>
                            </>
                          )}
                        </Stack>
                      </TableCell>
                    </TableRow>
                    {productCollapse?.orderid === row?.orderid && (
                      <TableRow>
                        <TableCell
                          colSpan={10}
                          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>
                                <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 }}>
                                      Sub Total
                                    </TableCell>
                                    <TableCell align="right" sx={{ fontWeight: 600 }}>
                                      Tax
                                    </TableCell>
                                    <TableCell align="right" sx={{ fontWeight: 600 }}>
                                      Grand Total
                                    </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}
                                            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 || 0).toFixed(2) || 0}</TableCell>
                                      <TableCell align="right">₹ {(product?.taxamount || 0).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={{}}>
                                      Amount Payable :
                                    </TableCell>
                                    <TableCell align="right" sx={{}}>
                                      ₹ {orderdetails?.pricedetails?.orderamount.toFixed(2)}
                                    </TableCell>
                                  </TableRow>
                                </TableBody>
                              </Table>
                            </Box>
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                  </>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>

        {!searchword && (
          <TablePagination
            rowsPerPageOptions={[5, 10, 25, 50, 100]}
            component="div"
            count={
              tabvalue == 0
                ? ordersCount?.created
                : tabvalue == 1
                ? ordersCount?.pending
                : tabvalue == 2
                ? ordersCount?.delivered
                : tabvalue == 3
                ? ordersCount?.cancelled
                : 0
            }
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
        )}
      </MainCard>
      {/* ============================================= || Assign Order (choose rider) | =============================================  */}
      <Dialog maxWidth={false} fullWidth={true} open={assignDialog} scroll={'paper'} TransitionComponent={PopupTransition}>
        <DialogTitle>Assign Orders</DialogTitle>
        <DialogContent dividers={true}>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>#</TableCell>
                  <TableCell>Order ID</TableCell>
                  <TableCell>Pickup </TableCell>
                  <TableCell>Delivery</TableCell>
                  <TableCell>Notes</TableCell>
                  <TableCell>Charges</TableCell>
                  <TableCell>KMS</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {deliverylist.map((val, i) => {
                  console.log('dialog val', val);
                  return (
                    <Fragment key={i}>
                      <TableRow sx={{}}>
                        <TableCell>
                          <Typography> {val.sno}</Typography>
                        </TableCell>
                        <TableCell align="left">
                          <Typography variant="body2" noWrap>
                            {val.orderid}
                          </Typography>
                          <Typography noWrap sx={{ fontSize: '11px' }}>
                            {dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
                          </Typography>
                          <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                            {dayjs(val.orderdate).utc().format('hh:mm A')}
                          </Typography>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{val.pickupcustomer}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {val.pickupcontactno}
                              </Typography>
                              <Tooltip title={val.pickupaddress}>
                                <Typography variant="caption" color="textSecondary">
                                  {val.pickupsuburb || val.pickupaddress.slice(0, 20)}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="caption">{val.deliverycustomer}</Typography>
                              <Typography variant="caption" color="textSecondary">
                                {val.deliverycontactno}
                              </Typography>
                              <Tooltip title={val.deliveryaddress}>
                                <Typography variant="caption" color="textSecondary">
                                  {val.deliverysuburb || val.deliveryaddress.slice(0, 20)}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">{val.ordernotes}</TableCell>
                        <TableCell align="left">₹ {val.deliverycharge.toFixed(2)}</TableCell>
                        <TableCell align="left">{val.kms}</TableCell>
                      </TableRow>
                    </Fragment>
                  );
                })}
              </TableBody>
            </Table>
          </TableContainer>
          <Grid container sx={{ mt: 2 }} spacing={2}>
            <Grid item xs={12} sm={6}>
              <Autocomplete
                id="free-solo-demo"
                options={paymentModes || []}
                renderInput={(params) => <TextField {...params} label="Choose Payment" />}
                onChange={(e, val) => {
                  if (val) {
                    console.log('payment val', val);
                    setPayment(val);
                  }
                }}
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <Autocomplete
                id="free-solo-demo"
                options={ridersList || []}
                getOptionLabel={(option) => `${option.fullname || ''}`}
                renderInput={(params) => <TextField {...params} label="Choose Rider" />}
                onChange={(e, val) => {
                  if (val) {
                    console.log('rider val', val);
                    setRider(val);
                  }
                }}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Stack sx={{ mt: 2, mr: 2 }} direction="row" justifyContent="flex-end" spacing={5}>
            <Button
              sx={{ width: '130px' }}
              color="error"
              variant="contained"
              onClick={() => {
                setAssignDialog(false);
              }}
            >
              Cancel
            </Button>

            <Button
              color="success"
              variant="contained"
              onClick={() => {
                handleCreateDelivery();
              }}
            >
              {assignLoading ? 'Assigning...' : 'Assign Orders'}
            </Button>
          </Stack>
        </DialogActions>
      </Dialog>
      {/* // ==============================|| delete dialog ||============================== // */}
      <Dialog
        open={deleteDialog}
        onClose={() => {
          setdeleteDialog(false);
        }}
        maxWidth="xs"
      >
        <DialogContent sx={{ mt: 2, my: 1 }}>
          <Stack alignItems="center" spacing={3.5}>
            <Avatar color="error" sx={{ width: 72, height: 72, fontSize: '1.75rem' }}>
              <DeleteFilled />
            </Avatar>

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

            <Stack direction="row" spacing={2} sx={{ width: 1 }}>
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  cancelorder(orderHeaderid);
                }}
                autoFocus
              >
                Yes, Cancel
              </Button>
              <Button
                fullWidth
                onClick={() => {
                  setdeleteDialog(false);
                }}
                color="secondary"
                variant="outlined"
              >
                No
              </Button>
            </Stack>
          </Stack>
        </DialogContent>
      </Dialog>
      {/* // ==============================|| date filter ||============================== // */}
      <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" onClick={() => setOpen(false)}>
            ok
          </Button>
        </Stack>
      </Dialog>
    </>
  );
};

export default Orders;
