import React, { useState, useMemo } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);

import {
  Avatar,
  Box,
  Divider,
  Grid,
  IconButton,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Tooltip,
  Typography,
  useMediaQuery
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import {
  MdReceiptLong,
  MdDashboard,
  MdHourglassEmpty,
  MdReportProblem,
  MdCheckCircle,
  MdGroups,
  MdEventNote,
  MdCurrencyRupee,
  MdVisibility,
  MdInventory2,
  MdOutlinePendingActions,
  MdOutlineCheckCircle
} from 'react-icons/md';

import { fetchinvoiceinsight, fetchdeliverylist } from 'pages/api/api';
import Loader from 'components/Loader';
import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar';
import PageHeader from 'components/nearle_components/PageHeader';
import StatCard from 'components/nearle_components/StatCard';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';
import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard';

// ============================================================================
// Design tokens — shared with deliveries / tenants / customers / pricing /
// orders-details / riders-summary 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 = '#662582';

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

// Bill status → tab visual meta (semantic colours; brand purple reserved for "All").
const STATUS_META = {
  0: { key: 'all',     label: 'All',     color: BRAND,     icon: MdDashboard,       countKey: 'totalcount' },
  1: { key: 'open',    label: 'Open',    color: '#ef4444', icon: MdHourglassEmpty,  countKey: 'pendingcount' },
  2: { key: 'overdue', label: 'Overdue', color: '#f59e0b', icon: MdReportProblem,   countKey: 'overduecount' },
  3: { key: 'paid',    label: 'Paid',    color: '#10b981', icon: MdCheckCircle,     countKey: 'paidcount' }
};
const STATUS_TABS = [0, 1, 2, 3];

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

const Invoice = () => {
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [billStatus, setBillStatus] = useState(0);
  const [isloader, setIsLoader] = useState(false);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  const handleDebouncedSearch = React.useCallback((val) => {
    setDebouncedSearch(val);
    setPage(0);
  }, []);

  // ============================================= || fetchinvoiceinsight ||
  const {
    data: insightdata,
    isLoading: isInsightLoading,
    isError: isInsightError,
    error: insightError
  } = useQuery({
    queryKey: ['invoiceInsight'],
    queryFn: fetchinvoiceinsight,
    refetchInterval: 300000
  });

  // ============================================= || fetchdeliverylist ||
  // NOTE: queryKey shape MUST stay `[billStatus]` — `fetchdeliverylist`
  // destructures `const [billStatus] = queryKey`.
  const {
    data: deliveryList,
    isLoading: isDeliveryLoading,
    isError: isDeliveryError,
    error: deliveryError
  } = useQuery({
    queryKey: [billStatus],
    queryFn: fetchdeliverylist,
    refetchInterval: 300000
  });

  const isLoading = isInsightLoading || isDeliveryLoading;
  const isError = isInsightError || isDeliveryError;
  const errorMessage = insightError?.message || deliveryError?.message;

  // Client-side filter across tenant name, contact person, invoice number.
  const filteredList = useMemo(() => {
    if (!deliveryList) return [];
    if (!debouncedSearch) return deliveryList;
    const q = debouncedSearch.toLowerCase().trim();
    return deliveryList.filter((row) =>
      [row.tenantname, row.contactperson, String(row.invoiceno)]
        .filter(Boolean)
        .some((field) => String(field).toLowerCase().includes(q))
    );
  }, [deliveryList, debouncedSearch]);

  const activePage = useMemo(() => {
    const maxPage = Math.max(0, Math.ceil(filteredList.length / rowsPerPage) - 1);
    return Math.min(page, maxPage);
  }, [filteredList.length, page, rowsPerPage]);

  // Keep page state in sync when filters or data updates shrink the list below current page
  React.useEffect(() => {
    if (page !== activePage) {
      setPage(activePage);
    }
  }, [page, activePage]);

  const pagedList = useMemo(
    () => filteredList.slice(activePage * rowsPerPage, activePage * rowsPerPage + rowsPerPage),
    [filteredList, activePage, rowsPerPage]
  );

  const grandTotal = useMemo(
    () => filteredList.reduce((sum, r) => sum + (Number(r.totalamount) || 0), 0),
    [filteredList]
  );

  const pageTotal = useMemo(
    () => pagedList.reduce((sum, r) => sum + (Number(r.totalamount) || 0), 0),
    [pagedList]
  );

  const handleChangePage = (event, newPage) => setPage(newPage);
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event?.target?.value);
    setPage(0);
  };

  if (isError) {
    return errorMessage;
  }

  const KPI_META = [
    { idx: 0, label: 'All Invoices', color: BRAND,     icon: MdDashboard,      value: insightdata?.totalcount ?? 0 },
    { idx: 1, label: 'Open',         color: '#ef4444', icon: MdOutlinePendingActions, value: insightdata?.pendingcount ?? 0 },
    { idx: 2, label: 'Overdue',      color: '#f59e0b', icon: MdReportProblem,  value: insightdata?.overduecount ?? 0 },
    { idx: 3, label: 'Paid',         color: '#10b981', icon: MdOutlineCheckCircle,    value: insightdata?.paidcount ?? 0 }
  ];

  const activeMeta = STATUS_META[billStatus];

  return (
    <>
      {(isloader || isLoading) && <Loader />}

      {/* ============================================= || Header || ============================================= */}
      <PageHeader
        title="Invoices"
        subtitle={`Live · Viewing ${activeMeta.label.toLowerCase()} invoices`}
        live
        action={
          <Box
            sx={{
              display: 'inline-flex',
              alignItems: 'center',
              gap: 1,
              px: 1.5,
              py: 0.875,
              borderRadius: 999,
              bgcolor: '#ffffff',
              border: `1.5px solid ${edge(BRAND)}`,
              color: BRAND,
              fontWeight: 800,
              fontSize: 12
            }}
          >
            <MdCurrencyRupee size={14} />
            <Typography variant="caption" sx={{ fontWeight: 800, color: DT.textSecondary, letterSpacing: 0.4, textTransform: 'uppercase' }}>
              Grand Total
            </Typography>
            <Typography sx={{ fontWeight: 800, color: BRAND, fontSize: 13 }}>
              {formatNumberToRupees(grandTotal)}
            </Typography>
          </Box>
        }
      />

      {/* ============================================= || KPI Cards (clickable filter) || ============================================= */}
      <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.idx} xs={6} sm={6} md={3}>
              <Box
                onClick={() => {
                  setBillStatus(item.idx);
                  setPage(0);
                }}
                sx={{ cursor: 'pointer', height: '100%' }}
              >
                <StatCard
                  title={item.label}
                  value={item.value}
                  icon={<Icon size={20} />}
                  color={item.color}
                  loading={isInsightLoading}
                />
              </Box>
            </Grid>
          );
        })}
      </Grid>

      {/* ============================================= || Status Tabs + Search || ============================================= */}
      <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="row"
          alignItems="center"
          justifyContent="space-between"
          gap={1.5}
          sx={{ flexWrap: 'wrap-reverse' }}
        >
          <Stack
            direction="row"
            spacing={0.75}
            sx={{
              flex: 1,
              overflowX: 'auto',
              py: 0.5,
              px: 0.25,
              '&::-webkit-scrollbar': { height: 6 },
              '&::-webkit-scrollbar-thumb': { backgroundColor: DT.borderSubtle, borderRadius: 4 }
            }}
          >
            {STATUS_TABS.map((idx) => {
              const meta = STATUS_META[idx];
              const Icon = meta.icon;
              const active = billStatus === idx;
              const count = insightdata?.[meta.countKey] ?? 0;
              return (
                <Box
                  key={idx}
                  onClick={() => {
                    setBillStatus(idx);
                    setPage(0);
                  }}
                  sx={{
                    display: 'inline-flex',
                    alignItems: 'center',
                    gap: { xs: 0.625, md: 0.875 },
                    pl: 0.5,
                    pr: { xs: 1, md: 1.25 },
                    py: 0.5,
                    flexShrink: 0,
                    cursor: 'pointer',
                    borderRadius: 999,
                    border: `1px solid ${active ? meta.color : DT.borderSubtle}`,
                    bgcolor: active ? meta.color : DT.surface,
                    color: active ? '#fff' : DT.textSecondary,
                    fontWeight: 600,
                    boxShadow: 'none',
                    transition: 'background-color 0.15s, border-color 0.15s, color 0.15s',
                    '&:hover': {
                      borderColor: active ? meta.color : '#cbd5e1',
                      bgcolor: active ? meta.color : DT.surfaceAlt
                    }
                  }}
                >
                  <Avatar
                    sx={{
                      width: { xs: 20, md: 22 },
                      height: { xs: 20, md: 22 },
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : soft(meta.color),
                      color: active ? '#fff' : meta.color
                    }}
                  >
                    <Icon size={12} />
                  </Avatar>
                  <Typography
                    variant="caption"
                    sx={{
                      fontWeight: 600,
                      fontSize: { xs: 11.5, md: 13 },
                      lineHeight: 1
                    }}
                  >
                    {meta.label}
                  </Typography>
                  <Box
                    sx={{
                      minWidth: { xs: 20, md: 24 },
                      height: { xs: 18, md: 20 },
                      px: 0.625,
                      display: 'inline-flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      borderRadius: 999,
                      fontSize: { xs: 10, md: 11 },
                      fontWeight: 700,
                      bgcolor: active ? 'rgba(255,255,255,0.22)' : DT.surfaceAlt,
                      color: active ? '#fff' : DT.textSecondary,
                      border: 'none'
                    }}
                  >
                    {count}
                  </Box>
                </Box>
              );
            })}
          </Stack>

          <Box sx={{ width: { xs: '100%', sm: 240, lg: 280 }, flex: { xs: '1 1 100%', sm: '0 0 auto' } }}>
            <DebounceSearchBar
              value={searchword}
              onChange={setSearchword}
              onDebouncedChange={handleDebouncedSearch}
              placeholder="Search invoices (ctrl+k)"
              sx={{
                m: 0,
                width: '100%',
                borderRadius: 999,
                bgcolor: '#ffffff',
                '& fieldset': { borderColor: '#e2e8f0', borderWidth: 1 },
                '&:hover fieldset': { borderColor: '#cbd5e1' },
                '&.Mui-focused fieldset': { borderColor: '#662582', 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 ? (
          <>
            {isDeliveryLoading ? (
              <Box sx={{ p: 1.5 }}>
                <OrdersTableSkeleton col={4} />
              </Box>
            ) : pagedList.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 }}>
                  <MdReceiptLong size={28} />
                </Avatar>
                <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                  No invoices to show
                </Typography>
                <Typography variant="caption" sx={{ color: DT.textSecondary, textAlign: 'center' }}>
                  {searchword
                    ? 'Try a different keyword.'
                    : `No ${activeMeta.label.toLowerCase()} invoices for this filter.`}
                </Typography>
              </Stack>
            ) : (
              <MobileCardList>
                {pagedList.map((item, index) => {
                  const overdue =
                    billStatus === 2 ||
                    (item.duedate && dayjs(item.duedate).isBefore(dayjs(), 'day') && billStatus !== 3);
                  return (
                    <MobileCard
                      key={item.invoiceno || index}
                      accent={BRAND}
                      header={
                        <Stack direction="row" alignItems="flex-start" justifyContent="space-between" spacing={1}>
                          <Stack direction="row" alignItems="center" spacing={1} sx={{ minWidth: 0 }}>
                            <AccentAvatar color={BRAND} size={36}>
                              <MdGroups size={18} />
                            </AccentAvatar>
                            <Stack spacing={0.25} sx={{ minWidth: 0 }}>
                              <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                                {item.tenantname || '—'}
                              </Typography>
                              {item.contactperson && (
                                <Typography variant="caption" sx={{ color: DT.textSecondary }} noWrap>
                                  {item.contactperson}
                                </Typography>
                              )}
                            </Stack>
                          </Stack>
                          <Tooltip title="Preview invoice" placement="left">
                            <IconButton
                              size="small"
                              onClick={() => {
                                setIsLoader(true);
                                setTimeout(() => {
                                  setIsLoader(false);
                                  navigate('/nearle/invoice/preview', { state: item });
                                }, 500);
                              }}
                              sx={{
                                flexShrink: 0,
                                bgcolor: soft(BRAND),
                                color: BRAND,
                                border: `1px solid ${edge(BRAND)}`,
                                '&:hover': { bgcolor: BRAND, color: '#fff' }
                              }}
                            >
                              <MdVisibility size={16} />
                            </IconButton>
                          </Tooltip>
                        </Stack>
                      }
                    >
                      <MobileFieldGrid>
                        <MobileField label="Invoice ID">
                          <Box
                            sx={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: 0.5,
                              px: 1,
                              py: 0.375,
                              borderRadius: 999,
                              bgcolor: tint('#0ea5e9'),
                              border: `1px solid ${edge('#0ea5e9')}`,
                              color: '#0ea5e9',
                              fontSize: 11,
                              fontWeight: 800
                            }}
                          >
                            <MdReceiptLong size={12} /> {item.invoiceno || '—'}
                          </Box>
                        </MobileField>
                        <MobileField label="Amount" align="right">
                          <Box
                            sx={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: 0.5,
                              px: 1,
                              py: 0.375,
                              borderRadius: 999,
                              bgcolor: '#ffffff',
                              border: `1px solid ${edge(BRAND)}`,
                              color: BRAND,
                              fontSize: 11,
                              fontWeight: 800,
                              justifyContent: 'center'
                            }}
                          >
                            <MdCurrencyRupee size={11} />
                            {formatNumberToRupees(item.totalamount).replace('₹', '').trim()}
                          </Box>
                        </MobileField>
                        <MobileField label="Invoice Date">
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <MdEventNote size={12} color={DT.textMuted} />
                            <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textPrimary }} noWrap>
                              {item.transactiondate ? dayjs(item.transactiondate).format('DD/MM/YYYY') : '—'}
                            </Typography>
                          </Stack>
                        </MobileField>
                        <MobileField label="Due Date">
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <MdEventNote size={12} color={overdue && billStatus !== 3 ? '#ef4444' : DT.textMuted} />
                            <Typography
                              variant="caption"
                              sx={{
                                fontWeight: 700,
                                color: overdue && billStatus !== 3 ? '#ef4444' : DT.textPrimary
                              }}
                              noWrap
                            >
                              {item.duedate ? dayjs(item.duedate).format('DD/MM/YYYY') : '—'}
                            </Typography>
                          </Stack>
                        </MobileField>
                        <MobileField label="Items">
                          <Box
                            sx={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              gap: 0.5,
                              px: 0.875,
                              py: 0.25,
                              borderRadius: 999,
                              bgcolor: tint('#14b8a6'),
                              border: `1px solid ${edge('#14b8a6')}`,
                              color: '#14b8a6',
                              fontSize: 11,
                              fontWeight: 800,
                              minWidth: 44,
                              justifyContent: 'center'
                            }}
                          >
                            <MdInventory2 size={11} /> {item.itemcount ?? 0}
                          </Box>
                        </MobileField>
                      </MobileFieldGrid>
                    </MobileCard>
                  );
                })}
              </MobileCardList>
            )}
          </>
        ) : (
          <TableContainer
            sx={{
              maxHeight: { xs: 'calc(100vh - 220px)', md: 'calc(100vh - 190px)' },
              '&::-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: 880, md: 1060 } }}>
            <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: 2 }
                  }
                }}
              >
                <TableCell>#</TableCell>
                <TableCell>Client</TableCell>
                <TableCell>Invoice ID</TableCell>
                <TableCell>Invoice Date</TableCell>
                <TableCell>Due Date</TableCell>
                <TableCell align="center">Items</TableCell>
                <TableCell align="right">Amount</TableCell>
                <TableCell align="center">Action</TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {isDeliveryLoading && <OrdersTableSkeleton col={4} />}
              {!isDeliveryLoading && pagedList.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} sx={{ py: 6 }}>
                    <Stack alignItems="center" spacing={1.5}>
                      <Avatar sx={{ width: 64, height: 64, bgcolor: soft('#94a3b8'), color: DT.textMuted }}>
                        <MdReceiptLong size={28} />
                      </Avatar>
                      <Typography variant="subtitle1" sx={{ fontWeight: 700, color: DT.textPrimary }}>
                        No invoices to show
                      </Typography>
                      <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                        {searchword
                          ? 'Try a different keyword.'
                          : `No ${activeMeta.label.toLowerCase()} invoices for this filter.`}
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              ) : (
                pagedList.map((item, index) => {
                  const overdue = billStatus === 2 || (item.duedate && dayjs(item.duedate).isBefore(dayjs(), 'day') && billStatus !== 3);
                  return (
                    <TableRow
                      key={item.invoiceno || index}
                      sx={{
                        transition: 'background-color 0.15s',
                        '& td': {
                          borderBottom: `1px solid ${DT.divider}`,
                          py: { xs: 1, md: 1.5 },
                          px: { xs: 1, md: 2 },
                          verticalAlign: 'top'
                        },
                        '&:hover': { backgroundColor: DT.surfaceAlt }
                      }}
                    >
                      <TableCell>
                        <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textMuted }}>
                          {String(activePage * rowsPerPage + index + 1).padStart(2, '0')}
                        </Typography>
                      </TableCell>

                      <TableCell>
                        <Stack direction="row" alignItems="center" spacing={1}>
                          <AccentAvatar color={BRAND} size={36}>
                            <MdGroups size={18} />
                          </AccentAvatar>
                          <Stack spacing={0.25} sx={{ minWidth: 0 }}>
                            <Typography variant="subtitle2" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                              {item.tenantname || '—'}
                            </Typography>
                            {item.contactperson && (
                              <Typography variant="caption" sx={{ color: DT.textSecondary }}>
                                {item.contactperson}
                              </Typography>
                            )}
                          </Stack>
                        </Stack>
                      </TableCell>

                      <TableCell>
                        <Box
                          sx={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: 0.5,
                            px: 1,
                            py: 0.375,
                            borderRadius: 999,
                            bgcolor: tint('#0ea5e9'),
                            border: `1px solid ${edge('#0ea5e9')}`,
                            color: '#0ea5e9',
                            fontSize: 11,
                            fontWeight: 800
                          }}
                        >
                          <MdReceiptLong size={12} /> {item.invoiceno || '—'}
                        </Box>
                      </TableCell>

                      <TableCell>
                        <Stack spacing={0.25}>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <MdEventNote size={12} color={DT.textMuted} />
                            <Typography variant="caption" sx={{ fontWeight: 700, color: DT.textPrimary, whiteSpace: 'nowrap' }}>
                              {item.transactiondate ? dayjs(item.transactiondate).format('DD/MM/YYYY') : '—'}
                            </Typography>
                          </Stack>
                          <Typography variant="caption" sx={{ color: DT.textSecondary, pl: 2 }}>
                            {item.transactiondate ? dayjs(item.transactiondate).utc().format('hh:mm A') : ''}
                          </Typography>
                        </Stack>
                      </TableCell>

                      <TableCell>
                        <Stack spacing={0.25}>
                          <Stack direction="row" alignItems="center" spacing={0.5}>
                            <MdEventNote
                              size={12}
                              color={overdue && billStatus !== 3 ? '#ef4444' : DT.textMuted}
                            />
                            <Typography
                              variant="caption"
                              sx={{
                                fontWeight: 700,
                                color: overdue && billStatus !== 3 ? '#ef4444' : DT.textPrimary,
                                whiteSpace: 'nowrap'
                              }}
                            >
                              {item.duedate ? dayjs(item.duedate).format('DD/MM/YYYY') : '—'}
                            </Typography>
                          </Stack>
                          <Typography variant="caption" sx={{ color: DT.textSecondary, pl: 2 }}>
                            {item.duedate ? dayjs(item.duedate).utc().format('hh:mm A') : ''}
                          </Typography>
                        </Stack>
                      </TableCell>

                      <TableCell align="center">
                        <Box
                          sx={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: 0.5,
                            px: 0.875,
                            py: 0.25,
                            borderRadius: 999,
                            bgcolor: tint('#14b8a6'),
                            border: `1px solid ${edge('#14b8a6')}`,
                            color: '#14b8a6',
                            fontSize: 11,
                            fontWeight: 800,
                            minWidth: 44,
                            justifyContent: 'center'
                          }}
                        >
                          <MdInventory2 size={11} /> {item.itemcount ?? 0}
                        </Box>
                      </TableCell>

                      <TableCell align="right">
                        <Box
                          sx={{
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: 0.5,
                            px: 1,
                            py: 0.375,
                            borderRadius: 999,
                            bgcolor: '#ffffff',
                            border: `1px solid ${edge(BRAND)}`,
                            color: BRAND,
                            fontSize: 11,
                            fontWeight: 800,
                            minWidth: 110,
                            justifyContent: 'center'
                          }}
                        >
                          <MdCurrencyRupee size={11} />
                          {formatNumberToRupees(item.totalamount).replace('₹', '').trim()}
                        </Box>
                      </TableCell>

                      <TableCell align="center">
                        <Tooltip title="Preview invoice" placement="left">
                          <IconButton
                            size="small"
                            onClick={() => {
                              setIsLoader(true);
                              setTimeout(() => {
                                setIsLoader(false);
                                navigate('/nearle/invoice/preview', { state: item });
                              }, 500);
                            }}
                            sx={{
                              bgcolor: soft(BRAND),
                              color: BRAND,
                              border: `1px solid ${edge(BRAND)}`,
                              '&:hover': { bgcolor: BRAND, color: '#fff' }
                            }}
                          >
                            <MdVisibility size={16} />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
              </TableBody>
            </Table>
          </TableContainer>
        )}

        <Divider />
        <Stack
          direction={{ xs: 'column', sm: 'row' }}
          alignItems={{ xs: 'flex-start', sm: 'center' }}
          justifyContent="space-between"
          sx={{
            px: 2,
            py: 1,
            background: '#ffffff'
          }}
        >
          <Typography variant="caption" sx={{ fontWeight: 800, color: DT.textSecondary, letterSpacing: 0.6, textTransform: 'uppercase' }}>
            Page total · {formatNumberToRupees(pageTotal)}
          </Typography>
          <TablePagination
            rowsPerPageOptions={[5, 10, 25, 100]}
            component="div"
            count={filteredList.length}
            rowsPerPage={rowsPerPage}
            page={activePage}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
            sx={{
              '& .MuiTablePagination-toolbar': { minHeight: 40, px: 0 },
              '& .MuiTablePagination-selectLabel, & .MuiTablePagination-displayedRows': {
                fontWeight: 700,
                color: DT.textSecondary
              }
            }}
          />
        </Stack>
      </Paper>

      <Outlet />
    </>
  );
};

export default Invoice;
