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 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 MyLocationIcon from '@mui/icons-material/MyLocation';
import { CalendarMonth, CancelOutlined, CheckCircleOutline } from '@mui/icons-material';

import {
  Avatar,
  Button,
  Grid,
  Tabs,
  Tab,
  IconButton,
  Stack,
  Chip,
  Typography,
  Table,
  TableCell,
  TableBody,
  TableHead,
  Dialog,
  TableRow,
  DialogContent,
  Tooltip,
  FormControl,
  OutlinedInput,
  InputAdornment,
  Skeleton,
  Autocomplete,
  TextField,
  CircularProgress
} from '@mui/material';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import ClearIcon from '@mui/icons-material/Clear';
import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import Loader from 'components/Loader';
// import { FilterList } from '@mui/icons-material';
import { useHotkeyFocus } from 'components/nearle_components/useHotkeyFocus';
import DateFilterDialog from 'components/nearle_components/DateFilterDialog';
import MainCard from 'components/MainCard';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import LocalShippingOutlinedIcon from '@mui/icons-material/LocalShippingOutlined';
import CircularLoader from 'components/nearle_components/CircularLoader';
import { useInfiniteQuery } from '@tanstack/react-query';

const Orders = () => {
  const tid = localStorage.getItem('tenantid');
  const tenId = localStorage.getItem('tenantid');
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [percentage1, setPercentage1] = useState('0');
  const [percentage2, setPercentage2] = useState('0');
  const [percentage3, setPercentage3] = useState('0');
  const [percentage4, setPercentage4] = useState('0');
  const [tenantLocations, setTenantlocations] = useState([]);
  const [coveredorders, setCoveredorders] = useState('');
  const [uncoveredorders, setUncoveredorders] = useState('');
  const [cancelled, setCancelled] = useState('');
  const [created, setCreated] = useState('');
  const [loading, setLoading] = useState(false);
  const theme = useTheme();
  const [tabvalue, setTabvalue] = useState(0);
  const [tabstatus, setTabstatus] = useState('Created');
  const [currentStatus, setCurrentStatus] = useState('created');
  const [createdLenght, setCreatedLenght] = useState();
  const [pendingLenght, setPendingLenght] = useState();
  const [deliveredlenght, setDeliveredlenght] = useState();
  const [cancelledLenght, setCancelledLenght] = useState();
  const [cancelOpen, setCancelOpen] = useState(false);
  const [orderheaderid, setOrderheaderid] = useState('');
  const [locationId, setLocationId] = useState(0);
  const [locoName, setLocoName] = useState('Select Location');
  const [dateOpen, setDateOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));

  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const getValueColor = (value) => {
    return value !== 0 ? 'red' : 'inherit';
  };

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearch(searchword);
    }, 400);

    return () => clearTimeout(handler);
  }, [searchword]);

  const statusMap = [
    {
      label: 'Created',
      value: 'created',
      count: createdLenght,
      icon: <AccessTimeIcon color="primary" fontSize="small" />
    },
    {
      label: 'Pending',
      value: 'pending',
      count: pendingLenght,
      icon: <LocalShippingOutlinedIcon color="primary" fontSize="small" />
    },
    {
      label: 'Delivered',
      value: 'delivered',
      count: deliveredlenght,
      icon: <CheckCircleOutline color="primary" fontSize="small" />
    },
    {
      label: 'Cancelled',
      value: 'cancelled',
      count: cancelledLenght,
      icon: <CancelOutlined color="primary" fontSize="small" />
    }
  ];

  const handleChangetab = (e, i) => {
    setSearchword('');
    setRowsPerPage(10);
    setTabvalue(i);
    setTabstatus(statusMap[i].label);
    setCurrentStatus(statusMap[i].value);
    setPage(0);
  };

  const textFieldRef = useRef(null);
  useHotkeyFocus(textFieldRef, 'k');

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

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

  const cancelorder = async () => {
    setLoading(true);
    await axios
      .put(`${process.env.REACT_APP_URL}/orders/updateorder`, {
        orderheaderid: orderheaderid,
        orderstatus: 'cancelled',
        cancelled: dayjs().format('YYYY-MM-DD HH:mm:ss')
      })
      .then((res) => {
        console.log(res);
        if (res.data.status) {
          enqueueSnackbar('Order Cancelled Successfully', {
            variant: 'success',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 2000
          });
          refetchOrders();
          fetchorderscount();
          setCancelOpen(false);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };

  // const getOrders = async () => {
  //   try {
  //     await axios
  //       .get(
  //         `${
  //           process.env.REACT_APP_URL
  //         }/orders/tenant/getorders/?tenantid=${tid}&locationid=${locationId}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
  //           page + 1
  //         }&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
  //       )
  //       .then((res) => {
  //         setRows(res.data.details);
  //       })
  //       .catch((err) => {
  //         console.log(err);
  //       });
  //   } catch (err) {
  //     console.log(err);
  //   }
  // };
  // useEffect(() => {
  //   getOrders();
  // }, [tabstatus, startdate, enddate, page, rowsPerPage, debouncedSearch, locationId]);
  const fetchOrders = async ({ pageParam = 1 }) => {
    const res = await axios.get(
      `${process.env.REACT_APP_URL}/orders/tenant/getorders/?tenantid=${tid}&locationid=${locationId}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${pageParam}&pagesize=${rowsPerPage}&keyword=${debouncedSearch}`
    );

    return {
      data: res.data.details,
      nextPage: res.data.details.length === rowsPerPage ? pageParam + 1 : undefined
    };
  };

  const {
    data: rowdata,
    isError: isErrorGetOrders,
    error: errorGetOrders,
    fetchNextPage,
    isLoading: isLoadingGeyOrders,
    hasNextPage,
    isFetchingNextPage,
    refetch: refetchOrders
    // status: rowdataStatus
  } = useInfiniteQuery({
    queryKey: [tabstatus, startdate, enddate, page, rowsPerPage, debouncedSearch, locationId],
    queryFn: fetchOrders,
    getNextPageParam: (lastPage) => lastPage.nextPage
  });

  const rows = rowdata ? rowdata.pages.flatMap((p) => p.data) : [];

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

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

  const fetchpercentage = async () => {
    setLoading(true);
    try {
      await axios
        .get(`${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}`)
        .then((res) => {
          console.log('summary', res.data.details);
          setCoveredorders(res.data.details.delivered.toString());
          setCancelled(res.data.details.cancelled.toString());
          setUncoveredorders(res.data.details.pending.toString());
          setCreated(res.data.details.created.toString());
          setPercentage1((Math.round((res.data.details.created / res.data.details.total) * 100) || 0).toString());
          setPercentage3((Math.round((res.data.details.delivered / res.data.details.total) * 100) || 0).toString());
          setPercentage4((Math.round((res.data.details.cancelled / res.data.details.total) * 100) || 0).toString());
          setPercentage2((Math.round((res.data.details.pending / res.data.details.total) * 100) || 0).toString());
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchpercentage();
  }, []);

  const fetchorderscount = async () => {
    setLoading(true);
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}&locationid=${locationId}&fromdate=${startdate}&todate=${enddate}`
        )
        .then((res) => {
          console.log('fetchorderscount', res.data.details);
          setCreatedLenght(res.data.details.created);
          setPendingLenght(res.data.details.pending);
          setDeliveredlenght(res.data.details.delivered);
          setCancelledLenght(res.data.details.cancelled);
          tabvalue === 0 && setPageCount(res.data.details.created);
          tabvalue === 1 && setPageCount(res.data.details.pending);
          tabvalue === 2 && setPageCount(res.data.details.delivered);
          tabvalue === 3 && setPageCount(res.data.details.cancelled);
          setLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    } catch (err) {
      console.log(err);
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchorderscount();
  }, [tabvalue, locationId, startdate, enddate]);
  // ============================================= || gettenantlocations (branches) || =============================================
  const gettenantlocations = async (id) => {
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${id}`);
      console.log('gettenantlocations', res.data.details);
      if (res.data.details.length == 1) {
        setIsLocation(true);
        setTenantlocations(res.data.details);
        setPickCust(res.data.details[0]);
      } else {
        setTenantlocations(res.data.details);
      }
    } catch (err) {
      console.log('gettenantlocations', err);
    }
  };
  useEffect(() => {
    gettenantlocations(tenId);
  }, []);

  return (
    <>
      {loading && (
        <>
          <Loader />
          <CircularLoader />
        </>
      )}
      {/* ============================================== || TitleCard || ============================================== */}
      <Stack direction={{ xs: 'column', md: 'row' }} justifyContent="space-between" alignItems="center" sx={{ mt: -2, mb: 1 }}>
        <Typography variant="h3">Orders</Typography>
      </Stack>
      {/* ============================================== || HoverSocialCard || ============================================== */}

      <Grid container spacing={3} sx={{}}>
        <Grid item xs={12} custom500={6} md={3}>
          <HoverSocialCard
            primary="Created Orders"
            secondary={created === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : created}
            percentage={percentage1.toString()}
            color={theme.palette.primary.main}
          />
        </Grid>
        <Grid item xs={12} custom500={6} md={3}>
          <HoverSocialCard
            primary="Pending orders"
            secondary={uncoveredorders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : uncoveredorders}
            percentage={percentage2.toString()}
            color={theme.palette.warning.main}
          />
        </Grid>

        <Grid item xs={12} custom500={6} md={3}>
          <HoverSocialCard
            primary="Delivered orders"
            secondary={coveredorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : coveredorders}
            percentage={percentage3.toString()}
            color={theme.palette.success.main}
          />
        </Grid>

        <Grid item xs={12} custom500={6} md={3}>
          <HoverSocialCard
            primary="Cancelled Orders"
            secondary={cancelled === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : cancelled}
            percentage={percentage4.toString()}
            color={theme.palette.secondary[600]}
          />
        </Grid>
      </Grid>
      {/* ============================================== || Filters || ============================================== */}

      <Stack
        display={'flex'}
        direction={'row'}
        justifyContent={'space-between'}
        alignItems={'center'}
        flexWrap={'wrap'}
        gap={2}
        sx={{ my: 2 }}
      >
        {startdate && enddate && (
          <Stack direction="row" flexWrap={'wrap'} gap={2} alignItems="flex-start">
            <Chip label={`Orders-${datestatus ? datestatus : ''}`} color="primary" variant="light" />

            <Chip
              label={
                <Typography noWrap color="secondary">
                  {dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
                </Typography>
              }
              sx={{ cursor: 'pointer' }}
              variant="combined"
              color="warning"
              onClick={() => setDateOpen(true)}
              deleteIcon={<CalendarMonth style={{ fontSize: 18 }} />}
              onDelete={() => setDateOpen(true)}
            />
          </Stack>
        )}
        <Stack
          display={'flex'}
          flexDirection={'row'}
          alignItems={'center'}
          flexWrap={'wrap'}
          gap={2}
          sx={{ width: { xs: '100%', custom800: 'auto' } }}
        >
          {tenantLocations.length == 1 ? (
            <TextField
              variant="outlined"
              fullWidth
              label={'Business Location'}
              value={tenantLocations[0].locationname}
              focused
              sx={{ width: 400 }}
              InputProps={{
                style: { color: theme.palette.primary.main },
                startAdornment: (
                  <InputAdornment position="start">
                    <MyLocationIcon color="primary" />
                  </InputAdornment>
                )
              }}
            />
          ) : (
            <Autocomplete
              fullWidth
              id="combo-box-demo"
              options={tenantLocations || []}
              getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
              renderInput={(params) => <TextField {...params} label={'Select Location'} value={locoName} color="primary" />}
              sx={{
                width: { xs: '100%', custom800: 400 }
              }}
              onChange={(event, value, reason) => {
                if (value) {
                  console.log('Business Locations', value);
                  setLocationId(value.locationid);
                  setLocoName(value.locationname);
                }
                if (reason == 'clear') {
                  setLocationId(0);
                  setLocoName('Select Location');
                }
              }}
            />
          )}
          {/* <Tooltip title="Date Filter">
            <IconButton
              color="secondary"
              variant="light"
              sx={{ color: 'text.primary', bgcolor: 'grey.200' }}
              aria-haspopup="true"
              onClick={() => setDateOpen(true)}
            >
              <FilterList />
            </IconButton>
          </Tooltip> */}
        </Stack>
      </Stack>
      {/* ============================================== || Table || ============================================== */}
      <Stack
        display={'flex'}
        flexDirection={'row'}
        justifyContent={'space-between'}
        alignItems={'center'}
        flexWrap={'wrap-reverse'}
        gap={2}
        sx={{
          border: '1px solid ',
          borderBottom: 0,
          borderColor: 'bg.main',
          p: 1.5
        }}
      >
        {/* Tabs Wrapper */}

        <Tabs value={tabvalue} onChange={handleChangetab} variant="scrollable" scrollButtons="auto" allowScrollButtonsMobile>
          {statusMap.map((item, index) => (
            <Tab
              key={index}
              label={
                <Stack direction="row" alignItems="center" spacing={1}>
                  {item.icon}
                  <span>{item.label}</span>
                  <Chip label={item.count} color="primary" variant="light" size="small" />
                </Stack>
              }
            />
          ))}
        </Tabs>

        {/* Search Box */}
        <Stack sx={{ width: { xs: '100%', custom1100: 350 } }}>
          <FormControl fullWidth>
            <OutlinedInput
              inputRef={textFieldRef}
              placeholder="Search (ctrl+k)"
              value={searchword}
              onChange={(e) => setSearchword(e.target.value)}
              autoComplete="off"
              startAdornment={
                <InputAdornment position="start">
                  <SearchOutlined style={{ color: theme.palette.primary.main }} />
                </InputAdornment>
              }
              endAdornment={
                <Tooltip title="clear">
                  <IconButton
                    sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                    onClick={() => {
                      setSearchword('');
                      refetchOrders();
                      fetchorderscount();
                    }}
                  >
                    <ClearIcon fontSize="small" sx={{ color: theme.palette.primary.main }} />
                  </IconButton>
                </Tooltip>
              }
            />
          </FormControl>
        </Stack>
      </Stack>
      <MainCard content={false}>
        <Fragment>
          <TableContainer
            onScroll={handleScroll}
            ref={containerRef}
            sx={{
              width: '100%',
              borderBottom: 1,
              borderColor: 'divider',
              maxHeight: 'calc(100vh - 225px)',
              overflow: 'auto',
              '&::-webkit-scrollbar': {
                width: '12px', // scroll bar width
                cursor: 'pointer'
              },
              '&::-webkit-scrollbar-thumb': {
                backgroundColor: theme.palette.primary.main, // thumb color
                borderRadius: '8px',
                cursor: 'pointer'
              },
              '&::-webkit-scrollbar-thumb:hover': {
                backgroundColor: theme.palette.primary.dark, // hover color
                cursor: 'pointer'
              },
              '&::-webkit-scrollbar-track': {
                backgroundColor: theme.palette.primary.lighter,
                cursor: 'pointer'
              }
            }}
          >
            <Table stickyHeader>
              <TableHead>
                <TableRow sx={{}}>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> S.No</TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}>
                    {' '}
                    Orders Location
                  </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Pickup</TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Drop </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Qty </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Cod </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> kms </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Charges </TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Notes</TableCell>
                  <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}> Status </TableCell>
                  {currentStatus == 'created' && (
                    <TableCell sx={{ position: 'sticky !important', backgroundColor: theme.palette.secondary.light }}>Action </TableCell>
                  )}
                </TableRow>
              </TableHead>
              {loading && (
                <>
                  <TableBody>
                    {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item, index) => (
                      <TableRow key={index}>
                        <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" />
                        </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 && (
                  <>
                    <TableCell colSpan={tabstatus === 'Created' ? 11 : 10}>
                      <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                        <Empty description={' Orders not found in this status'} />
                      </Stack>
                    </TableCell>
                  </>
                )}

                {rows?.map((row, index) => {
                  return (
                    <>
                      <TableRow
                        key={index}
                        sx={{
                          cursor: 'pointer'
                        }}
                      >
                        <TableCell padding="none">
                          <Typography> {page * rowsPerPage + index + 1}</Typography>
                        </TableCell>

                        <TableCell align="left">
                          <Typography variant="subtitle1" noWrap>
                            {row.locationname} {row.locationsuburb && `- ${row.locationsuburb}`}
                          </Typography>
                          <Typography variant="body2" noWrap>
                            {row.orderid}
                          </Typography>
                          <Stack direction={'row'} spacing={1} alignItems="center">
                            <Typography noWrap sx={{ fontSize: '11px' }}>
                              {dayjs(row.pickupslot).format('DD/MM/YYYY')}
                            </Typography>
                            <Tooltip title={'Pickup Slot'}>
                              <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                                {dayjs(row.pickupslot).format('hh:mm A')}
                              </Typography>
                            </Tooltip>
                          </Stack>{' '}
                          {/* <Stack direction={'row'} spacing={1} alignItems="center">
                            <Stack>
                              <Typography noWrap sx={{ fontSize: '11px' }}>
                                {dayjs(row.orderdate).utc().format('DD/MM/YYYY')}
                              </Typography>
                              <Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
                                {dayjs(row.orderdate).utc().format('hh:mm A')}
                              </Typography>
                            </Stack>
                            -
                            <Stack>
                              <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>
                            </Stack>
                          </Stack> */}
                        </TableCell>

                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="subtitle2">{row.pickupcustomer}</Typography>
                              <Typography variant="caption">{row.pickupcontactno}</Typography>
                              <Tooltip title={row.pickupaddress}>
                                <Typography variant="caption">{row.pickupsuburb || row.pickupaddress.slice(0, 20)}</Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>
                        <TableCell align="left">
                          <Stack direction={'row'} spacing={1}>
                            <Stack direction="column">
                              <Typography variant="subtitle2">{row.deliverycustomer}</Typography>
                              <Typography variant="caption">{row.deliverycontactno}</Typography>
                              <Tooltip title={row.deliveryaddress}>
                                <Typography variant="caption">
                                  {row.deliverysuburb ||
                                    (row.deliveryaddress?.length > 20 ? `${row.deliveryaddress.slice(0, 20)}...` : row.deliveryaddress)}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </Stack>
                        </TableCell>

                        <TableCell align="left">
                          <Typography variant="subtitle1" sx={{ color: getValueColor(row.quantity), textAlign: 'center' }}>
                            {row.quantity}
                          </Typography>
                        </TableCell>
                        <TableCell align="left">
                          <Typography variant="subtitle1" sx={{ color: getValueColor(row.collectionamt), textAlign: 'center' }}>
                            ₹{row.collectionamt.toFixed(2)}
                          </Typography>
                        </TableCell>
                        <TableCell align="left">
                          <Typography variant="subtitle1" sx={{ color: getValueColor(row.kms), textAlign: 'center' }}>
                            {row.kms}
                          </Typography>
                        </TableCell>

                        <TableCell align="left">
                          <Typography variant="subtitle1" sx={{ color: getValueColor(row.deliverycharge), textAlign: 'center' }}>
                            ₹{row.deliverycharge.toFixed(2)}
                          </Typography>
                        </TableCell>
                        <TableCell align="left">
                          <Typography>{row.ordernotes}</Typography>
                        </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="Delivered" 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="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>

                        {currentStatus == 'created' && (
                          <TableCell>
                            {row.orderstatus == 'created' && (
                              <>
                                <Tooltip title="Cancel">
                                  <IconButton
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      setOrderheaderid(row.orderheaderid);
                                      setCancelOpen(true);
                                    }}
                                  >
                                    <CloseOutlined
                                      style={{
                                        color: theme.palette.error.main
                                      }}
                                      //  twoToneColor={theme.palette.primary.main}
                                    />
                                  </IconButton>
                                </Tooltip>
                              </>
                            )}
                          </TableCell>
                        )}
                      </TableRow>
                    </>
                  );
                })}
                {rows?.length != 0 && (
                  <TableRow>
                    <TableCell colSpan={15} rowSpan={3}>
                      <div ref={loadMoreRef} style={{ height: 40, textAlign: 'center' }}>
                        {isFetchingNextPage ? <CircularProgress /> : hasNextPage ? <CircularProgress /> : 'No More Orders'}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </Fragment>
      </MainCard>

      {/* ============================================== || cancel order || ============================================== */}
      <Dialog open={cancelOpen} onClose={() => setCancelOpen(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
                onClick={() => {
                  setCancelOpen(false);
                }}
                color="secondary"
                variant="outlined"
              >
                No
              </Button>{' '}
              <Button
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  cancelorder();
                }}
                autoFocus
              >
                Yes, Cancel
              </Button>
            </Stack>
          </Stack>
        </DialogContent>
      </Dialog>
      {/* ============================================== || Date filter || ============================================== */}
      <DateFilterDialog
        open={dateOpen}
        onClose={() => setDateOpen(false)}
        onApply={({ startDate, endDate, label }) => {
          setStartdate(startDate);
          setEnddate(endDate);
          setDatestatus(label);
        }}
      />
    </>
  );
};

export default Orders;
