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

// material-ui
import {
  Autocomplete,
  Avatar,
  Box,
  Chip,
  Collapse,
  Divider,
  Grid,
  IconButton,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TextField,
  Tooltip,
  Typography,
  useMediaQuery,
  useTheme
} from '@mui/material';
import {
  MdAssignment,
  MdCalendarMonth,
  MdCancel,
  MdCheckCircle,
  MdCurrencyRupee,
  MdExpandLess,
  MdExpandMore,
  MdGroups,
  MdHourglassEmpty,
  MdLocalShipping,
  MdLocationOn,
  MdMyLocation,
  MdPerson,
  MdStraighten,
  MdStore,
  MdOutlineLocalShipping,
  MdOutlinePendingActions,
  MdOutlineCheckCircle,
  MdOutlineCurrencyRupee
} from 'react-icons/md';

import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

import { getreportlocationsummary, getreportsummary, gettenantlocations, getTenants } from 'pages/api/api';
import Loader from 'components/Loader';
import DateFilterDialog from 'components/DateFilterDialog';
import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete';
import PageHeader from 'components/nearle_components/PageHeader';
import StatCard from 'components/nearle_components/StatCard';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';
import { OpenToast } from 'components/third-party/OpenToast';

// ============================================================================
// Design tokens — shared with deliveries / ridersSummary / customers /
// tenants pages.
// ============================================================================
const DT = {
  radiusPill: 999,
  radiusCard: 14,
  shadowSoft: '0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05)',
  shadowMd: '0 1px 3px rgba(15, 23, 42, 0.06)',
  shadowPop: '0 12px 32px rgba(15, 23, 42, 0.12)',
  textPrimary: '#0f172a',
  textSecondary: '#64748b',
  textMuted: '#94a3b8',
  borderSubtle: '#e2e8f0',
  divider: '#f1f5f9',
  surface: '#ffffff',
  surfaceAlt: '#f8fafc'
};
const a = (c, suffix) => `${c}${suffix}`;
const tint = (c) => a(c, '08');
const soft = (c) => a(c, '18');
const ring = (c) => a(c, '26');
const edge = (c) => a(c, '55');

const BRAND = '#C01227';
const BRAND_LIGHT = '#D25463';

const SoftPaper = (props) => (
  <Paper
    {...props}
    sx={{
      mt: 0.75,
      borderRadius: 2,
      boxShadow: DT.shadowPop,
      border: '1px solid',
      borderColor: 'divider',
      overflow: 'hidden'
    }}
  />
);

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>
);

// Pill used in cells for km / amount metrics.
const MetricPill = ({ color, icon, label, tooltip, minWidth = 80 }) => (
  <Tooltip title={tooltip || ''} placement="top">
    <Box
      sx={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 0.5,
        px: 1,
        py: 0.375,
        borderRadius: 999,
        bgcolor: '#ffffff',
        border: `1px solid ${edge(color)}`,
        color,
        fontSize: 11,
        fontWeight: 800,
        minWidth,
        justifyContent: 'center',
        whiteSpace: 'nowrap'
      }}
    >
      {icon}
      {label}
    </Box>
  </Tooltip>
);

// Coloured numeric cell — non-zero values get a soft accent badge to draw
// the eye, preserving the legacy "red when present" affordance with the
// modern soft-pill aesthetic.
const CountCell = ({ value, color = '#ef4444', icon }) => {
  const n = Number(value) || 0;
  if (n === 0) {
    return (
      <Typography variant="caption" sx={{ color: DT.textMuted, fontWeight: 700 }}>
        0
      </Typography>
    );
  }
  return (
    <Box
      sx={{
        display: 'inline-flex',
        alignItems: 'center',
        gap: 0.5,
        px: 0.875,
        py: 0.25,
        borderRadius: 999,
        bgcolor: '#ffffff',
        border: `1px solid ${edge(color)}`,
        color,
        fontSize: 12,
        fontWeight: 800,
        minWidth: 36,
        justifyContent: 'center'
      }}
    >
      {icon}
      {n}
    </Box>
  );
};

// Pill-style filter inputs for the Tenant / Location autocompletes.
const pillFieldSx = (color) => ({
  '& .MuiOutlinedInput-root': {
    borderRadius: '10px',
    bgcolor: '#ffffff',
    fontWeight: 600,
    '& fieldset': { borderColor: '#e2e8f0', borderWidth: 1 },
    '&:hover fieldset': { borderColor: '#cbd5e1' },
    '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring(color)}` },
    '&.Mui-focused fieldset': { borderColor: '#C01227', borderWidth: 1.5 }
  }
});

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

// ============================================================================
// Orders Summary
// ============================================================================
export default function OrdersReport() {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));

  const locationRef = useRef(null);
  const tenantRef = useRef(null);

  const [appId, setAppId] = useState(0);
  const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
  const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
  const [locaName, setLocoName] = useState('All');
  const [open, setOpen] = useState(false);
  const [openRow, setOpenRow] = useState(null);
  const [datestatus, setDatestatus] = useState('Today');
  const [ridersdata, setRidersdata] = useState([]);
  const [loading, setLoading] = useState(false);
  const [locationid, setLocationid] = useState(0);
  const [tenantid, setTenantid] = useState(0);
  const [tenantValue, setTenantValue] = useState(null);
  const [locationValue, setLocationValue] = useState(null);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [, setPage] = useState(0);

  // Clear nested filters when scope widens.
  useEffect(() => {
    setTenantid(0);
    setTenantValue(null);
    setLocationid(0);
    setLocationValue(null);
    setOpenRow(null);
  }, [appId]);

  useEffect(() => {
    setLocationid(0);
    setLocationValue(null);
    setOpenRow(null);
  }, [tenantid]);

  // ==============================|| primary summary query ||============================== //
  // The api.js destructure expects [appId, tenantid, locationid, startdate, enddate]
  // — do NOT prepend a name slot without updating api.js in lockstep.
  const {
    data: rows,
    isLoading: isLoadingReports,
    isError: isErrorReports,
    error: reportsError
  } = useQuery({
    queryKey: [appId, tenantid, locationid, startdate, enddate],
    queryFn: tenantid ? getreportlocationsummary : getreportsummary
  });

  // ==============================|| tenant list ||============================== //
  const { data: tenantlist } = useQuery({
    queryKey: ['tenantlist', appId],
    queryFn: () => getTenants(appId),
    enabled: appId !== 0
  });

  // ==============================|| tenant locations ||============================== //
  const { data: locationlist } = useQuery({
    queryKey: ['gettenantlocations', tenantid],
    queryFn: () => gettenantlocations(tenantid),
    enabled: tenantid !== 0
  });

  // Defensive: backend sometimes returns null for empty results.
  const safeRows = useMemo(() => (Array.isArray(rows) ? rows : []), [rows]);

  // Client-side filter on tenant / location name.
  const filteredRows = useMemo(() => {
    if (!debouncedSearch) return safeRows;
    const q = debouncedSearch.toLowerCase().trim();
    return safeRows.filter((r) =>
      [r.tenantname, r.locationname, String(r.tenantid || ''), String(r.locationid || '')]
        .filter(Boolean)
        .some((field) => String(field).toLowerCase().includes(q))
    );
  }, [safeRows, debouncedSearch]);

  // KPIs + grand total derived directly from the loaded summary.
  const stats = useMemo(() => {
    return filteredRows.reduce(
      (acc, row) => {
        acc.totalOrders += Number(row.totalorders) || 0;
        acc.orderPend += Number(row.Orderspending) || 0;
        acc.orderComplete += Number(row.orderscompleted) || 0;
        acc.orderCancel += Number(row.orderscancelled) || 0;
        acc.deliPend += Number(row.deliveriespending) || 0;
        acc.deliComplete += Number(row.deliveriescompleted) || 0;
        acc.deliCancel += Number(row.deliveriescancelled) || 0;
        acc.collection += Number(row.collectionamt) || 0;
        acc.kms += Number(row.kms) || 0;
        acc.cumulativekms += Number(row.cumulativekms) || 0;
        acc.amount += Math.max(Number(row.charges) || 0, Number(row.deliveryamt) || 0);
        return acc;
      },
      {
        totalOrders: 0,
        orderPend: 0,
        orderComplete: 0,
        orderCancel: 0,
        deliPend: 0,
        deliComplete: 0,
        deliCancel: 0,
        collection: 0,
        kms: 0,
        cumulativekms: 0,
        amount: 0
      }
    );
  }, [filteredRows]);

  // No per-tenant or per-location rider-breakdown endpoint in the new API.
  const getuserreportsummary = async () => {
    setLoading(true);
    setRidersdata([]);
    setLoading(false);
  };

  const getriderlocationsummary = async () => {
    setLoading(true);
    setRidersdata([]);
    setLoading(false);
  };

  if (isErrorReports) console.warn('ordersSummary error:', reportsError?.message);

  const KPI_META = [
    {
      key: 'orders',
      label: 'Total Orders',
      color: BRAND,
      icon: MdOutlineLocalShipping,
      value: stats.totalOrders
    },
    {
      key: 'pending',
      label: 'Orders Pending',
      color: '#f59e0b',
      icon: MdOutlinePendingActions,
      value: stats.orderPend
    },
    {
      key: 'completed',
      label: 'Orders Completed',
      color: '#10b981',
      icon: MdOutlineCheckCircle,
      value: stats.orderComplete
    },
    {
      key: 'amount',
      label: 'Total Amount',
      color: '#0ea5e9',
      icon: MdOutlineCurrencyRupee,
      value: formatNumberToRupees(stats.amount)
    }
  ];

  const isLocationGroup = Boolean(tenantid);

  return (
    <>
      {(loading || isLoadingReports) && <Loader />}

      {/* ============================================= || Header || ============================================= */}
      <PageHeader
        title="Orders Summary"
        subtitle={`Live · ${locaName || 'All Zones'} · ${datestatus}`}
        live
        action={
          <LocationAutocomplete
            ref={locationRef}
            locaName={locaName}
            setAppId={setAppId}
            setLocoName={setLocoName}
            setPage={setPage}
            pill
            accentColor={BRAND}
            icon={<MdMyLocation size={14} />}
            placeholder="Select Zone"
            paperComponent={SoftPaper}
            sx={{ width: { xs: '100%', sm: 280 }, zIndex: 100 }}
          />
        }
      />

      {/* ============================================= || KPI Cards || ============================================= */}
      <Grid container spacing={{ xs: 2, md: 2.5 }} sx={{ mb: { xs: 1.5, md: 2 } }}>
        {KPI_META.map((item) => {
          const Icon = item.icon;
          return (
            <Grid item key={item.key} xs={6} sm={6} md={3}>
              <StatCard
                title={item.label}
                value={item.value ?? 0}
                icon={<Icon size={20} />}
                color={item.color}
                loading={isLoadingReports}
              />
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Filter bar || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          mt: { xs: 1.5, md: 2 },
          p: { xs: 1, md: 1.5 },
          borderTopLeftRadius: DT.radiusCard / 8,
          borderTopRightRadius: DT.radiusCard / 8,
          borderBottomLeftRadius: 0,
          borderBottomRightRadius: 0,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          borderBottom: 0,
          background: '#fff'
        }}
      >
        <Stack
          direction={{ xs: 'column', md: 'row' }}
          alignItems={{ xs: 'stretch', md: 'center' }}
          justifyContent="space-between"
          spacing={1.25}
        >
          <Stack direction="row" alignItems="center" spacing={1.25} flexWrap="wrap">
            <Tooltip title="Date Filter" placement="top">
              <Box
                onClick={() => setOpen(true)}
                sx={{
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 0.75,
                  px: 1.25,
                  py: 0.75,
                  borderRadius: 999,
                  cursor: 'pointer',
                  bgcolor: tint('#f59e0b'),
                  border: `1.5px solid ${edge('#f59e0b')}`,
                  color: '#f59e0b',
                  fontWeight: 800,
                  fontSize: 12,
                  transition: 'all 0.18s',
                  '&:hover': { borderColor: '#f59e0b', boxShadow: `0 0 0 3px ${ring('#f59e0b')}` }
                }}
              >
                <MdCalendarMonth size={14} />
                Orders · {datestatus} · {dayjs(startdate).format('DD/MM/YY')} – {dayjs(enddate).format('DD/MM/YY')}
              </Box>
            </Tooltip>

            <Autocomplete
              options={tenantlist || []}
              value={tenantValue}
              getOptionLabel={(option) => option?.tenantname || option?.label || ''}
              isOptionEqualToValue={(opt, val) => opt?.tenantid === val?.tenantid}
              PaperComponent={SoftPaper}
              sx={{ minWidth: { xs: '100%', sm: 220 }, ...pillFieldSx(BRAND) }}
              onOpen={(event) => {
                if (!appId) {
                  event.preventDefault();
                  OpenToast('Please select a Zone first!', 'warning', 3000);
                  setTimeout(() => locationRef.current?.focus(), 0);
                }
              }}
              onChange={(e, val, reason) => {
                if (reason === 'clear' || !val) {
                  setTenantid(0);
                  setTenantValue(null);
                  setLocationid(0);
                  setLocationValue(null);
                } else {
                  setTenantid(val?.tenantid || 0);
                  setTenantValue(val);
                  setLocationid(val?.locationid || 0);
                  setLocationValue(null);
                }
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  inputRef={tenantRef}
                  placeholder="Select Tenant"
                  size="small"
                  InputProps={{
                    ...params.InputProps,
                    startAdornment: (
                      <Stack direction="row" alignItems="center" spacing={0.75} sx={{ pl: 0.5 }}>
                        <AccentAvatar color={BRAND} size={24} selected={Boolean(tenantValue)}>
                          <MdStore size={14} />
                        </AccentAvatar>
                        {params.InputProps.startAdornment}
                      </Stack>
                    )
                  }}
                />
              )}
            />

            <Autocomplete
              options={locationlist || []}
              value={locationValue}
              getOptionLabel={(option) =>
                option?.locationname ? `${option.locationname}${option.suburb ? ` (${option.suburb})` : ''}` : ''
              }
              isOptionEqualToValue={(opt, val) => opt?.locationid === val?.locationid}
              PaperComponent={SoftPaper}
              sx={{ minWidth: { xs: '100%', sm: 220 }, ...pillFieldSx('#0ea5e9') }}
              onOpen={(event) => {
                if (!appId && !tenantid) {
                  event.preventDefault();
                  OpenToast('Please select Zone and Tenant first!', 'warning', 3000);
                  setTimeout(() => locationRef.current?.focus(), 0);
                } else if (!tenantid) {
                  event.preventDefault();
                  OpenToast('Please select a Tenant first!', 'warning', 3000);
                  setTimeout(() => tenantRef.current?.focus(), 0);
                }
              }}
              onChange={(e, val, reason) => {
                if (reason === 'clear' || !val) {
                  setLocationid(0);
                  setLocationValue(null);
                } else {
                  setLocationid(val?.locationid || 0);
                  setLocationValue(val);
                }
              }}
              renderInput={(params) => (
                <TextField
                  {...params}
                  placeholder="Select Location"
                  size="small"
                  InputProps={{
                    ...params.InputProps,
                    startAdornment: (
                      <Stack direction="row" alignItems="center" spacing={0.75} sx={{ pl: 0.5 }}>
                        <AccentAvatar color="#0ea5e9" size={24} selected={Boolean(locationValue)}>
                          <MdLocationOn size={14} />
                        </AccentAvatar>
                        {params.InputProps.startAdornment}
                      </Stack>
                    )
                  }}
                />
              )}
            />
          </Stack>

          <Box sx={{ width: { xs: '100%', md: 280, lg: 320 }, flex: { xs: '1 1 100%', md: '0 0 auto' } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={setDebouncedSearch}
              placeholder={`Search ${isLocationGroup ? 'locations' : 'tenants'} (ctrl+k)`}
              sx={{
                m: 0,
                width: '100%',
                borderRadius: 999,
                bgcolor: '#ffffff',
                '& fieldset': { borderColor: '#e2e8f0', borderWidth: 1 },
                '&:hover fieldset': { borderColor: '#cbd5e1' },
                '&.Mui-focused fieldset': { borderColor: '#C01227', borderWidth: 1.5 },
                '&.Mui-focused': { boxShadow: `0 0 0 3px ${ring(BRAND)}` }
              }}
            />
          </Box>
        </Stack>
      </Paper>

      {/* ============================================= || Table || ============================================= */}
      <Paper
        elevation={0}
        sx={{
          borderTopLeftRadius: 0,
          borderTopRightRadius: 0,
          borderBottomLeftRadius: DT.radiusCard / 8,
          borderBottomRightRadius: DT.radiusCard / 8,
          border: '1px solid',
          borderColor: DT.borderSubtle,
          overflow: 'hidden',
          background: '#fff'
        }}
      >
        {isMobile ? (
          <>
            {isLoadingReports && (
              <MobileCardList>
                {[0, 1, 2, 3].map((i) => (
                  <MobileCard key={i} accent={DT.borderSubtle}>
                    <Box sx={{ height: 96 }} />
                  </MobileCard>
                ))}
              </MobileCardList>
            )}

            {!isLoadingReports && filteredRows.length === 0 && (
              <Stack alignItems="center" spacing={1.5} sx={{ py: 6, px: 2 }}>
                <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                  <MdAssignment size={28} />
                </Avatar>
                <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                  No {isLocationGroup ? 'locations' : 'tenants'} to show
                </Typography>
                <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center', maxWidth: 360 }}>
                  {debouncedSearch
                    ? 'Try a different keyword.'
                    : isErrorReports
                      ? 'Something went wrong fetching the summary. Try a different filter.'
                      : 'Pick a zone, tenant, or date range to load the summary.'}
                </Typography>
              </Stack>
            )}

            {!isLoadingReports && filteredRows.length > 0 && (
              <MobileCardList>
                {filteredRows.map((row, index) => {
                  const rowKey = isLocationGroup ? row.locationname : row.tenantname;
                  const isOpen = openRow === rowKey;
                  const amount = Math.max(Number(row.charges) || 0, Number(row.deliveryamt) || 0);
                  const rowAccent = isLocationGroup ? '#0ea5e9' : BRAND;

                  return (
                    <MobileCard
                      key={`${rowKey}-${index}`}
                      accent={rowAccent}
                      selected={isOpen}
                      header={
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <AccentAvatar color={rowAccent} size={36}>
                            {isLocationGroup ? <MdLocationOn size={18} /> : <MdStore size={18} />}
                          </AccentAvatar>
                          <Stack sx={{ minWidth: 0, flex: 1 }}>
                            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                              {(isLocationGroup ? row.locationname : row.tenantname) || '—'}
                            </Typography>
                            <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                              ID #{isLocationGroup ? row.locationid : row.tenantid}
                            </Typography>
                          </Stack>
                          <Tooltip title={isOpen ? 'Hide rider breakdown' : 'View rider breakdown'} placement="top">
                            <IconButton
                              size="small"
                              onClick={() => {
                                const isOpening = !isOpen;
                                setOpenRow(isOpening ? rowKey : null);
                                if (!isOpening) return;
                                setRidersdata([]);
                                if (isLocationGroup) {
                                  getriderlocationsummary(row.locationid);
                                } else {
                                  getuserreportsummary(row.tenantid);
                                }
                              }}
                              sx={{
                                flexShrink: 0,
                                bgcolor: isOpen ? BRAND : soft(BRAND),
                                color: isOpen ? '#fff' : BRAND,
                                border: `1px solid ${edge(BRAND)}`,
                                '&:hover': { bgcolor: BRAND, color: '#fff' }
                              }}
                            >
                              {isOpen ? <MdExpandLess size={16} /> : <MdExpandMore size={16} />}
                            </IconButton>
                          </Tooltip>
                        </Stack>
                      }
                    >
                      <MobileFieldGrid columns={3}>
                        <MobileField label="All" align="center">
                          <CountCell value={row.totalorders} color={BRAND} icon={<MdLocalShipping size={11} />} />
                        </MobileField>
                        <MobileField label="Ord Pending" align="center">
                          <CountCell value={row.Orderspending} color="#f59e0b" icon={<MdHourglassEmpty size={11} />} />
                        </MobileField>
                        <MobileField label="Ord Cancelled" align="center">
                          <CountCell value={row.orderscancelled} color="#ef4444" icon={<MdCancel size={11} />} />
                        </MobileField>
                        <MobileField label="Ord Completed" align="center">
                          <CountCell value={row.orderscompleted} color="#10b981" icon={<MdCheckCircle size={11} />} />
                        </MobileField>
                        <MobileField label="Del Pending" align="center">
                          <CountCell value={row.deliveriespending} color="#f59e0b" icon={<MdHourglassEmpty size={11} />} />
                        </MobileField>
                        <MobileField label="Del Cancelled" align="center">
                          <CountCell value={row.deliveriescancelled} color="#ef4444" icon={<MdCancel size={11} />} />
                        </MobileField>
                        <MobileField label="Del Completed" align="center">
                          <CountCell value={row.deliveriescompleted} color="#10b981" icon={<MdCheckCircle size={11} />} />
                        </MobileField>
                        <MobileField label="Collection" align="center">
                          <MetricPill
                            color="#f59e0b"
                            icon={<MdCurrencyRupee size={11} />}
                            label={Number(row.collectionamt || 0).toFixed(2)}
                            tooltip="Collection Amount"
                            minWidth={90}
                          />
                        </MobileField>
                        <MobileField label="Amount" align="center">
                          <MetricPill
                            color={BRAND}
                            icon={<MdCurrencyRupee size={11} />}
                            label={formatNumberToRupees(amount).replace('₹', '').trim()}
                            tooltip="Total Amount"
                            minWidth={100}
                          />
                        </MobileField>
                        <MobileField label="KMS" align="center">
                          <MetricPill
                            color="#ef4444"
                            icon={<MdStraighten size={11} />}
                            label={`${Number(row.kms || 0).toFixed(2)} km`}
                            tooltip="KMS"
                          />
                        </MobileField>
                        <MobileField label="Actual KMS" align="center">
                          <MetricPill
                            color="#10b981"
                            icon={<MdStraighten size={11} />}
                            label={`${Number(row.cumulativekms || 0).toFixed(2)} km`}
                            tooltip="Actual KMS"
                          />
                        </MobileField>
                      </MobileFieldGrid>

                      {/* Collapsible rider breakdown — mobile */}
                      <Collapse in={isOpen} timeout="auto" unmountOnExit>
                        <Box sx={{ mt: 1.5 }}>
                          <Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1 }}>
                            <AccentAvatar color={BRAND} size={24} selected>
                              <MdGroups size={12} />
                            </AccentAvatar>
                            <Typography
                              variant="caption"
                              sx={{ fontWeight: 800, color: DT.textPrimary, letterSpacing: 0.6, textTransform: 'uppercase' }}
                            >
                              Rider Breakdown
                            </Typography>
                          </Stack>

                          {!loading && (!ridersdata || ridersdata.length === 0) ? (
                            <Typography variant="caption" sx={{ color: DT.textMuted, display: 'block', py: 1, textAlign: 'center' }}>
                              No rider activity for this row.
                            </Typography>
                          ) : (
                            <Stack spacing={1}>
                              {ridersdata.map((sub, sidx) => {
                                const subAmount = Math.max(Number(sub.charges) || 0, Number(sub.deliveryamt) || 0);
                                return (
                                  <MobileCard key={`${sub.userid}-${sidx}`} accent={BRAND}>
                                    <Stack direction="row" alignItems="center" spacing={0.75}>
                                      <AccentAvatar color={BRAND} size={28}>
                                        <MdPerson size={14} />
                                      </AccentAvatar>
                                      <Stack sx={{ minWidth: 0 }}>
                                        <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                                          {`${sub.firstname || ''} ${sub.lastname || ''}`.trim() || '—'}
                                        </Typography>
                                        <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                                          {sub.ridercontact || `ID #${sub.userid}`}
                                        </Typography>
                                      </Stack>
                                    </Stack>
                                    <MobileFieldGrid columns={3}>
                                      <MobileField label="Orders" align="center">
                                        <CountCell value={sub.orderscreated} color={BRAND} icon={<MdLocalShipping size={10} />} />
                                      </MobileField>
                                      <MobileField label="Deliveries" align="center">
                                        <CountCell value={sub.totalorders} color="#0ea5e9" icon={<MdLocalShipping size={10} />} />
                                      </MobileField>
                                      <MobileField label="Pending" align="center">
                                        <CountCell value={sub.deliveriespending} color="#f59e0b" icon={<MdHourglassEmpty size={10} />} />
                                      </MobileField>
                                      <MobileField label="Cancelled" align="center">
                                        <CountCell value={sub.deliveriescancelled} color="#ef4444" icon={<MdCancel size={10} />} />
                                      </MobileField>
                                      <MobileField label="Completed" align="center">
                                        <CountCell value={sub.deliveriescompleted} color="#10b981" icon={<MdCheckCircle size={10} />} />
                                      </MobileField>
                                      <MobileField label="Collection" align="center">
                                        <MetricPill
                                          color="#f59e0b"
                                          icon={<MdCurrencyRupee size={10} />}
                                          label={Number(sub.collectionamt || 0).toFixed(2)}
                                          tooltip="Collection"
                                          minWidth={80}
                                        />
                                      </MobileField>
                                      <MobileField label="KMS" align="center">
                                        <MetricPill
                                          color="#ef4444"
                                          icon={<MdStraighten size={10} />}
                                          label={`${Number(sub.kms || 0).toFixed(2)} km`}
                                          tooltip="KMS"
                                        />
                                      </MobileField>
                                      <MobileField label="Actual KMS" align="center">
                                        <MetricPill
                                          color="#10b981"
                                          icon={<MdStraighten size={10} />}
                                          label={`${Number(sub.cumulativekms || 0).toFixed(2)} km`}
                                          tooltip="Actual KMS"
                                        />
                                      </MobileField>
                                      <MobileField label="Amount" align="center">
                                        <MetricPill
                                          color={BRAND}
                                          icon={<MdCurrencyRupee size={10} />}
                                          label={formatNumberToRupees(subAmount).replace('₹', '').trim()}
                                          tooltip="Total Amount"
                                          minWidth={100}
                                        />
                                      </MobileField>
                                    </MobileFieldGrid>
                                  </MobileCard>
                                );
                              })}
                            </Stack>
                          )}
                        </Box>
                      </Collapse>
                    </MobileCard>
                  );
                })}
              </MobileCardList>
            )}
          </>
        ) : (
        <TableContainer
          sx={{
            maxHeight: { xs: 'calc(100vh - 280px)', md: 'calc(100vh - 240px)' },
            '&::-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 sx={{ minWidth: { xs: 1080, md: 1200 } }}>
            <TableHead>
              <TableRow
                sx={{
                  '& th': {
                    backgroundColor: DT.surfaceAlt,
                    color: DT.textSecondary,
                    fontSize: { xs: 10, md: 11 },
                    fontWeight: 800,
                    letterSpacing: 0.6,
                    textTransform: 'uppercase',
                    whiteSpace: 'nowrap',
                    borderBottom: `1px solid ${DT.borderSubtle}`,
                    py: { xs: 1, md: 1.25 },
                    px: { xs: 1, md: 1.5 }
                  }
                }}
              >
                <TableCell rowSpan={2}>#</TableCell>
                <TableCell rowSpan={2}>{isLocationGroup ? 'Location' : 'Tenant'}</TableCell>
                <TableCell align="center" rowSpan={2}>
                  All
                </TableCell>
                <TableCell align="center" colSpan={3} sx={{ bgcolor: `${tint('#ef4444')} !important`, color: '#ef4444 !important' }}>
                  Orders
                </TableCell>
                <TableCell align="center" colSpan={3} sx={{ bgcolor: `${tint('#10b981')} !important`, color: '#10b981 !important' }}>
                  Deliveries
                </TableCell>
                <TableCell align="center" rowSpan={2}>
                  Collection
                </TableCell>
                <TableCell align="center" rowSpan={2}>
                  KMS / Actual
                </TableCell>
                <TableCell align="center" rowSpan={2}>
                  Amount
                </TableCell>
                <TableCell align="right" rowSpan={2}>
                  Action
                </TableCell>
              </TableRow>
              <TableRow
                sx={{
                  '& th': {
                    backgroundColor: DT.surfaceAlt,
                    color: DT.textSecondary,
                    fontSize: { xs: 10, md: 10.5 },
                    fontWeight: 800,
                    letterSpacing: 0.6,
                    textTransform: 'uppercase',
                    whiteSpace: 'nowrap',
                    borderBottom: `1px solid ${DT.borderSubtle}`,
                    py: { xs: 0.75, md: 1 },
                    px: { xs: 1, md: 1.5 }
                  }
                }}
              >
                <TableCell align="center" sx={{ bgcolor: `${tint('#ef4444')} !important`, color: '#f59e0b !important' }}>
                  Pending
                </TableCell>
                <TableCell align="center" sx={{ bgcolor: `${tint('#ef4444')} !important`, color: '#ef4444 !important' }}>
                  Cancelled
                </TableCell>
                <TableCell align="center" sx={{ bgcolor: `${tint('#ef4444')} !important`, color: '#10b981 !important' }}>
                  Completed
                </TableCell>
                <TableCell align="center" sx={{ bgcolor: `${tint('#10b981')} !important`, color: '#f59e0b !important' }}>
                  Pending
                </TableCell>
                <TableCell align="center" sx={{ bgcolor: `${tint('#10b981')} !important`, color: '#ef4444 !important' }}>
                  Cancelled
                </TableCell>
                <TableCell align="center" sx={{ bgcolor: `${tint('#10b981')} !important`, color: '#10b981 !important' }}>
                  Completed
                </TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {isLoadingReports && <OrdersTableSkeleton col={9} />}

              {!isLoadingReports && filteredRows.length === 0 && (
                <TableRow>
                  <TableCell colSpan={13} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                        <MdAssignment size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                        No {isLocationGroup ? 'locations' : 'tenants'} to show
                      </Typography>
                      <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center', maxWidth: 360 }}>
                        {debouncedSearch
                          ? 'Try a different keyword.'
                          : isErrorReports
                            ? 'Something went wrong fetching the summary. Try a different filter.'
                            : 'Pick a zone, tenant, or date range to load the summary.'}
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              )}

              {filteredRows.map((row, index) => {
                const rowKey = isLocationGroup ? row.locationname : row.tenantname;
                const isOpen = openRow === rowKey;
                const amount = Math.max(Number(row.charges) || 0, Number(row.deliveryamt) || 0);

                return (
                  <React.Fragment key={`${rowKey}-${index}`}>
                    <TableRow
                      sx={{
                        transition: 'background-color 0.15s',
                        '& td': {
                          borderBottom: isOpen ? 'none' : `1px solid ${DT.divider}`,
                          py: { xs: 1, md: 1.25 },
                          px: { xs: 1, md: 1.5 }
                        },
                        '&:hover': { backgroundColor: isOpen ? '#fff' : DT.surfaceAlt },
                        bgcolor: isOpen ? tint(BRAND) : 'transparent'
                      }}
                    >
                      <TableCell>
                        <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textMuted }}>
                          {String(index + 1).padStart(2, '0')}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <AccentAvatar color={isLocationGroup ? '#0ea5e9' : BRAND} size={36}>
                            {isLocationGroup ? <MdLocationOn size={18} /> : <MdStore size={18} />}
                          </AccentAvatar>
                          <Stack>
                            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                              {(isLocationGroup ? row.locationname : row.tenantname) || '—'}
                            </Typography>
                            <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                              ID #{isLocationGroup ? row.locationid : row.tenantid}
                            </Typography>
                          </Stack>
                        </Stack>
                      </TableCell>

                      <TableCell align="center">
                        <CountCell value={row.totalorders} color={BRAND} icon={<MdLocalShipping size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.Orderspending} color="#f59e0b" icon={<MdHourglassEmpty size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.orderscancelled} color="#ef4444" icon={<MdCancel size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.orderscompleted} color="#10b981" icon={<MdCheckCircle size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.deliveriespending} color="#f59e0b" icon={<MdHourglassEmpty size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.deliveriescancelled} color="#ef4444" icon={<MdCancel size={11} />} />
                      </TableCell>
                      <TableCell align="center">
                        <CountCell value={row.deliveriescompleted} color="#10b981" icon={<MdCheckCircle size={11} />} />
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill
                          color="#f59e0b"
                          icon={<MdCurrencyRupee size={11} />}
                          label={Number(row.collectionamt || 0).toFixed(2)}
                          tooltip="Collection Amount"
                          minWidth={90}
                        />
                      </TableCell>

                      <TableCell align="center">
                        <Stack direction="column" spacing={0.5} alignItems="center">
                          <MetricPill
                            color="#ef4444"
                            icon={<MdStraighten size={11} />}
                            label={`${Number(row.kms || 0).toFixed(2)} km`}
                            tooltip="KMS"
                          />
                          <MetricPill
                            color="#10b981"
                            icon={<MdStraighten size={11} />}
                            label={`${Number(row.cumulativekms || 0).toFixed(2)} km`}
                            tooltip="Actual KMS"
                          />
                        </Stack>
                      </TableCell>

                      <TableCell align="center">
                        <MetricPill
                          color={BRAND}
                          icon={<MdCurrencyRupee size={11} />}
                          label={formatNumberToRupees(amount).replace('₹', '').trim()}
                          tooltip="Total Amount"
                          minWidth={100}
                        />
                      </TableCell>

                      <TableCell align="right">
                        <Tooltip title={isOpen ? 'Hide rider breakdown' : 'View rider breakdown'} placement="top">
                          <IconButton
                            size="small"
                            onClick={() => {
                              const isOpening = !isOpen;
                              setOpenRow(isOpening ? rowKey : null);
                              if (!isOpening) return;
                              setRidersdata([]);
                              if (isLocationGroup) {
                                getriderlocationsummary(row.locationid);
                              } else {
                                getuserreportsummary(row.tenantid);
                              }
                            }}
                            sx={{
                              bgcolor: isOpen ? BRAND : soft(BRAND),
                              color: isOpen ? '#fff' : BRAND,
                              border: `1px solid ${edge(BRAND)}`,
                              '&:hover': { bgcolor: BRAND, color: '#fff' }
                            }}
                          >
                            {isOpen ? <MdExpandLess size={16} /> : <MdExpandMore size={16} />}
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>

                    {/* ============================================= || Collapsible rider breakdown || ============================================= */}
                    {isOpen && (
                      <TableRow>
                        <TableCell
                          colSpan={13}
                          sx={{
                            p: 0,
                            borderBottom: `1px solid ${DT.divider}`,
                            bgcolor: tint(BRAND)
                          }}
                        >
                          <Collapse in={isOpen} timeout="auto" unmountOnExit>
                            <Box sx={{ p: { xs: 1, md: 2 } }}>
                              <Paper
                                elevation={0}
                                sx={{
                                  borderRadius: DT.radiusCard / 8,
                                  border: '1px solid',
                                  borderColor: DT.borderSubtle,
                                  overflow: 'hidden',
                                  boxShadow: DT.shadowSoft
                                }}
                              >
                                <Stack
                                  direction="row"
                                  alignItems="center"
                                  spacing={1}
                                  sx={{
                                    px: 2,
                                    py: 1.25,
                                    background: '#ffffff',
                                    borderBottom: `1px solid ${DT.borderSubtle}`
                                  }}
                                >
                                  <AccentAvatar color={BRAND} size={28} selected>
                                    <MdGroups size={14} />
                                  </AccentAvatar>
                                  <Typography
                                    variant="caption"
                                    sx={{
                                      fontWeight: 700,
                                      color: DT.textPrimary,
                                      letterSpacing: 0.6,
                                      textTransform: 'uppercase'
                                    }}
                                  >
                                    Rider Breakdown · {isLocationGroup ? row.locationname : row.tenantname}
                                  </Typography>
                                </Stack>

                                <Table size="small">
                                  <TableHead>
                                    <TableRow
                                      sx={{
                                        '& th': {
                                          backgroundColor: DT.surfaceAlt,
                                          color: DT.textSecondary,
                                          fontSize: 10,
                                          fontWeight: 800,
                                          letterSpacing: 0.6,
                                          textTransform: 'uppercase',
                                          whiteSpace: 'nowrap',
                                          borderBottom: `1px solid ${DT.borderSubtle}`,
                                          py: 1,
                                          px: 1.5
                                        }
                                      }}
                                    >
                                      <TableCell>#</TableCell>
                                      <TableCell>Rider</TableCell>
                                      <TableCell align="center">Orders</TableCell>
                                      <TableCell align="center">Deliveries</TableCell>
                                      <TableCell align="center">Pending</TableCell>
                                      <TableCell align="center">Cancelled</TableCell>
                                      <TableCell align="center">Completed</TableCell>
                                      <TableCell align="center">Collection</TableCell>
                                      <TableCell align="center">KMS / Actual</TableCell>
                                      <TableCell align="center">Amount</TableCell>
                                    </TableRow>
                                  </TableHead>
                                  <TableBody>
                                    {loading && <OrdersTableSkeleton col={6} />}
                                    {!loading && (!ridersdata || ridersdata.length === 0) ? (
                                      <TableRow>
                                        <TableCell colSpan={10} sx={{ py: 3 }}>
                                          <Typography variant="caption" sx={{ color: DT.textMuted, textAlign: 'center', display: 'block' }}>
                                            No rider activity for this row.
                                          </Typography>
                                        </TableCell>
                                      </TableRow>
                                    ) : (
                                      ridersdata.map((sub, sidx) => {
                                        const subAmount = Math.max(Number(sub.charges) || 0, Number(sub.deliveryamt) || 0);
                                        return (
                                          <TableRow
                                            key={`${sub.userid}-${sidx}`}
                                            sx={{
                                              '& td': {
                                                borderBottom: `1px solid ${DT.divider}`,
                                                py: 1,
                                                px: 1.5
                                              },
                                              '&:hover': { backgroundColor: DT.surfaceAlt }
                                            }}
                                          >
                                            <TableCell>
                                              <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textMuted }}>
                                                {String(sidx + 1).padStart(2, '0')}
                                              </Typography>
                                            </TableCell>
                                            <TableCell>
                                              <Stack direction="row" alignItems="center" spacing={0.75}>
                                                <AccentAvatar color={BRAND} size={28}>
                                                  <MdPerson size={14} />
                                                </AccentAvatar>
                                                <Stack>
                                                  <Typography
                                                    variant="subtitle2"
                                                    sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}
                                                  >
                                                    {`${sub.firstname || ''} ${sub.lastname || ''}`.trim() || '—'}
                                                  </Typography>
                                                  <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                                                    {sub.ridercontact || `ID #${sub.userid}`}
                                                  </Typography>
                                                </Stack>
                                              </Stack>
                                            </TableCell>
                                            <TableCell align="center">
                                              <CountCell value={sub.orderscreated} color={BRAND} icon={<MdLocalShipping size={10} />} />
                                            </TableCell>
                                            <TableCell align="center">
                                              <CountCell value={sub.totalorders} color="#0ea5e9" icon={<MdLocalShipping size={10} />} />
                                            </TableCell>
                                            <TableCell align="center">
                                              <CountCell
                                                value={sub.deliveriespending}
                                                color="#f59e0b"
                                                icon={<MdHourglassEmpty size={10} />}
                                              />
                                            </TableCell>
                                            <TableCell align="center">
                                              <CountCell value={sub.deliveriescancelled} color="#ef4444" icon={<MdCancel size={10} />} />
                                            </TableCell>
                                            <TableCell align="center">
                                              <CountCell
                                                value={sub.deliveriescompleted}
                                                color="#10b981"
                                                icon={<MdCheckCircle size={10} />}
                                              />
                                            </TableCell>
                                            <TableCell align="center">
                                              <MetricPill
                                                color="#f59e0b"
                                                icon={<MdCurrencyRupee size={10} />}
                                                label={Number(sub.collectionamt || 0).toFixed(2)}
                                                tooltip="Collection"
                                                minWidth={80}
                                              />
                                            </TableCell>
                                            <TableCell align="center">
                                              <Stack direction="column" spacing={0.5} alignItems="center">
                                                <MetricPill
                                                  color="#ef4444"
                                                  icon={<MdStraighten size={10} />}
                                                  label={`${Number(sub.kms || 0).toFixed(2)} km`}
                                                  tooltip="KMS"
                                                />
                                                <MetricPill
                                                  color="#10b981"
                                                  icon={<MdStraighten size={10} />}
                                                  label={`${Number(sub.cumulativekms || 0).toFixed(2)} km`}
                                                  tooltip="Actual KMS"
                                                />
                                              </Stack>
                                            </TableCell>
                                            <TableCell align="center">
                                              <MetricPill
                                                color={BRAND}
                                                icon={<MdCurrencyRupee size={10} />}
                                                label={formatNumberToRupees(subAmount).replace('₹', '').trim()}
                                                tooltip="Total Amount"
                                                minWidth={100}
                                              />
                                            </TableCell>
                                          </TableRow>
                                        );
                                      })
                                    )}
                                  </TableBody>
                                </Table>
                              </Paper>
                            </Box>
                          </Collapse>
                        </TableCell>
                      </TableRow>
                    )}
                  </React.Fragment>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
        )}

        {/* ============================================= || Total Bar || ============================================= */}
        {filteredRows.length > 0 && (
          <>
            <Divider />
            <Stack
              direction="row"
              alignItems="center"
              justifyContent="space-between"
              spacing={1.5}
              flexWrap="wrap"
              sx={{
                px: 2,
                py: 1.5,
                background: '#ffffff'
              }}
            >
              <Stack direction="row" alignItems="center" spacing={1} flexWrap="wrap">
                <Typography
                  variant="caption"
                  sx={{ fontWeight: 800, color: DT.textSecondary, letterSpacing: 0.6, textTransform: 'uppercase' }}
                >
                  Grand Total
                </Typography>
                <Chip
                  size="small"
                  label={`${stats.totalOrders} orders`}
                  sx={{ fontWeight: 700, bgcolor: soft(BRAND), color: BRAND, border: `1px solid ${edge(BRAND)}` }}
                />
                <Chip
                  size="small"
                  label={`${stats.deliComplete} delivered`}
                  sx={{ fontWeight: 700, bgcolor: soft('#10b981'), color: '#10b981', border: `1px solid ${edge('#10b981')}` }}
                />
                <Chip
                  size="small"
                  label={`${stats.deliPend} pending`}
                  sx={{ fontWeight: 700, bgcolor: soft('#f59e0b'), color: '#f59e0b', border: `1px solid ${edge('#f59e0b')}` }}
                />
              </Stack>
              <Chip
                label={formatNumberToRupees(stats.amount)}
                sx={{
                  fontWeight: 800,
                  fontSize: 13,
                  color: '#fff',
                  background: `linear-gradient(135deg, ${BRAND} 0%, ${BRAND_LIGHT} 100%)`,
                  boxShadow: `0 6px 16px ${ring(BRAND)}`
                }}
              />
            </Stack>
          </>
        )}
      </Paper>

      {/* ============================================= || Date Filter Dialog || ============================================= */}
      <DateFilterDialog
        open={open}
        onClose={() => setOpen(false)}
        onSelect={(range) => {
          setStartdate(range.startDate);
          setEnddate(range.endDate);
          setDatestatus(range.label);
        }}
      />
    </>
  );
}
