import React, { useState, useEffect, useRef, Fragment } from 'react';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';

import {
  Avatar,
  Box,
  Button,
  Collapse,
  Dialog,
  DialogContent,
  Divider,
  Grid,
  IconButton,
  InputBase,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Typography,
  Skeleton
} from '@mui/material';
import {
  MdLocalShipping,
  MdHourglassEmpty,
  MdCheckCircle,
  MdCancel,
  MdSearch,
  MdClear,
  MdCalendarMonth,
  MdReceiptLong,
  MdStraighten,
  MdCurrencyRupee,
  MdInventory2,
  MdInsights,
  MdLocalOffer,
  MdKeyboardArrowDown,
  MdKeyboardArrowUp,
  MdAssignmentTurnedIn,
  MdGroups,
  MdAccessTime,
  MdTaskAlt,
  MdHighlightOff,
  MdPlace
} from 'react-icons/md';

import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { DateRangePicker } from 'mui-daterange-picker';
import { addDays, addMonths, addWeeks, endOfMonth, endOfWeek, startOfMonth, startOfWeek } from 'date-fns';

import Loader from 'components/Loader';
import { useTheme } from '@mui/material/styles';
import { fetchRidersSummary } from '../api/api';

// ============================================================================
// Design tokens — shared with the rest of the redesigned operator pages.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 16,
  shadowSoft: '0 14px 40px rgba(15, 23, 42, 0.10)',
  shadowMd: '0 8px 24px rgba(15, 23, 42, 0.08)',
  shadowPop: '0 18px 50px rgba(15, 23, 42, 0.18)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const dtA = (c, suffix) => `${c}${suffix}`;
const tint = (c) => dtA(c, '08');
const soft = (c) => dtA(c, '18');
const ring = (c) => dtA(c, '26');
const edge = (c) => dtA(c, '55');

const BRAND = '#662582';
const BRAND_LIGHT = '#9255AB';

// Semantic colour palette per metric column.
const C_PENDING = '#f59e0b';
const C_ASSIGNED = '#0ea5e9';
const C_ACCEPTED = '#6366f1';
const C_ARRIVED = '#06b6d4';
const C_PICKED = '#8b5cf6';
const C_ACTIVE = '#14b8a6';
const C_SKIPPED = '#f97316';
const C_CANCELLED = '#ef4444';
const C_DELIVERED = '#10b981';
const C_KMS = '#f59e0b';
const C_COD = '#ef4444';
const C_PLA = '#10b981';

const AccentAvatar = ({ color, selected, size = 24, children }) => (
  <Avatar
    sx={{
      width: size,
      height: size,
      bgcolor: selected ? color : soft(color),
      color: selected ? '#fff' : color,
      transition: 'background-color 0.15s, color 0.15s'
    }}
  >
    {children}
  </Avatar>
);

// Inline metric pill used in cells; faded slate when zero.
const MetricPill = ({ value, color, icon, isMoney = false, minWidth }) => {
  const n = Number(value);
  const display = isMoney ? formatNumberToRupees(n) : Number.isFinite(n) ? n : value || 0;
  const isZero = !Number.isFinite(n) || n === 0;
  if (isZero) {
    return (
      <Typography variant="caption" sx={{ color: DT.textMuted, fontWeight: 700 }}>
        {display}
      </Typography>
    );
  }
  return (
    <Box
      sx={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 0.5,
        px: 0.875,
        py: 0.25,
        borderRadius: 999,
        bgcolor: tint(color),
        border: `1px solid ${edge(color)}`,
        color,
        fontSize: 12,
        fontWeight: 800,
        whiteSpace: 'nowrap',
        minWidth
      }}
    >
      {icon}
      {display}
    </Box>
  );
};

function formatNumberToRupees(value) {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    minimumFractionDigits: 2
  }).format(value || 0);
}

// ==============================|| RidersSummary ||============================== //

export default function RidersSummary() {
  const theme = useTheme();
  const tenantid = localStorage.getItem('tenantid');

  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [open, setOpen] = useState(false);
  const [datestatus, setDatestatus] = useState('Today');
  const [tenantData, setTenantData] = useState([]);
  const [openRow, setOpenRow] = useState(null);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const textFieldRef = useRef(null);

  // Debounce client-side search on rider name.
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedSearch(searchword), 350);
    return () => clearTimeout(handler);
  }, [searchword]);

  // Ctrl/Cmd+K focuses search.
  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();
        textFieldRef.current && textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);
    return () => document.removeEventListener('keydown', handleKeyPress);
  }, []);

  // ============================================= || fetchRidersSummary || =============================================
  const {
    isLoading: isLoadingReports,
    isError: isErrorReports,
    data: rows,
    error: reportsError
  } = useQuery({
    queryKey: [tenantid, startdate, enddate],
    queryFn: fetchRidersSummary
  });


  // ============================================= || fetchTenantSummary (per rider) || =============================================
  const fetchTenantSummary = async (riderUserid) => {
    try {
      const tenantRes = await axios.get(
        `${process.env.REACT_APP_URL}/deliveries/getriderlocationreportsummary/?&fromdate=${startdate}&todate=${enddate}&userid=${riderUserid}&tenantid=${tenantid}`
      );
      setTenantData(tenantRes.data.details || []);
    } catch (error) {
      console.log('tenantRes', error);
    }
  };

  if (isErrorReports) return 'An error has occurred:(isErrorReports) ' + reportsError.message;

  // Client-side filter on rider name.
  const filteredRows = (rows || []).filter((r) => {
    const q = debouncedSearch.trim().toLowerCase();
    if (!q) return true;
    return (
      String(r.firstname || '').toLowerCase().includes(q) ||
      String(r.lastname || '').toLowerCase().includes(q) ||
      String(r.userid || '').toLowerCase().includes(q)
    );
  });

  // KPI totals — aggregate across filtered rows.
  const kpiTotals = filteredRows.reduce(
    (acc, r) => {
      acc.deliveries += Number(r.totalorders || 0);
      acc.pending += Number(r.pending || 0);
      acc.delivered += Number(r.delivered || 0);
      acc.charges += Number(r.deliveryamt || 0);
      return acc;
    },
    { deliveries: 0, pending: 0, delivered: 0, charges: 0 }
  );

  const kpiCards = [
    { key: 'riders',     label: 'Riders',         color: BRAND,       icon: MdGroups,         value: filteredRows.length },
    { key: 'deliveries', label: 'Deliveries',     color: C_ASSIGNED,  icon: MdLocalShipping,  value: kpiTotals.deliveries },
    { key: 'pending',    label: 'Pending',        color: C_PENDING,   icon: MdHourglassEmpty, value: kpiTotals.pending },
    { key: 'delivered',  label: 'Delivered',      color: C_DELIVERED, icon: MdCheckCircle,    value: kpiTotals.delivered },
  ];

  return (
    <>
      {isLoadingReports && <Loader />}

      {/* ============================================= || Header (compact, standardized actions) || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mb: { xs: 1, md: 1.25 },
          px: { xs: 1.5, sm: 2 },
          py: { xs: 1, sm: 1.25 },
          borderRadius: 2,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`,
          boxShadow: DT.shadowMd
        }}
      >
        <Stack
          direction={{ xs: 'column', sm: 'row' }}
          alignItems={{ xs: 'flex-start', sm: 'center' }}
          justifyContent="space-between"
          spacing={{ xs: 1, sm: 1.5 }}
        >
          <Stack direction="row" alignItems="center" spacing={1.25}>
            <Avatar
              variant="rounded"
              sx={{
                width: 36,
                height: 36,
                bgcolor: BRAND,
                color: '#fff',
                borderRadius: 1.5,
                boxShadow: `0 4px 12px ${ring(BRAND)}`
              }}
            >
              <MdGroups size={19} />
            </Avatar>
            <Stack spacing={0.125}>
              <Typography
                variant="h3"
                sx={{
                  fontWeight: 800,
                  color: DT.textPrimary,
                  lineHeight: 1.1,
                  fontSize: { xs: '1.1rem', sm: '1.25rem', md: '1.375rem' }
                }}
              >
                Riders Summary
              </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 }}>
                  Live · {filteredRows.length} riders · {datestatus}
                </Typography>
              </Stack>
            </Stack>
          </Stack>

          <Tooltip title="Filter by date range" arrow>
            <Button
              onClick={() => setOpen(true)}
              disableElevation
              variant="outlined"
              size="small"
              startIcon={<MdCalendarMonth size={15} />}
              sx={{
                height: 32,
                px: 1.25,
                borderRadius: 1.5,
                textTransform: 'none',
                fontSize: 12.5,
                fontWeight: 700,
                letterSpacing: 0.1,
                bgcolor: '#fff',
                borderColor: DT.borderSubtle,
                color: DT.textPrimary,
                '&:hover': {
                  bgcolor: '#fff',
                  borderColor: BRAND,
                  color: BRAND,
                  boxShadow: `0 0 0 3px ${ring(BRAND)}`
                }
              }}
            >
              {startdate && enddate
                ? `${dayjs(startdate).format('DD MMM')} – ${dayjs(enddate).format('DD MMM')}`
                : 'All time'}
            </Button>
          </Tooltip>
        </Stack>
      </Paper>

      {/* ============================================= || KPI Cards (compact) || ============================================= */}
      <Grid container spacing={{ xs: 1, sm: 1.25, md: 1.5 }}>
        {kpiCards.map((item) => {
          const Icon = item.icon;
          return (
            <Grid item key={item.key} xs={6} sm={6} md={3}>
              <Paper
                elevation={0}
                sx={{
                  position: 'relative',
                  overflow: 'hidden',
                  px: { xs: 1.25, sm: 1.5 },
                  py: { xs: 0.875, sm: 1.125 },
                  borderRadius: 2,
                  border: '1px solid',
                  borderColor: DT.borderSubtle,
                  background: '#fff',
                  transition: 'transform 0.15s, box-shadow 0.15s, border-color 0.15s',
                  '&:hover': {
                    transform: 'translateY(-1px)',
                    boxShadow: DT.shadowMd,
                    borderColor: edge(item.color)
                  }
                }}
              >
                <Box
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    bottom: 0,
                    width: 3,
                    background: item.color
                  }}
                />
                <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={1} sx={{ pl: 0.5 }}>
                  <Stack spacing={0.125} sx={{ minWidth: 0, flex: 1 }}>
                    <Typography
                      sx={{
                        color: DT.textSecondary,
                        fontWeight: 700,
                        letterSpacing: 0.4,
                        textTransform: 'uppercase',
                        fontSize: 10.5,
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        lineHeight: 1.2
                      }}
                    >
                      {item.label}
                    </Typography>
                    <Typography
                      sx={{
                        fontWeight: 800,
                        color: DT.textPrimary,
                        lineHeight: 1.15,
                        fontSize: { xs: '0.95rem', sm: '1.1rem', md: '1.2rem' }
                      }}
                      noWrap
                    >
                      {isLoadingReports ? (
                        <Skeleton sx={{ width: 40 }} animation="wave" />
                      ) : item.isMoney ? (
                        formatNumberToRupees(item.value)
                      ) : (
                        item.value
                      )}
                    </Typography>
                  </Stack>
                  <Avatar
                    variant="rounded"
                    sx={{
                      width: 30,
                      height: 30,
                      bgcolor: soft(item.color),
                      color: item.color,
                      borderRadius: 1.25,
                      flexShrink: 0
                    }}
                  >
                    <Icon size={15} />
                  </Avatar>
                </Stack>
              </Paper>
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Filter Bar (compact) || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1, md: 1.25 },
          p: { xs: 1, md: 1.125 },
          borderRadius: 2,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          background: '#fff',
          boxShadow: DT.shadowSoft
        }}
      >
        <Stack
          direction={{ xs: 'column', md: 'row' }}
          spacing={1.25}
          alignItems={{ xs: 'stretch', md: 'center' }}
          justifyContent="space-between"
        >
          <Box sx={{ width: { xs: '100%', md: 360 } }}>
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 0.75,
                px: 1.25,
                py: 0.5,
                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
                inputRef={textFieldRef}
                placeholder="Search rider name (ctrl+k)"
                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>
          </Box>

          <Stack direction="row" spacing={1} alignItems="center" flexWrap="wrap" useFlexGap>
            <Box
              sx={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: 0.5,
                px: 1,
                py: 0.5,
                borderRadius: 999,
                bgcolor: tint(BRAND),
                border: `1px solid ${edge(BRAND)}`,
                color: BRAND,
                fontSize: 11,
                fontWeight: 800
              }}
            >
              <MdReceiptLong size={12} /> Orders · {datestatus}
            </Box>
            {startdate && enddate && (
              <Box
                sx={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 0.5,
                  px: 1,
                  py: 0.5,
                  borderRadius: 999,
                  bgcolor: tint('#f59e0b'),
                  border: `1px solid ${edge('#f59e0b')}`,
                  color: '#f59e0b',
                  fontSize: 11,
                  fontWeight: 800
                }}
              >
                <MdAccessTime size={12} /> {dayjs(startdate).format('DD/MM/YY')} – {dayjs(enddate).format('DD/MM/YY')}
              </Box>
            )}
          </Stack>
        </Stack>
      </Paper>

      {/* ============================================= || Table (dense, sticky header) || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1, md: 1.25 },
          borderRadius: 2,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          overflow: 'hidden',
          background: '#fff'
        }}
      >
        <TableContainer
          sx={{
            minHeight: 320,
            maxHeight: { xs: 'calc(100vh - 320px)', md: 'calc(100vh - 300px)' },
            overflow: 'auto',
            '&::-webkit-scrollbar': { width: 10, height: 10 },
            '&::-webkit-scrollbar-thumb': {
              backgroundColor: edge(BRAND),
              borderRadius: 8,
              '&:hover': { backgroundColor: BRAND }
            },
            '&::-webkit-scrollbar-track': { backgroundColor: DT.surfaceAlt }
          }}
        >
          <Table stickyHeader size="small" sx={{ minWidth: 1300 }}>
            <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>#</TableCell>
                <TableCell>Rider</TableCell>
                <TableCell align="center">Deliveries</TableCell>
                <TableCell align="center" sx={{ color: `${C_PENDING} !important` }}>Pending</TableCell>
                <TableCell align="center" sx={{ color: `${C_ASSIGNED} !important` }}>Assigned</TableCell>
                <TableCell align="center" sx={{ color: `${C_ACCEPTED} !important` }}>Accepted</TableCell>
                <TableCell align="center" sx={{ color: `${C_ARRIVED} !important` }}>Arrived</TableCell>
                <TableCell align="center" sx={{ color: `${C_PICKED} !important` }}>Picked</TableCell>
                <TableCell align="center" sx={{ color: `${C_ACTIVE} !important` }}>Active</TableCell>
                <TableCell align="center" sx={{ color: `${C_SKIPPED} !important` }}>Skipped</TableCell>
                <TableCell align="center" sx={{ color: `${C_CANCELLED} !important` }}>Cancelled</TableCell>
                <TableCell align="center" sx={{ color: `${C_DELIVERED} !important` }}>Delivered</TableCell>
                <TableCell align="center">Kms</TableCell>
                <TableCell align="center">COD / PLA</TableCell>
                <TableCell align="center">Action</TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {isLoadingReports &&
                filteredRows.length === 0 &&
                Array.from({ length: 10 }).map((_, idx) => (
                  <TableRow key={`sk-${idx}`}>
                    {Array.from({ length: 15 }).map((__, ci) => (
                      <TableCell key={ci} sx={{ borderBottom: `1px solid ${DT.divider}`, py: 0.625, px: 1 }}>
                        <Skeleton animation="wave" height={20} />
                      </TableCell>
                    ))}
                  </TableRow>
                ))}

              {!isLoadingReports && filteredRows.length === 0 && (
                <TableRow>
                  <TableCell colSpan={15} 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
                        }}
                      >
                        <MdGroups size={26} />
                      </Avatar>
                      <Typography sx={{ fontWeight: 700, color: DT.textPrimary, fontSize: 14 }}>
                        No riders to show
                      </Typography>
                      <Typography sx={{ color: DT.textSecondary, fontSize: 12 }}>
                        {searchword ? 'Try a different rider name or clear the search.' : 'Adjust the date range above.'}
                      </Typography>
                      {searchword && (
                        <Button
                          size="small"
                          onClick={() => setSearchword('')}
                          sx={{
                            mt: 0.5,
                            height: 28,
                            textTransform: 'none',
                            fontSize: 12,
                            fontWeight: 700,
                            color: BRAND,
                            borderRadius: 1.25,
                            '&:hover': { bgcolor: tint(BRAND) }
                          }}
                          startIcon={<MdClear size={14} />}
                        >
                          Clear search
                        </Button>
                      )}
                    </Stack>
                  </TableCell>
                </TableRow>
              )}

              {filteredRows.map((row, index) => (
                <Fragment key={`${row.userid}-${index}`}>
                  {/* ===================== || Main rider row || ===================== */}
                  <TableRow
                    sx={{
                      cursor: 'pointer',
                      transition: 'background-color 0.12s, box-shadow 0.12s',
                      '& td': {
                        borderBottom: `1px solid ${DT.divider}`,
                        py: 0.625,
                        px: 1,
                        verticalAlign: 'middle'
                      },
                      backgroundColor: openRow === row.userid ? tint(BRAND) : 'transparent',
                      boxShadow: openRow === row.userid ? `inset 3px 0 0 ${BRAND}` : 'none',
                      '&:hover': {
                        backgroundColor: openRow === row.userid ? soft(BRAND) : tint(BRAND),
                        boxShadow: `inset 3px 0 0 ${BRAND}`
                      }
                    }}
                  >
                    <TableCell>
                      <Typography sx={{ fontWeight: 700, fontSize: 12, color: DT.textMuted }}>{index + 1}</Typography>
                    </TableCell>

                    <TableCell>
                      <Stack direction="row" alignItems="center" spacing={1}>
                        <AccentAvatar color={BRAND} size={28} selected>
                          {String(row.firstname || '?').charAt(0).toUpperCase()}
                        </AccentAvatar>
                        <Stack spacing={0.125}>
                          <Typography sx={{ fontSize: 12.5, fontWeight: 700, color: DT.textPrimary, lineHeight: 1.25 }} noWrap>
                            {row.firstname} {row.lastname}
                          </Typography>
                          <Typography sx={{ fontSize: 10.5, fontWeight: 600, color: DT.textMuted, lineHeight: 1.3 }}>
                            Id : {row.userid}
                          </Typography>
                        </Stack>
                      </Stack>
                    </TableCell>

                    <TableCell align="center">
                      <MetricPill value={row.totalorders} color={BRAND} icon={<MdInventory2 size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.pending} color={C_PENDING} icon={<MdHourglassEmpty size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.assigned} color={C_ASSIGNED} icon={<MdAssignmentTurnedIn size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.accepted} color={C_ACCEPTED} icon={<MdCheckCircle size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.arrived} color={C_ARRIVED} icon={<MdCheckCircle size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.picked} color={C_PICKED} icon={<MdLocalShipping size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.active} color={C_ACTIVE} icon={<MdLocalShipping size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.skipped} color={C_SKIPPED} icon={<MdCancel size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.cancelled} color={C_CANCELLED} icon={<MdCancel size={11} />} />
                    </TableCell>
                    <TableCell align="center">
                      <MetricPill value={row.delivered} color={C_DELIVERED} icon={<MdCheckCircle size={11} />} />
                    </TableCell>

                    <TableCell align="center">
                      <Tooltip title="Cumulative Kms" placement="top">
                        <Box sx={{ display: 'inline-block' }}>
                          <MetricPill
                            value={row.cumulativekms ? Number(parseFloat(row.cumulativekms).toFixed(2)) : 0}
                            color={C_KMS}
                            icon={<MdStraighten size={11} />}
                          />
                        </Box>
                      </Tooltip>
                    </TableCell>

                    <TableCell align="center">
                      <Stack direction="row" spacing={0.5} justifyContent="center">
                        <Tooltip title="Pay on Delivery">
                          <Box sx={{ display: 'inline-block' }}>
                            <MetricPill value={row.payondelivery} color={C_COD} icon={<MdCurrencyRupee size={11} />} isMoney />
                          </Box>
                        </Tooltip>
                        <Tooltip title="Pay Later">
                          <Box sx={{ display: 'inline-block' }}>
                            <MetricPill value={row.Paylater} color={C_PLA} icon={<MdCurrencyRupee size={11} />} isMoney />
                          </Box>
                        </Tooltip>
                      </Stack>
                    </TableCell>

                    <TableCell align="center">
                      <Tooltip title={openRow === row.userid ? 'Collapse locations' : 'View locations'}>
                        <IconButton
                          size="small"
                          onClick={() => {
                            fetchTenantSummary(row.userid);
                            setOpenRow(openRow === row.userid ? null : row.userid);
                          }}
                          sx={{
                            bgcolor: openRow === row.userid ? BRAND : tint(BRAND),
                            border: `1px solid ${openRow === row.userid ? BRAND : edge(BRAND)}`,
                            color: openRow === row.userid ? '#fff' : BRAND,
                            borderRadius: 999,
                            p: 0.75,
                            transition: 'all 0.18s',
                            '&:hover': {
                              bgcolor: openRow === row.userid ? BRAND : soft(BRAND),
                              borderColor: BRAND,
                              boxShadow: `0 0 0 3px ${ring(BRAND)}`
                            }
                          }}
                        >
                          {openRow === row.userid ? <MdKeyboardArrowUp size={14} /> : <MdKeyboardArrowDown size={14} />}
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>

                  {/* ===================== || Collapsible per-location summary || ===================== */}
                  {openRow === row.userid && (
                    <TableRow>
                      <TableCell colSpan={15} sx={{ p: 0, borderBottom: `1px solid ${DT.divider}`, bgcolor: DT.surfaceAlt }}>
                        <Collapse in={openRow === row.userid} timeout="auto" unmountOnExit>
                          <Box sx={{ p: { xs: 1.5, md: 2 } }}>
                            <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1.25 }}>
                              <AccentAvatar color={BRAND} size={22} selected>
                                <MdPlace size={12} />
                              </AccentAvatar>
                              <Typography variant="subtitle2" sx={{ fontWeight: 800, color: DT.textPrimary }}>
                                Locations · {row.firstname} {row.lastname}
                              </Typography>
                            </Stack>

                            <Paper
                              elevation={0}
                              sx={{
                                borderRadius: 2,
                                border: '1px solid',
                                borderColor: DT.borderSubtle,
                                overflow: 'hidden',
                                background: '#fff'
                              }}
                            >
                              <Table size="small">
                                <TableHead>
                                  <TableRow
                                    sx={{
                                      '& th': {
                                        backgroundColor: tint(BRAND),
                                        color: BRAND,
                                        fontSize: 10.5,
                                        fontWeight: 800,
                                        letterSpacing: 0.6,
                                        textTransform: 'uppercase',
                                        whiteSpace: 'nowrap',
                                        borderBottom: `1px solid ${edge(BRAND)}`,
                                        py: 0.75
                                      }
                                    }}
                                  >
                                    <TableCell align="center">#</TableCell>
                                    <TableCell>Location</TableCell>
                                    <TableCell align="center">All</TableCell>
                                    <TableCell align="center">Pending</TableCell>
                                    <TableCell align="center">Completed</TableCell>
                                    <TableCell align="center">Cancelled</TableCell>
                                    <TableCell align="center">Kms</TableCell>
                                    <TableCell align="center">COD / PLA</TableCell>
                                  </TableRow>
                                </TableHead>
                                <TableBody>
                                  {tenantData && tenantData.length > 0 ? (
                                    tenantData.map((subrow, sridx) => (
                                      <TableRow
                                        key={`${subrow.locationid}-${sridx}`}
                                        sx={{
                                          '& td': { borderBottom: `1px solid ${DT.divider}`, py: 0.5, px: 1 },
                                          '&:hover': { backgroundColor: tint(BRAND), boxShadow: `inset 3px 0 0 ${BRAND}` }
                                        }}
                                      >
                                        <TableCell align="center">
                                          <Typography sx={{ fontWeight: 700, color: DT.textSecondary, fontSize: 12 }}>
                                            {sridx + 1}
                                          </Typography>
                                        </TableCell>
                                        <TableCell>
                                          <Stack>
                                            <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                                              {subrow.locationname}
                                            </Typography>
                                            <Typography variant="caption" sx={{ color: DT.textMuted, fontSize: 10 }}>
                                              Id : {subrow.locationid}
                                            </Typography>
                                          </Stack>
                                        </TableCell>
                                        <TableCell align="center">
                                          <MetricPill value={subrow.totalorders} color={BRAND} icon={<MdInventory2 size={10} />} />
                                        </TableCell>
                                        <TableCell align="center">
                                          <MetricPill value={subrow.deliveriespending} color={C_PENDING} icon={<MdHourglassEmpty size={10} />} />
                                        </TableCell>
                                        <TableCell align="center">
                                          <MetricPill value={subrow.deliveriescompleted} color={C_DELIVERED} icon={<MdCheckCircle size={10} />} />
                                        </TableCell>
                                        <TableCell align="center">
                                          <MetricPill value={subrow.deliveriescancelled} color={C_CANCELLED} icon={<MdCancel size={10} />} />
                                        </TableCell>
                                        <TableCell align="center">
                                          <MetricPill
                                            value={subrow.cumulativekms ? Number(parseFloat(subrow.cumulativekms).toFixed(2)) : 0}
                                            color={C_KMS}
                                            icon={<MdStraighten size={10} />}
                                          />
                                        </TableCell>
                                        <TableCell align="center">
                                          <Stack direction="row" spacing={0.5} justifyContent="center">
                                            <Tooltip title="Pay on Delivery">
                                              <Box sx={{ display: 'inline-block' }}>
                                                <MetricPill value={subrow.payondelivery} color={C_COD} icon={<MdCurrencyRupee size={10} />} isMoney />
                                              </Box>
                                            </Tooltip>
                                            <Tooltip title="Pay Later">
                                              <Box sx={{ display: 'inline-block' }}>
                                                <MetricPill value={subrow.paylater} color={C_PLA} icon={<MdCurrencyRupee size={10} />} isMoney />
                                              </Box>
                                            </Tooltip>
                                          </Stack>
                                        </TableCell>
                                      </TableRow>
                                    ))
                                  ) : (
                                    <TableRow>
                                      <TableCell colSpan={8} sx={{ py: 3, borderBottom: 'none' }}>
                                        <Stack alignItems="center" spacing={1}>
                                          <Avatar sx={{ width: 40, height: 40, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                                            <MdPlace size={18} />
                                          </Avatar>
                                          <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 700 }}>
                                            No location data for this rider
                                          </Typography>
                                        </Stack>
                                      </TableCell>
                                    </TableRow>
                                  )}
                                </TableBody>
                              </Table>
                            </Paper>
                          </Box>
                        </Collapse>
                      </TableCell>
                    </TableRow>
                  )}
                </Fragment>
              ))}
            </TableBody>
          </Table>
        </TableContainer>

      </Paper>

      {/* ============================================= || Date Filter Dialog || ============================================= */}
      <Dialog open={open} onClose={() => setOpen(false)} PaperProps={{ sx: { borderRadius: 3 } }}>
        <Box
          sx={{
            p: 2.5,
            background: `linear-gradient(135deg, ${tint(BRAND)} 0%, ${tint(BRAND_LIGHT)} 100%)`,
            borderBottom: `1px solid ${DT.borderSubtle}`
          }}
        >
          <Stack direction="row" alignItems="center" spacing={1.5}>
            <Avatar sx={{ bgcolor: BRAND, color: '#fff', width: 40, height: 40, boxShadow: `0 6px 18px ${ring(BRAND)}` }}>
              <MdCalendarMonth size={20} />
            </Avatar>
            <Stack>
              <Typography variant="h5" sx={{ fontWeight: 800, color: DT.textPrimary }}>
                Select Date Range
              </Typography>
              <Typography variant="caption" sx={{ color: DT.textSecondary, fontWeight: 600 }}>
                Filter rider activity by a date range or preset
              </Typography>
            </Stack>
          </Stack>
        </Box>
        <DialogContent sx={{ width: '100%' }} className="datedialog">
          <DateRangePicker
            open={open}
            toggle={() => setOpen(!open)}
            id="daterange1"
            onChange={(range) => {
              if (range.label === 'All') {
                setStartdate('');
                setEnddate('');
                setDatestatus('All');
                setOpen(false);
              } else {
                setStartdate(dayjs(range.startDate).format('YYYY-MM-DD'));
                setEnddate(dayjs(range.endDate).format('YYYY-MM-DD'));
                setDatestatus(range.label || '');
              }
            }}
            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" spacing={1} sx={{ width: '100%', p: 2, borderTop: `1px solid ${DT.divider}` }}>
          <Button
            variant="outlined"
            onClick={() => setOpen(false)}
            sx={{
              borderRadius: 999,
              px: 2.5,
              borderColor: DT.borderSubtle,
              color: DT.textSecondary,
              fontWeight: 700,
              '&:hover': { borderColor: DT.textSecondary, bgcolor: DT.surfaceAlt }
            }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            onClick={() => setOpen(false)}
            sx={{
              borderRadius: 999,
              px: 3,
              bgcolor: BRAND,
              fontWeight: 700,
              boxShadow: `0 6px 18px ${ring(BRAND)}`,
              '&:hover': { bgcolor: '#4D1C61' }
            }}
          >
            Apply
          </Button>
        </Stack>
      </Dialog>
    </>
  );
}
