import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  Drawer,
  IconButton,
  Typography,
  useMediaQuery,
  useTheme,
  Tooltip,
  TableCell,
  Stack,
  TableRow,
  TableBody,
  TableHead,
  Table,
  TableContainer,
  CircularProgress,
  InputBase,
  Paper,
  Avatar,
  ButtonBase
} from '@mui/material';
import {
  MdMenu,
  MdSearch,
  MdClear,
  MdPlace,
  MdStorefront,
  MdMyLocation,
  MdAccessTime,
  MdLocalShipping,
  MdHourglassEmpty,
  MdCheckCircle,
  MdCancel,
  MdReceiptLong
} from 'react-icons/md';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { fetchOrders1, gettenantlocations } from '../api/api';
import Loader from 'components/Loader';
import CircularLoader from 'components/nearle_components/CircularLoader';
import { Empty, Skeleton } from 'antd';
import {
  DT,
  BRAND,
  BRAND_LIGHT,
  tint,
  soft,
  ring,
  edge,
  StatusBadge,
  AccentAvatar
} from '../_shared/ordersDesign';
import axios from 'axios';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

const drawerWidth = 300;

// Status filter tabs — colors aligned with STATUS_META in the shared design system
// (blue=created, amber=pending, green=delivered, red=cancelled).
const STATUS_TABS = [
  { label: 'Created', value: 'created', color: '#3b82f6', icon: MdLocalShipping },
  { label: 'Pending', value: 'pending', color: '#f59e0b', icon: MdHourglassEmpty },
  { label: 'Delivered', value: 'delivered', color: '#10b981', icon: MdCheckCircle },
  { label: 'Cancelled', value: 'cancelled', color: '#ef4444', icon: MdCancel }
];

const ResponsiveLocationDrawer = () => {
  const loadMoreRef = useRef();
  const containerRef = useRef();
  const theme = useTheme();
  const tenantid = localStorage.getItem('tenantid');
  const isDesktop = useMediaQuery('(min-width:900px)');
  const [open, setOpen] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState(null);
  const [currentStatus, setCurrentStatus] = useState('created');
  const [tabvalue, setTabvalue] = useState(0);
  const [createdLenght, setCreatedLenght] = useState();
  const [pendingLenght, setPendingLenght] = useState();
  const [deliveredlenght, setDeliveredlenght] = useState();
  const [cancelledLenght, setCancelledLenght] = useState();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [searchLocation, setSearchLocation] = useState('');
  const [debouncedSearchLocation, setDebouncedSearchLocation] = useState('');

  const [searchword, setSearchword] = useState('');
  const [debouncedSearchword, setDebouncedSearchword] = useState('');

  // Per-status counts keyed by tab value, so the filter pills can show a badge.
  const statusCounts = {
    created: createdLenght,
    pending: pendingLenght,
    delivered: deliveredlenght,
    cancelled: cancelledLenght
  };

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchLocation(searchLocation);
    }, 400);

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

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

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

  const handleChangetab = (i) => {
    setSearchword('');
    setRowsPerPage(10);
    setTabvalue(i);
    setCurrentStatus(STATUS_TABS[i].value);
    setPage(0);
  };

  const {
    data: locations,
    isLoading: locationIsLoading,
    isError: locationIsError,
    error: locationError
  } = useQuery({
    queryKey: ['locations', debouncedSearchLocation],
    queryFn: gettenantlocations
  });
  // Auto-pick a sensible default whenever the locations list changes:
  //   • Nothing selected yet → pick the first item.
  //   • Current selection has been filtered out → also pick the first item
  //     (otherwise the orders panel queries a locationid that's no longer
  //     in the visible list, returning nothing and confusing the operator).
  useEffect(() => {
    if (!Array.isArray(locations) || locations.length === 0) return;
    const stillVisible = selectedLocation && locations.some((l) => l.locationid === selectedLocation.locationid);
    if (!stillVisible) setSelectedLocation(locations[0]);
  }, [locations]);

  const {
    data: ordersData,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading,
    error
  } = useInfiniteQuery({
    queryKey: [
      'orders',
      tenantid,
      selectedLocation?.locationid ?? null, // stable
      currentStatus,
      startdate,
      enddate,
      debouncedSearchword,
      rowsPerPage
    ],
    queryFn: fetchOrders1,
    getNextPageParam: (lastPage) => lastPage.nextPage
  });

  const rows = ordersData?.pages?.flatMap((page) => page.details) || [];

  useEffect(() => {
    if (!hasNextPage) return;
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          fetchNextPage();
        }
      },
      {
        root: document.querySelector('.MuiTableContainer-root'),
        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 fetchorderscount = async () => {
    setLoading(true);
    try {
      await axios
        .get(
          `${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tenantid}&locationid=${selectedLocation?.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();
  }, [currentStatus, selectedLocation, startdate, enddate]);

  useEffect(() => {
    setOpen(isDesktop);
  }, [isDesktop]);
  const toggleDrawer = () => setOpen(!open);

  const errMessage = locationIsError ? `${locationError.message}` : null;

  useEffect(() => {
    errMessage && console.log(errMessage);
  }, [errMessage]);

  // Brand-styled scrollbar reused on the sidebar + table.
  const scrollbarSx = {
    '&::-webkit-scrollbar': { width: 8, height: 8 },
    '&::-webkit-scrollbar-thumb': {
      backgroundColor: edge(BRAND),
      borderRadius: 8,
      '&:hover': { backgroundColor: BRAND }
    },
    '&::-webkit-scrollbar-track': { backgroundColor: DT.surfaceAlt }
  };

  // --------------------------------------------------------------------------
  // Sidebar — searchable location list. Shared between the desktop persistent
  // drawer and the mobile temporary drawer.
  // --------------------------------------------------------------------------
  const sidebarContent = (
    <Stack sx={{ height: '100%', bgcolor: '#fff' }}>
      {/* Sidebar header */}
      <Box sx={{ px: 1.5, pt: 1.5, pb: 1 }}>
        <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1.25 }}>
          <Avatar
            variant="rounded"
            sx={{ width: 30, height: 30, bgcolor: BRAND, color: '#fff', borderRadius: 1.5, boxShadow: `0 4px 12px ${ring(BRAND)}` }}
          >
            <MdStorefront size={16} />
          </Avatar>
          <Stack spacing={0}>
            <Typography sx={{ fontSize: 13.5, fontWeight: 800, color: DT.textPrimary, lineHeight: 1.1 }}>Locations</Typography>
            <Typography sx={{ fontSize: 10.5, fontWeight: 600, color: DT.textMuted }}>
              {Array.isArray(locations) ? `${locations.length} active` : '—'}
            </Typography>
          </Stack>
        </Stack>

        {/* Search pill */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 0.75,
            px: 1.25,
            py: 0.75,
            borderRadius: 999,
            bgcolor: tint(BRAND),
            border: `1.5px solid ${edge(BRAND)}`,
            transition: 'all 0.18s',
            '&:focus-within': { borderColor: BRAND, boxShadow: `0 0 0 3px ${ring(BRAND)}` }
          }}
        >
          <MdSearch size={16} style={{ color: BRAND, flexShrink: 0 }} />
          <InputBase
            placeholder="Search location"
            value={searchLocation}
            onChange={(e) => setSearchLocation(e.target.value)}
            autoComplete="off"
            sx={{
              flex: 1,
              fontSize: 13,
              fontWeight: 600,
              color: DT.textPrimary,
              '& input::placeholder': { color: DT.textMuted, opacity: 1 }
            }}
          />
          {searchLocation && (
            <IconButton size="small" onClick={() => setSearchLocation('')} sx={{ p: 0.25, color: BRAND }}>
              <MdClear size={14} />
            </IconButton>
          )}
        </Box>
      </Box>

      {/* Location list */}
      <Box sx={{ flex: 1, overflowY: 'auto', px: 1, pb: 1, ...scrollbarSx }}>
        {locationIsLoading &&
          Array.from({ length: 8 }).map((_, i) => (
            <Box key={i} sx={{ px: 1, py: 1 }}>
              <Skeleton avatar active paragraph={{ rows: 1 }} title={false} />
            </Box>
          ))}

        {!locationIsLoading && Array.isArray(locations) && locations.length === 0 && (
          <Box sx={{ py: 5 }}>
            <Empty description="No locations" />
          </Box>
        )}

        <Stack spacing={0.5}>
          {locations?.map((row, index) => {
            const isSelected = row.locationid === selectedLocation?.locationid;
            return (
              <ButtonBase
                key={index}
                onClick={() => setSelectedLocation(row)}
                sx={{
                  width: '100%',
                  justifyContent: 'flex-start',
                  textAlign: 'left',
                  gap: 1,
                  px: 1,
                  py: 0.875,
                  borderRadius: 2,
                  position: 'relative',
                  transition: 'background-color 0.14s, box-shadow 0.14s',
                  bgcolor: isSelected ? tint(BRAND) : 'transparent',
                  boxShadow: isSelected ? `inset 3px 0 0 ${BRAND}` : 'none',
                  '&:hover': { bgcolor: isSelected ? tint(BRAND) : DT.surfaceAlt }
                }}
              >
                <AccentAvatar color={BRAND} selected={isSelected} size={36}>
                  {row.locationname?.[0]?.toUpperCase() || '?'}
                </AccentAvatar>
                <Stack spacing={0} sx={{ minWidth: 0, flex: 1 }}>
                  <Typography
                    sx={{ fontSize: 13, fontWeight: 700, color: isSelected ? BRAND : DT.textPrimary, lineHeight: 1.2 }}
                    noWrap
                  >
                    {row.locationname}
                  </Typography>
                  <Stack direction="row" alignItems="center" spacing={0.375}>
                    <MdPlace size={11} style={{ color: DT.textMuted, flexShrink: 0 }} />
                    <Typography sx={{ fontSize: 11, fontWeight: 600, color: DT.textSecondary }} noWrap>
                      {row.suburb || '—'}
                    </Typography>
                  </Stack>
                </Stack>
              </ButtonBase>
            );
          })}
        </Stack>
      </Box>
    </Stack>
  );

  return (
    <React.Fragment>
      {locationIsLoading && (
        <>
          <Loader /> <CircularLoader />
        </>
      )}

      <Box sx={{ display: 'flex', width: '100%', height: '100%', position: 'relative', bgcolor: DT.surfaceAlt }}>
        {/* ---------------- LOCATION SIDEBAR ---------------- */}
        <Drawer
          variant={isDesktop ? 'persistent' : 'temporary'}
          open={open}
          onClose={() => !isDesktop && toggleDrawer()}
          ModalProps={{ keepMounted: true }}
          sx={{
            '& .MuiDrawer-paper': {
              width: drawerWidth,
              boxSizing: 'border-box',
              position: 'absolute',
              left: 0,
              top: 0,
              height: '100%',
              overflow: 'hidden',
              borderRight: `1px solid ${DT.borderSubtle}`,
              transition: 'transform 0.35s ease-in-out',
              zIndex: 10
            }
          }}
        >
          {sidebarContent}
        </Drawer>

        {/* ---------------- MAIN PANEL ---------------- */}
        <Box
          sx={{
            flexGrow: 1,
            height: '100%',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            pl: isDesktop && open ? `${drawerWidth}px` : 0,
            transition: 'padding-left 0.3s ease'
          }}
        >
          {/* ---------------- GRADIENT HEADER ---------------- */}
          <Paper
            elevation={0}
            sx={{
              flexShrink: 0,
              px: { xs: 1.25, sm: 1.75 },
              py: { xs: 1, sm: 1.25 },
              borderRadius: 0,
              borderBottom: `1px solid ${DT.borderSubtle}`,
              background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`
            }}
          >
            <Stack
              direction={{ xs: 'column', md: 'row' }}
              alignItems={{ xs: 'stretch', md: 'center' }}
              justifyContent="space-between"
              spacing={{ xs: 1, md: 1.5 }}
            >
              <Stack direction="row" alignItems="center" spacing={1.25}>
                <Tooltip title={open ? 'Hide locations' : 'Show locations'} arrow>
                  <IconButton
                    onClick={toggleDrawer}
                    sx={{
                      width: 34,
                      height: 34,
                      borderRadius: 1.5,
                      bgcolor: '#fff',
                      border: `1px solid ${DT.borderSubtle}`,
                      color: BRAND,
                      '&:hover': { bgcolor: tint(BRAND), borderColor: BRAND }
                    }}
                  >
                    <MdMenu size={18} />
                  </IconButton>
                </Tooltip>

                <Avatar
                  variant="rounded"
                  sx={{ width: 36, height: 36, bgcolor: BRAND, color: '#fff', borderRadius: 1.5, boxShadow: `0 4px 12px ${ring(BRAND)}` }}
                >
                  <MdMyLocation size={19} />
                </Avatar>
                <Stack spacing={0.125}>
                  <Typography
                    variant="h3"
                    sx={{
                      fontWeight: 800,
                      color: DT.textPrimary,
                      lineHeight: 1.1,
                      fontSize: { xs: '1.05rem', sm: '1.2rem', md: '1.3rem' }
                    }}
                    noWrap
                  >
                    {selectedLocation?.locationname || 'Select a location'}
                  </Typography>
                  <Stack direction="row" alignItems="center" spacing={0.75}>
                    <Box sx={{ width: 7, height: 7, borderRadius: '50%', bgcolor: '#10b981', boxShadow: '0 0 0 3px rgba(16,185,129,0.18)' }} />
                    <Typography sx={{ fontSize: 11.5, color: DT.textSecondary, fontWeight: 600 }} noWrap>
                      {selectedLocation?.suburb ? `${selectedLocation.suburb} · ` : ''}Live · {dayjs(startdate).format('DD MMM YYYY')}
                    </Typography>
                  </Stack>
                </Stack>
              </Stack>

              {/* Order search pill */}
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 0.75,
                  px: 1.25,
                  py: 0.75,
                  borderRadius: 999,
                  bgcolor: '#fff',
                  border: `1.5px solid ${edge(BRAND)}`,
                  minWidth: { xs: '100%', md: 280 },
                  maxWidth: { md: 360 },
                  transition: 'all 0.18s',
                  '&:focus-within': { borderColor: BRAND, boxShadow: `0 0 0 3px ${ring(BRAND)}` }
                }}
              >
                <MdSearch size={16} style={{ color: BRAND, flexShrink: 0 }} />
                <InputBase
                  placeholder="Search order details"
                  value={searchword}
                  onChange={(e) => setSearchword(e.target.value)}
                  autoComplete="off"
                  sx={{
                    flex: 1,
                    fontSize: 13,
                    fontWeight: 600,
                    color: DT.textPrimary,
                    '& input::placeholder': { color: DT.textMuted, opacity: 1 }
                  }}
                />
                {searchword && (
                  <IconButton size="small" onClick={() => setSearchword('')} sx={{ p: 0.25, color: BRAND }}>
                    <MdClear size={14} />
                  </IconButton>
                )}
              </Box>
            </Stack>
          </Paper>

          {/* ---------------- STATUS FILTER PILLS ---------------- */}
          <Box
            sx={{
              flexShrink: 0,
              px: { xs: 1, sm: 1.5 },
              py: 1,
              bgcolor: '#fff',
              borderBottom: `1px solid ${DT.borderSubtle}`,
              display: 'flex',
              gap: 0.75,
              overflowX: 'auto',
              ...scrollbarSx
            }}
          >
            {STATUS_TABS.map((item, index) => {
              const isActive = tabvalue === index;
              const Icon = item.icon;
              const count = statusCounts[item.value];
              return (
                <ButtonBase
                  key={index}
                  onClick={() => handleChangetab(index)}
                  sx={{
                    flexShrink: 0,
                    gap: 0.75,
                    px: 1.25,
                    py: 0.625,
                    borderRadius: 999,
                    fontWeight: 700,
                    transition: 'all 0.15s',
                    border: `1.5px solid ${isActive ? item.color : DT.borderSubtle}`,
                    bgcolor: isActive ? item.color : '#fff',
                    color: isActive ? '#fff' : DT.textSecondary,
                    boxShadow: isActive ? `0 4px 12px ${ring(item.color)}` : 'none',
                    '&:hover': {
                      borderColor: item.color,
                      color: isActive ? '#fff' : item.color,
                      bgcolor: isActive ? item.color : tint(item.color)
                    }
                  }}
                >
                  <Icon size={14} />
                  <Typography sx={{ fontSize: 12.5, fontWeight: 700, lineHeight: 1 }}>{item.label}</Typography>
                  <Box
                    sx={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      minWidth: 20,
                      height: 18,
                      px: 0.625,
                      borderRadius: 999,
                      fontSize: 10.5,
                      fontWeight: 800,
                      bgcolor: isActive ? 'rgba(255,255,255,0.25)' : soft(item.color),
                      color: isActive ? '#fff' : item.color
                    }}
                  >
                    {count ?? 0}
                  </Box>
                </ButtonBase>
              );
            })}
          </Box>

          {/* ---------------- ORDERS TABLE ---------------- */}
          <Box sx={{ flex: 1, overflow: 'hidden', p: { xs: 1, sm: 1.5 } }}>
            <Paper
              elevation={0}
              sx={{
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                borderRadius: 2,
                border: `1px solid ${DT.borderSubtle}`,
                overflow: 'hidden',
                background: '#fff',
                boxShadow: DT.shadowSoft
              }}
            >
              <TableContainer
                onScroll={handleScroll}
                ref={containerRef}
                sx={{ flex: 1, overflow: 'auto', ...scrollbarSx }}
              >
                <Table stickyHeader size="small">
                  <TableHead>
                    <TableRow
                      sx={{
                        '& th': {
                          backgroundColor: DT.surfaceAlt,
                          color: DT.textSecondary,
                          fontSize: 10.5,
                          fontWeight: 800,
                          letterSpacing: 0.5,
                          textTransform: 'uppercase',
                          whiteSpace: 'nowrap',
                          borderBottom: `1px solid ${DT.borderSubtle}`,
                          py: 0.75,
                          px: 1
                        }
                      }}
                    >
                      <TableCell sx={{ width: 36 }}>#</TableCell>
                      <TableCell sx={{ minWidth: 150 }}>Order</TableCell>
                      <TableCell sx={{ minWidth: 150 }}>Pickup</TableCell>
                      <TableCell sx={{ minWidth: 150 }}>Drop</TableCell>
                      <TableCell sx={{ minWidth: 140 }}>Notes</TableCell>
                      <TableCell sx={{ width: 120 }}>Status</TableCell>
                    </TableRow>
                  </TableHead>

                  <TableBody>
                    {/* LOADING STATE */}
                    {loading &&
                      Array.from({ length: 10 }).map((_, index) => (
                        <TableRow key={index}>
                          {Array.from({ length: 6 }).map((__, i) => (
                            <TableCell key={i} sx={{ borderBottom: `1px solid ${DT.divider}`, py: 0.625, px: 1 }}>
                              <Skeleton.Input active size="small" style={{ width: '100%', height: 18 }} />
                            </TableCell>
                          ))}
                        </TableRow>
                      ))}

                    {/* EMPTY STATE */}
                    {!loading && rows?.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={6} sx={{ py: 7, borderBottom: 'none' }}>
                          <Stack alignItems="center" spacing={1.25}>
                            <Avatar variant="rounded" sx={{ width: 56, height: 56, bgcolor: soft('#94a3b8'), color: DT.textMuted, borderRadius: 2 }}>
                              <MdReceiptLong size={26} />
                            </Avatar>
                            <Typography sx={{ fontWeight: 700, color: DT.textPrimary, fontSize: 14 }}>No orders found</Typography>
                            <Typography sx={{ color: DT.textSecondary, fontSize: 12 }}>
                              {searchword ? 'Try a different keyword or clear the search.' : 'No orders in this status for the selected location.'}
                            </Typography>
                          </Stack>
                        </TableCell>
                      </TableRow>
                    )}

                    {/* DATA ROWS */}
                    {!loading &&
                      rows?.map((row, index) => (
                        <TableRow
                          key={index}
                          sx={{
                            cursor: 'pointer',
                            transition: 'background-color 0.12s, box-shadow 0.12s',
                            '& td': { borderBottom: `1px solid ${DT.divider}`, py: 0.75, px: 1, verticalAlign: 'top' },
                            '&:hover': { backgroundColor: tint(BRAND), boxShadow: `inset 3px 0 0 ${BRAND}` }
                          }}
                        >
                          <TableCell>
                            <Typography sx={{ fontWeight: 700, fontSize: 12, color: DT.textMuted }}>{page * rowsPerPage + index + 1}</Typography>
                          </TableCell>

                          {/* Order Info */}
                          <TableCell>
                            <Typography sx={{ fontSize: 12.5, fontWeight: 700, color: DT.textPrimary, lineHeight: 1.25 }} noWrap>
                              {row.orderid}
                            </Typography>
                            <Stack direction="row" alignItems="center" spacing={0.5} sx={{ mt: 0.125 }}>
                              <MdAccessTime size={10} style={{ color: DT.textMuted, flexShrink: 0 }} />
                              <Typography sx={{ fontSize: 10.5, color: DT.textSecondary, fontWeight: 700 }} noWrap>
                                {dayjs(row.deliverydate).utc().format('hh:mm A')}
                              </Typography>
                              <Typography sx={{ fontSize: 10.5, color: DT.textMuted, fontWeight: 600 }} noWrap>
                                · {dayjs(row.deliverydate).utc().format('DD MMM YY')}
                              </Typography>
                            </Stack>
                          </TableCell>

                          {/* Pickup */}
                          <TableCell>
                            <Stack spacing={0.125}>
                              <Typography sx={{ fontSize: 12.5, fontWeight: 700, color: DT.textPrimary, lineHeight: 1.25 }} noWrap>
                                {row.pickupcustomer || '—'}
                              </Typography>
                              <Typography sx={{ fontSize: 11, color: DT.textSecondary, fontWeight: 600, lineHeight: 1.3 }} noWrap>
                                {row.pickupcontactno}
                              </Typography>
                              <Tooltip title={row.pickupaddress || ''}>
                                <Typography sx={{ fontSize: 10.5, color: DT.textMuted, fontWeight: 600, lineHeight: 1.3 }} noWrap>
                                  {row.pickupsuburb || (row.pickupaddress ? `${row.pickupaddress.slice(0, 20)}…` : '—')}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </TableCell>

                          {/* Drop */}
                          <TableCell>
                            <Stack spacing={0.125}>
                              <Typography sx={{ fontSize: 12.5, fontWeight: 700, color: DT.textPrimary, lineHeight: 1.25 }} noWrap>
                                {row.deliverycustomer || '—'}
                              </Typography>
                              <Typography sx={{ fontSize: 11, color: DT.textSecondary, fontWeight: 600, lineHeight: 1.3 }} noWrap>
                                {row.deliverycontactno}
                              </Typography>
                              <Tooltip title={row.deliveryaddress || ''}>
                                <Typography sx={{ fontSize: 10.5, color: DT.textMuted, fontWeight: 600, lineHeight: 1.3 }} noWrap>
                                  {row.deliverysuburb || (row.deliveryaddress ? `${row.deliveryaddress.slice(0, 20)}…` : '—')}
                                </Typography>
                              </Tooltip>
                            </Stack>
                          </TableCell>

                          {/* Notes */}
                          <TableCell>
                            <Typography sx={{ fontSize: 11.5, color: DT.textSecondary, fontWeight: 600, lineHeight: 1.35 }}>
                              {row.ordernotes || '—'}
                            </Typography>
                          </TableCell>

                          {/* Status */}
                          <TableCell>
                            <StatusBadge status={row.orderstatus} />
                          </TableCell>
                        </TableRow>
                      ))}

                    {rows?.length != 0 && (
                      <TableRow>
                        <TableCell colSpan={6} sx={{ borderBottom: 'none' }}>
                          <Stack ref={loadMoreRef} alignItems="center" justifyContent="center" sx={{ height: 40 }}>
                            {isFetchingNextPage || hasNextPage ? (
                              <CircularProgress size={20} sx={{ color: BRAND }} />
                            ) : (
                              <Typography sx={{ fontSize: 11.5, fontWeight: 700, color: DT.textMuted }}>No more orders</Typography>
                            )}
                          </Stack>
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </Paper>
          </Box>
        </Box>
      </Box>
    </React.Fragment>
  );
};

export default ResponsiveLocationDrawer;
