import React, { useState, useEffect, useCallback, memo } from "react";
import { acotService } from "@/services/dashboard/acotService";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { BusinessRangeSelect } from "@/components/dashboard/shared/BusinessRangeSelect";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  Legend,
} from "recharts";
// Import Tooltip from recharts with alias to avoid naming conflict
import { Tooltip as RechartsTooltip } from "recharts";
import {
  DollarSign,
  ShoppingCart,
  Package,
  Clock,
  Map,
  Tags,
  Star,
  XCircle,
  TrendingUp,
  AlertCircle,
  RefreshCcw,
  CircleDollarSign,
  MapPin,
} from "lucide-react";
import { DateTime } from "luxon";
import { CARD_STYLES } from "@/lib/dashboard/designTokens";
import {
  DashboardStatCard,
  DashboardStatCardSkeleton,
  ChartSkeleton,
  TableSkeleton,
  DashboardEmptyState,
  DashboardErrorState,
  TOOLTIP_STYLES,
} from "@/components/dashboard/shared";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from "@/components/ui/tooltip";

const formatCurrency = (value, minimumFractionDigits = 0) => {
  if (!value || isNaN(value)) return "$0";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits,
    maximumFractionDigits: minimumFractionDigits,
  }).format(value);
};

const formatPercentage = (value) => {
  if (typeof value !== "number") return "0%";
  return `${Math.round(value)}%`;
};

const formatHour = (hour) => {
  const date = new Date();
  date.setHours(hour, 0, 0);
  return date.toLocaleString("en-US", { hour: "numeric", hour12: true });
};

// Reusable chart components
const TimeSeriesChart = ({
  data,
  dataKey,
  name,
  color = "hsl(var(--primary))",
  type = "line",
  valueFormatter = (value) => value,
  height = 400,
}) => {
  const ChartComponent = type === "line" ? LineChart : BarChart;
  const DataComponent = type === "line" ? Line : Bar;

  // Handle multiple series
  const keys = Array.isArray(dataKey) ? dataKey : [dataKey];
  const names = Array.isArray(name) ? name : [name];
  const colors = Array.isArray(color) ? color : [color];

  return (
    <div className="h-[400px] w-full">
      <ResponsiveContainer width="100%" height={height}>
        <ChartComponent
          data={data}
          margin={{ top: 10, right: 20, left: -20, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis
            dataKey="timestamp"
            tickFormatter={(value) => DateTime.fromISO(value).toFormat("LLL d")}
            className="text-xs"
          />
          <YAxis tickFormatter={valueFormatter} className="text-xs" />
          <RechartsTooltip
            content={({ active, payload, label }) => {
              if (!active || !payload?.length) return null;
              return (
                <div className={TOOLTIP_STYLES.container}>
                  <p className={TOOLTIP_STYLES.header}>
                    {DateTime.fromISO(label).toFormat("LLL d")}
                  </p>
                  <div className={TOOLTIP_STYLES.content}>
                    {payload.map((entry, i) => (
                      <div key={i} className={TOOLTIP_STYLES.row}>
                        <div className={TOOLTIP_STYLES.rowLabel}>
                          <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: entry.color || entry.stroke }} />
                          <span className={TOOLTIP_STYLES.name}>{entry.name}</span>
                        </div>
                        <span className={TOOLTIP_STYLES.value}>{valueFormatter(entry.value)}</span>
                      </div>
                    ))}
                  </div>
                </div>
              );
            }}
          />
          <Legend />
          {keys.map((key, index) => (
            <DataComponent
              key={key}
              type="monotone"
              dataKey={key}
              name={names[index] || key}
              stroke={colors[index]}
              fill={colors[index]}
              strokeWidth={2}
              dot={false}
            />
          ))}
        </ChartComponent>
      </ResponsiveContainer>
    </div>
  );
};

const DetailDialog = ({ open, onOpenChange, title, children }) => (
  <Dialog open={open} onOpenChange={onOpenChange}>
    <DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle>{title}</DialogTitle>
      </DialogHeader>
      {children}
    </DialogContent>
  </Dialog>
);

// Detail view components
const RevenueDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  // Ensure we have daily data points and they're properly formatted
  const chartData = data
    .map((day) => ({
      timestamp: DateTime.fromISO(day.timestamp).toFormat("yyyy-MM-dd"),
      revenue: parseFloat(day.revenue || 0),
      orders: parseInt(day.orders || 0),
      date: DateTime.fromISO(day.timestamp).toFormat("LLL d"),
    }))
    .sort(
      (a, b) => DateTime.fromISO(a.timestamp) - DateTime.fromISO(b.timestamp)
    );

  return (
    <TimeSeriesChart
      data={chartData}
      dataKey="revenue"
      name="Revenue"
      color="hsl(142.1 76.2% 36.3%)"
      valueFormatter={(value) => formatCurrency(value)}
      height={400}
    />
  );
};

const OrdersDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  return (
    <>
      <TimeSeriesChart
        data={data}
        dataKey="orders"
        name="Orders"
        color="hsl(221.2 83.2% 53.3%)"
      />
      {data[0]?.hourlyOrders && (
        <div className="mt-8">
          <h3 className="text-lg font-medium mb-4">Hourly Distribution</h3>
          <TimeSeriesChart
            data={data[0].hourlyOrders.map((count, hour) => ({
              hour: formatHour(hour),
              orders: count,
            }))}
            dataKey="orders"
            name="Orders"
            type="bar"
            color="hsl(221.2 83.2% 53.3%)"
          />
        </div>
      )}
    </>
  );
};

// Add detail view components
const AverageOrderDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  return (
    <TimeSeriesChart
      data={data}
      dataKey="averageOrderValue"
      name="Average Order Value"
      color="hsl(262.1 83.3% 57.8%)"
      valueFormatter={(value) => formatCurrency(value)}
    />
  );
};

const CancellationsDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  const cancelData = data[0]?.canceledOrders || {
    total: 0,
    count: 0,
    reasons: {},
    items: [],
  };
  const timeSeriesData = data.map((day) => ({
    timestamp: day.timestamp,
    total: day.canceledOrders?.total || 0,
    count: day.canceledOrders?.count || 0,
  }));

  const reasonData = Object.entries(cancelData.reasons || {})
    .map(([reason, count]) => ({
      reason,
      count,
    }))
    .sort((a, b) => b.count - a.count);

  return (
    <div className="space-y-8">
      <div>
        <h3 className="text-lg font-medium mb-4">Daily Cancellation Amount</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="total"
          name="Cancellation Amount"
          color="hsl(0 84.2% 60.2%)"
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Daily Cancellation Count</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="count"
          name="Cancellation Count"
          type="bar"
          color="hsl(0 84.2% 60.2%)"
        />
      </div>

      {reasonData.length > 0 && (
        <div>
          <h3 className="text-lg font-medium mb-4">Cancellation Reasons</h3>
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Reason</TableHead>
                  <TableHead className="text-right">Count</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {reasonData.map((item, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">{item.reason}</TableCell>
                    <TableCell className="text-right">
                      {item.count.toLocaleString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>
      )}
    </div>
  );
};

const BrandsCategoriesDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  const stats = data[0];
  const brandsList = stats?.brands?.list || [];
  const categoriesList = stats?.categories?.list || [];

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
      <div className="flex flex-col h-[40vh] md:h-[60vh]">
        <h3 className="text-md font-medium mb-4 flex items-center gap-2">
          <Star className="h-5 w-5 text-yellow-500" />
          Brands ({stats?.brands?.total || 0})
        </h3>
        <div className="rounded-md border overflow-auto">
          <Table>
            <TableHeader className="sticky top-0 bg-background z-10">
              <TableRow>
                <TableHead>Brand</TableHead>
                <TableHead className="text-right">Items</TableHead>
                <TableHead className="text-right">Revenue</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody className="max-h-[40vh] md:max-h-[60vh] overflow-auto">
              {brandsList.map((brand) => (
                <TableRow key={brand.id || brand.name}>
                  <TableCell className="font-medium">{brand.name}</TableCell>
                  <TableCell className="text-right">
                    {brand.count?.toLocaleString()}
                  </TableCell>
                  <TableCell className="text-right">
                    ${brand.revenue?.toFixed(2)}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      <div className="flex flex-col h-[40vh] md:h-[60vh]">
        <h3 className="text-md font-medium mb-4 flex items-center gap-2">
          <Tags className="h-5 w-5 text-indigo-500" />
          Categories ({stats?.categories?.total || 0})
        </h3>
        <div className="rounded-md border overflow-auto">
          <Table>
            <TableHeader className="sticky top-0 bg-background z-10">
              <TableRow>
                <TableHead>Category</TableHead>
                <TableHead className="text-right">Items</TableHead>
                <TableHead className="text-right">Revenue</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody className="max-h-[40vh] md:max-h-[60vh] overflow-auto">
              {categoriesList.map((category) => (
                <TableRow key={category.id || category.name}>
                  <TableCell className="font-medium">{category.name}</TableCell>
                  <TableCell className="text-right">
                    {category.count?.toLocaleString()}
                  </TableCell>
                  <TableCell className="text-right">
                    ${category.revenue?.toFixed(2)}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
};

const ShippingDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  const shippedCount = data[0]?.shipping?.shippedCount || 0;
  const locations = data[0]?.shipping?.locations || {};
  const methodStats = data[0]?.shipping?.methodStats || [];

  // Shipping method name mappings
  const shippingMethodNames = {
    usps_ground_advantage: "USPS Ground Advantage",
    usps_priority: "USPS Priority",
    Unknown: "Digital",
    fedex_ieconomy: "FedEx Intl Economy",
    fedex_homedelivery: "FedEx Ground",
    fedex_ground: "FedEx Ground",
    fedex_iground: "FedEx Intl Ground",
    fedex_2day: "FedEx 2 Day",
  };

  return (
    <div className="space-y-8">
      {/* Shipping Methods */}
      <div>
        <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
          <Package className="h-5 w-5 text-teal-500" />
          Shipping Methods
        </h3>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50%]">Method</TableHead>
                <TableHead className="w-[25%] text-right">Orders</TableHead>
                <TableHead className="w-[25%] text-right">% of Total</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {methodStats.map((method) => (
                <TableRow key={method.name}>
                  <TableCell className="font-medium">
                    {shippingMethodNames[method.name] || method.name}
                  </TableCell>
                  <TableCell className="text-right">
                    {method.value.toLocaleString()}
                  </TableCell>
                  <TableCell className="text-right">
                    {((method.value / shippedCount) * 100).toFixed(1)}%
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* Countries */}
      <div>
        <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
          <MapPin className="h-5 w-5 text-teal-500" />
          Countries ({locations.byCountry?.length || 0})
        </h3>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50%]">Country</TableHead>
                <TableHead className="w-[25%] text-right">Orders</TableHead>
                <TableHead className="w-[25%] text-right">% of Total</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {locations.byCountry?.map((country) => (
                <TableRow key={country.country}>
                  <TableCell className="font-medium">
                    {country.country}
                  </TableCell>
                  <TableCell className="text-right">
                    {country.count.toLocaleString()}
                  </TableCell>
                  <TableCell className="text-right">
                    {country.percentage.toFixed(1)}%
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* States */}
      <div>
        <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
          <MapPin className="h-5 w-5 text-teal-500" />
          States/Regions ({locations.byState?.length || 0})
        </h3>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50%]">State</TableHead>
                <TableHead className="w-[25%] text-right">Orders</TableHead>
                <TableHead className="w-[25%] text-right">% of Total</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {locations.byState?.map((state) => (
                <TableRow key={state.state}>
                  <TableCell className="font-medium">{state.state}</TableCell>
                  <TableCell className="text-right">
                    {state.count.toLocaleString()}
                  </TableCell>
                  <TableCell className="text-right">
                    {state.percentage.toFixed(1)}%
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>
    </div>
  );
};

const OrderTypeDetails = ({ data, type }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  const timeSeriesData = data.map((day) => ({
    timestamp: day.timestamp || day.date,
    count: day.count ?? day.orders,  // Backend returns 'orders'
    value: day.value ?? day.revenue,  // Backend returns 'revenue'
    percentage: day.percentage,
  }));

  const typeColors = {
    pre_orders: "hsl(47.9 95.8% 53.1%)", // Yellow for pre-orders
    local_pickup: "hsl(192.2 70.1% 51.4%)", // Cyan for local pickup
    on_hold: "hsl(346.8 77.2% 49.8%)", // Red for on hold
  };

  const color = typeColors[type];

  return (
    <div className="space-y-8">
      <div>
        <h3 className="text-lg font-medium mb-4">Daily Order Count</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="count"
          name="Orders"
          type="bar"
          color={color}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Daily Value</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="value"
          name="Value"
          color={color}
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Percentage of Orders</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="percentage"
          name="Percentage"
          color={color}
          valueFormatter={(value) => `${value.toFixed(1)}%`}
        />
      </div>
    </div>
  );
};

const PeakHourDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  // hourlyOrders is now an array of {hour, count} objects in chronological order (rolling 24hrs)
  const hourlyData =
    data[0]?.hourlyOrders?.map((item) => ({
      timestamp: item.hour,  // The actual hour (0-23)
      orders: item.count,
    })) || [];

  return (
    <div className="h-[400px] w-full">
      <ResponsiveContainer width="100%" height={400}>
        <BarChart
          data={hourlyData}
          margin={{ top: 10, right: 30, left: 20, bottom: 5 }}
        >
          <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
          <XAxis
            dataKey="timestamp"
            tickFormatter={(hour) => {
              const date = new Date();
              date.setHours(hour, 0, 0);
              return date.toLocaleString("en-US", {
                hour: "numeric",
                hour12: true,
              });
            }}
            className="text-xs"
          />
          <YAxis className="text-xs" />
          <RechartsTooltip
            content={({ active, payload, label }) => {
              if (!active || !payload?.length) return null;
              const date = new Date();
              date.setHours(label, 0, 0);
              const time = date.toLocaleString("en-US", {
                hour: "numeric",
                hour12: true,
              });
              return (
                <div className={TOOLTIP_STYLES.container}>
                  <p className={TOOLTIP_STYLES.header}>{time}</p>
                  <div className={TOOLTIP_STYLES.content}>
                    <div className={TOOLTIP_STYLES.row}>
                      <div className={TOOLTIP_STYLES.rowLabel}>
                        <span className={TOOLTIP_STYLES.dot} style={{ backgroundColor: "hsl(322.7 73.9% 52.4%)" }} />
                        <span className={TOOLTIP_STYLES.name}>Orders</span>
                      </div>
                      <span className={TOOLTIP_STYLES.value}>{payload[0].value}</span>
                    </div>
                  </div>
                </div>
              );
            }}
          />
          <Bar dataKey="orders" name="Orders" fill="hsl(322.7 73.9% 52.4%)" />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
};

const RefundDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  const refundData = data[0]?.refunds || { total: 0, count: 0, reasons: {} };
  const timeSeriesData = data.map((day) => ({
    timestamp: day.timestamp,
    total: day.refunds?.total || 0,
    count: day.refunds?.count || 0,
  }));

  const reasonData = Object.entries(refundData.reasons || {})
    .map(([reason, count]) => ({
      reason,
      count,
    }))
    .sort((a, b) => b.count - a.count);

  return (
    <div className="space-y-8">
      <div>
        <h3 className="text-lg font-medium mb-4">Daily Refund Amount</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="total"
          name="Refund Amount"
          color="hsl(20.5 90.2% 48.2%)"
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Daily Refund Count</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="count"
          name="Refund Count"
          type="bar"
          color="hsl(20.5 90.2% 48.2%)"
        />
      </div>

      {reasonData.length > 0 && (
        <div>
          <h3 className="text-lg font-medium mb-4">Refund Reasons</h3>
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Reason</TableHead>
                  <TableHead className="text-right">Count</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {reasonData.map((item, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">{item.reason}</TableCell>
                    <TableCell className="text-right">
                      {item.count.toLocaleString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>
      )}
    </div>
  );
};

const OrderRangeDetails = ({ data }) => {
  if (!data?.length)
    return (
      <div className="text-muted-foreground">
        No data available for the selected time range.
      </div>
    );

  // Get the data from the entire period
  const allData = data.reduce((acc, day) => {
    // Initialize distribution data structure if not exists
    if (!acc.orderValueDistribution) {
      acc.orderValueDistribution =
        day.orderValueDistribution?.map((range) => ({
          ...range,
          count: 0,
          total: 0,
        })) || [];
    }

    // Aggregate distribution data
    day.orderValueDistribution?.forEach((range, index) => {
      if (acc.orderValueDistribution[index]) {
        acc.orderValueDistribution[index].count += range.count;
        acc.orderValueDistribution[index].total += range.total;
      }
    });

    // Track total orders for percentage calculation
    acc.totalOrders = (acc.totalOrders || 0) + (day.orders || 0);

    return acc;
  }, {});

  const timeSeriesData = data.map((day) => ({
    timestamp: day.timestamp,
    largest: day.orderValueRange?.largest || 0,
    smallest: day.orderValueRange?.smallest || 0,
    average: day.averageOrderValue || 0,
  }));

  // Transform distribution data using aggregated values
  const formattedDistributionData =
    allData.orderValueDistribution?.map((range) => {
      const totalRevenue = allData.orderValueDistribution.reduce(
        (sum, r) => sum + (r.total || 0),
        0
      );
      return {
        range:
          range.max === "Infinity"
            ? `$${range.min}+`
            : `$${range.min}-${range.max}`,
        count: range.count,
        total: range.total,
        percentage: ((range.count / (allData.totalOrders || 1)) * 100).toFixed(
          1
        ),
        revenuePercentage: ((range.total / (totalRevenue || 1)) * 100).toFixed(
          1
        ),
      };
    }) || [];

  return (
    <div className="space-y-8">
      <div>
        <h3 className="text-lg font-medium mb-4">Order Value Range</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey={["largest", "smallest"]}
          name={["Largest Order", "Smallest Order"]}
          color={["hsl(262.1 83.3% 57.8%)", "hsl(221.2 83.2% 53.3%)"]}
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Average Order Value</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="average"
          name="Average Order Value"
          color="hsl(142.1 76.2% 36.3%)"
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

      {formattedDistributionData.length > 0 && (
        <div>
          <h3 className="text-lg font-medium mb-4">Order Value Distribution</h3>
          <div className="rounded-lg border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="">Range</TableHead>
                  <TableHead className="text-right">Orders</TableHead>
                  <TableHead className="text-right">Total Revenue</TableHead>
                  <TableHead className="text-right">% of Orders</TableHead>
                  <TableHead className="text-right">% of Revenue</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {formattedDistributionData.map((range, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium whitespace-nowrap">
                      {range.range}
                    </TableCell>
                    <TableCell className="text-right whitespace-nowrap">
                      {range.count.toLocaleString()}
                    </TableCell>
                    <TableCell className="text-right whitespace-nowrap">
                      {formatCurrency(range.total)}
                    </TableCell>
                    <TableCell className="text-right whitespace-nowrap">
                      {range.percentage}%
                    </TableCell>
                    <TableCell className="text-right whitespace-nowrap">
                      {range.revenuePercentage}%
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <div className="mt-4 h-[300px]">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={formattedDistributionData}
                margin={{ top: 10, right: 20, left: -20, bottom: 40 }}
              >
                <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                <XAxis
                  dataKey="range"
                  angle={-45}
                  textAnchor="end"
                  height={80}
                  className="text-xs"
                />
                <YAxis
                  className="text-xs"
                  tickFormatter={(value) => `${value}%`}
                />
                <RechartsTooltip
                  content={({ active, payload }) => {
                    if (!active || !payload?.length) return null;
                    const data = payload[0].payload;
                    return (
                      <div className={TOOLTIP_STYLES.container}>
                        <p className={TOOLTIP_STYLES.header}>{data.range}</p>
                        <div className={TOOLTIP_STYLES.content}>
                          <div className={TOOLTIP_STYLES.row}>
                            <span className={TOOLTIP_STYLES.name}>Orders</span>
                            <span className={TOOLTIP_STYLES.value}>{data.count.toLocaleString()}</span>
                          </div>
                          <div className={TOOLTIP_STYLES.row}>
                            <span className={TOOLTIP_STYLES.name}>Revenue</span>
                            <span className={TOOLTIP_STYLES.value}>{formatCurrency(data.total)}</span>
                          </div>
                          <div className={TOOLTIP_STYLES.row}>
                            <span className={TOOLTIP_STYLES.name}>% of Orders</span>
                            <span className={TOOLTIP_STYLES.value}>{data.percentage}%</span>
                          </div>
                          <div className={TOOLTIP_STYLES.row}>
                            <span className={TOOLTIP_STYLES.name}>% of Revenue</span>
                            <span className={TOOLTIP_STYLES.value}>{data.revenuePercentage}%</span>
                          </div>
                        </div>
                      </div>
                    );
                  }}
                />
                <Bar
                  dataKey="percentage"
                  name="Percentage of Orders"
                  fill="hsl(262.1 83.3% 57.8%)"
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}
    </div>
  );
};

// Add this before the StatCards component
const useDataCache = () => {
  const [cache, setCache] = useState({});

  const getCacheKey = (timeRange, metric) => `${timeRange}_${metric}`;

  const setCacheData = (timeRange, metric, data) => {
    setCache((prev) => ({
      ...prev,
      [getCacheKey(timeRange, metric)]: {
        data,
        timestamp: Date.now(),
      },
    }));
  };

  const getCacheData = (timeRange, metric) => {
    const key = getCacheKey(timeRange, metric);
    return cache[key]?.data;
  };

  const clearCache = () => setCache({});

  return { setCacheData, getCacheData, clearCache };
};

// Add memoized detail components at the top level
const MemoizedRevenueDetails = memo(RevenueDetails);
const MemoizedOrdersDetails = memo(OrdersDetails);
const MemoizedAverageOrderDetails = memo(AverageOrderDetails);
const MemoizedRefundDetails = memo(RefundDetails);
const MemoizedOrderRangeDetails = memo(OrderRangeDetails);
const MemoizedOrderTypeDetails = memo(OrderTypeDetails);
const MemoizedBrandsCategoriesDetails = memo(BrandsCategoriesDetails);
const MemoizedShippingDetails = memo(ShippingDetails);
const MemoizedPeakHourDetails = memo(PeakHourDetails);
const MemoizedCancellationsDetails = memo(CancellationsDetails);

// Note: Using ChartSkeleton and TableSkeleton from @/components/dashboard/shared

const StatCards = ({
  timeRange: initialTimeRange = "today",
  startDate,
  endDate,
  title = "Sales Dashboard",
  description = "",
}) => {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdate, setLastUpdate] = useState(null);
  const [timeRange, setTimeRange] = useState(initialTimeRange);
  const [selectedMetric, setSelectedMetric] = useState(null);
  const [detailDataLoading, setDetailDataLoading] = useState({});
  const [detailData, setDetailData] = useState({});
  const [projection, setProjection] = useState(null);
  const [projectionLoading, setProjectionLoading] = useState(false);
  const { setCacheData, getCacheData } = useDataCache();

  // Function to determine if we should use last30days for trend charts
  const shouldUseLast30Days = useCallback(
    (metric) => {
      if (["brands_categories", "shipping"].includes(metric)) {
        return false;
      }
      const shortPeriods = [
        "today",
        "yesterday",
        "last7days",
        "thisWeek",
        "lastWeek",
      ];
      return shortPeriods.includes(timeRange);
    },
    [timeRange]
  );

  // Function to fetch detail data for a specific metric
  const fetchDetailData = useCallback(
    async (metric, orderType) => {
      const detailTimeRange = shouldUseLast30Days(metric)
        ? "last30days"
        : timeRange;
      const cachedData = getCacheData(detailTimeRange, metric);

      if (cachedData) {
        setDetailData((prev) => ({ ...prev, [metric]: cachedData }));
        return cachedData;
      }

      setDetailDataLoading((prev) => ({ ...prev, [metric]: true }));

      try {
        const params = {
          ...(timeRange === "custom"
            ? { startDate, endDate }
            : { timeRange: detailTimeRange }),
          metric,
          daily: true,
        };

        // For metrics that need the full stats
        if (["shipping", "brands_categories"].includes(metric)) {
          const response = await acotService.getStats(params);
          const data = [response.stats];
          setCacheData(detailTimeRange, metric, data);
          setDetailData((prev) => ({ ...prev, [metric]: data }));
          setError(null);
          return data;
        }

        // For order types (pre_orders, local_pickup, on_hold)
        if (["pre_orders", "local_pickup", "on_hold"].includes(metric)) {
          const response = await acotService.getStatsDetails({
            ...params,
            orderType: orderType,
          });
          const data = response.stats;
          setCacheData(detailTimeRange, metric, data);
          setDetailData((prev) => ({ ...prev, [metric]: data }));
          setError(null);
          return data;
        }

        // For refunds and cancellations
        if (["refunds", "cancellations"].includes(metric)) {
          const response = await acotService.getStatsDetails({
            ...params,
            eventType:
              metric === "refunds" ? "PAYMENT_REFUNDED" : "CANCELED_ORDER",
          });
          const data = response.stats;

          // Transform the data to match the expected format
          const transformedData = data.map((day) => ({
            ...day,
            timestamp: day.timestamp,
            refunds:
              metric === "refunds"
                ? {
                    total: day.refunds?.total || 0,
                    count: day.refunds?.count || 0,
                    reasons: day.refunds?.reasons || {},
                  }
                : undefined,
            canceledOrders:
              metric === "cancellations"
                ? {
                    total: day.canceledOrders?.total || 0,
                    count: day.canceledOrders?.count || 0,
                    reasons: day.canceledOrders?.reasons || {},
                  }
                : undefined,
          }));

          setCacheData(detailTimeRange, metric, transformedData);
          setDetailData((prev) => ({ ...prev, [metric]: transformedData }));
          setError(null);
          return transformedData;
        }

        // For order range
        if (metric === "order_range") {
          const response = await acotService.getStatsDetails({
            ...params,
            eventType: "PLACED_ORDER",
          });
          const data = response.stats;
          setCacheData(detailTimeRange, metric, data);
          setDetailData((prev) => ({ ...prev, [metric]: data }));
          setError(null);
          return data;
        }

        // For all other metrics
        const response = await acotService.getStatsDetails(params);
        const data = response.stats;
        setCacheData(detailTimeRange, metric, data);
        setDetailData((prev) => ({ ...prev, [metric]: data }));
        setError(null);
        return data;
      } catch (error) {
        console.error(`Error fetching detail data for ${metric}:`, error);
        setError(error.response?.data?.error || error.message);
        return null;
      } finally {
        setDetailDataLoading((prev) => ({ ...prev, [metric]: false }));
      }
    },
    [
      timeRange,
      startDate,
      endDate,
      shouldUseLast30Days,
      setCacheData,
      getCacheData,
    ]
  );

  // Throttled preloadDetailData function to avoid overwhelming the server
  const preloadDetailData = useCallback(async () => {
    const metrics = [
      "revenue",
      "orders",
      "average_order",
      "refunds",
      "cancellations",
      "order_range",
      "pre_orders",
      "local_pickup",
      "on_hold",
    ];

    // Process metrics in batches of 3 to avoid overwhelming the connection pool
    const batchSize = 3;
    for (let i = 0; i < metrics.length; i += batchSize) {
      const batch = metrics.slice(i, i + batchSize);
      try {
        await Promise.all(
          batch.map((metric) => fetchDetailData(metric, metric))
        );
        // Small delay between batches to prevent overwhelming the server
        if (i + batchSize < metrics.length) {
          await new Promise(resolve => setTimeout(resolve, 50));
        }
      } catch (error) {
        console.error(`Error during detail data preload batch ${i / batchSize + 1}:`, error);
      }
    }
  }, [fetchDetailData]);

  // Move trend calculation functions inside the component
  const calculateTrend = useCallback((current, previous) => {
    if (!current || !previous) return null;
    const trend = current >= previous ? "up" : "down";
    const diff = Math.abs(current - previous);
    const percentage = (diff / previous) * 100;

    return {
      trend,
      value: percentage,
      current,
      previous,
    };
  }, []);

  const calculateRevenueTrend = useCallback(() => {
    if (!stats?.prevPeriodRevenue && stats?.prevPeriodRevenue !== 0) return null;

    // If period is complete, use actual revenue
    // If period is incomplete, use smart projection when available, fallback to simple projection
    const currentRevenue = stats.periodProgress < 100 
      ? (projection?.projectedRevenue || stats.projectedRevenue) 
      : stats.revenue;
    const prevRevenue = stats.prevPeriodRevenue;  // Previous period's total revenue

    if (!currentRevenue || !prevRevenue) return null;

    // Calculate absolute difference percentage
    const trend = currentRevenue >= prevRevenue ? "up" : "down";
    const diff = Math.abs(currentRevenue - prevRevenue);
    const percentage = (diff / prevRevenue) * 100;

    return {
      trend,
      value: percentage,
      current: currentRevenue,
      previous: prevRevenue,
    };
  }, [stats, projection]);

  const calculateOrderTrend = useCallback(() => {
    if (!stats?.prevPeriodOrders) return null;

    // If period is incomplete, use projected orders for fair comparison
    const currentOrders = stats.periodProgress < 100
      ? (projection?.projectedOrders || Math.round(stats.orderCount / (stats.periodProgress / 100)))
      : stats.orderCount;

    return calculateTrend(currentOrders, stats.prevPeriodOrders);
  }, [stats, projection, calculateTrend]);

  const calculateAOVTrend = useCallback(() => {
    if (!stats?.prevPeriodAOV) return null;
    return calculateTrend(stats.averageOrderValue, stats.prevPeriodAOV);
  }, [stats, calculateTrend]);

  // Initial load effect
  useEffect(() => {
    let isMounted = true;

    const loadData = async () => {
      try {
        setLoading(true);
        setStats(null);

        const params =
          timeRange === "custom" ? { startDate, endDate } : { timeRange };

        const response = await acotService.getStats(params);

        if (!isMounted) return;

        setStats(response.stats);
        setLastUpdate(DateTime.now().setZone("America/New_York"));
        setError(null);

        // Start preloading detail data
        preloadDetailData();
      } catch (error) {
        console.error("Error loading data:", error);
        if (isMounted) {
          setError(error.message);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    loadData();
    return () => {
      isMounted = false;
    };
  }, [timeRange, startDate, endDate]);

  // Load smart projection separately
  useEffect(() => {
    let isMounted = true;

    const loadProjection = async () => {
      if (!stats?.periodProgress || stats.periodProgress >= 100) return;

      try {
        setProjectionLoading(true);
        const params =
          timeRange === "custom" ? { startDate, endDate } : { timeRange };

        const response = await acotService.getProjection(params);

        if (!isMounted) return;
        setProjection(response);
      } catch (error) {
        console.error("Error loading projection:", error);
      } finally {
        if (isMounted) {
          setProjectionLoading(false);
        }
      }
    };

    loadProjection();
    return () => {
      isMounted = false;
    };
  }, [timeRange, startDate, endDate, stats?.periodProgress]);

  // Auto-refresh for 'today' view
  useEffect(() => {
    if (timeRange !== "today") return;

    const interval = setInterval(async () => {
      try {
        const [statsResponse, projectionResponse] = await Promise.all([
          acotService.getStats({ timeRange: "today" }),
          acotService.getProjection({ timeRange: "today" }),
        ]);

        setStats(statsResponse.stats);
        setProjection(projectionResponse);
        setLastUpdate(DateTime.now().setZone("America/New_York"));
      } catch (error) {
        console.error("Error auto-refreshing stats:", error);
      }
    }, 60000);

    return () => clearInterval(interval);
  }, [timeRange]);

  // Fetch detail data when a metric is selected (if not already cached)
  useEffect(() => {
    if (!selectedMetric) return;

    // Skip metrics that use stats directly instead of fetched detail data
    if (["brands_categories", "shipping", "peak_hour"].includes(selectedMetric)) {
      return;
    }

    const detailTimeRange = shouldUseLast30Days(selectedMetric)
      ? "last30days"
      : timeRange;
    const cachedData = detailData[selectedMetric] || getCacheData(detailTimeRange, selectedMetric);
    const isLoading = detailDataLoading[selectedMetric];

    if (!cachedData && !isLoading) {
      const isOrderTypeMetric = ["pre_orders", "local_pickup", "on_hold"].includes(selectedMetric);
      fetchDetailData(selectedMetric, isOrderTypeMetric ? selectedMetric : undefined);
    }
  }, [selectedMetric, timeRange, shouldUseLast30Days, detailData, detailDataLoading, getCacheData, fetchDetailData]);

  // Modified getDetailComponent to use memoized components
  const getDetailComponent = useCallback(() => {
    if (!selectedMetric || !stats) {
      return (
        <DashboardEmptyState
          title="No data available"
          description="Try selecting a different time range"
          height="sm"
        />
      );
    }

    const data = detailData[selectedMetric];
    const isLoading = detailDataLoading[selectedMetric];

    if (isLoading) {
      // Show metric-specific loading skeletons
      switch (selectedMetric) {
        case "brands_categories":
        case "shipping":
          return <TableSkeleton rows={8} columns={3} />;
        case "revenue":
        case "orders":
        case "average_order":
          return <ChartSkeleton type="line" height="default" withCard={false} />;
        default:
          return <ChartSkeleton type="bar" height="default" withCard={false} />;
      }
    }

    switch (selectedMetric) {
      case "revenue":
      case "best_revenue_day":
        return <MemoizedRevenueDetails data={data || []} />;
      case "orders":
        return <MemoizedOrdersDetails data={data || []} />;
      case "average_order":
        return (
          <MemoizedAverageOrderDetails
            data={data || []}
            orderCount={stats.orderCount}
          />
        );
      case "refunds":
        return <MemoizedRefundDetails data={data || []} />;
      case "cancellations":
        return <MemoizedCancellationsDetails data={data || []} />;
      case "order_range":
        return <MemoizedOrderRangeDetails data={data || []} />;
      case "pre_orders":
      case "local_pickup":
      case "on_hold":
        return (
          <MemoizedOrderTypeDetails data={data || []} type={selectedMetric} />
        );
      case "brands_categories":
        return <MemoizedBrandsCategoriesDetails data={[stats]} />;
      case "shipping":
        return <MemoizedShippingDetails data={[stats]} timeRange={timeRange} />;
      case "peak_hour":
        if (!["today", "yesterday"].includes(timeRange)) {
          return (
            <div className="text-muted-foreground">
              Peak hour details are only available for single-day periods.
            </div>
          );
        }
        return <MemoizedPeakHourDetails data={[stats]} />;
      default:
        return (
          <div className="text-muted-foreground">Invalid metric selected.</div>
        );
    }
  }, [selectedMetric, stats, timeRange, detailData, detailDataLoading]);

  if (loading && !stats) {
    return (
      <Card className={`w-full ${CARD_STYLES.base}`}>
        <CardHeader className="p-6 pb-2">
          <div className="flex flex-col space-y-2">
            <div className="flex justify-between items-start">
              <div>
                <CardTitle className="text-xl font-semibold text-foreground">
                  {title}
                </CardTitle>
                {description && (
                  <CardDescription className="mt-1 text-muted-foreground">
                    {description}
                  </CardDescription>
                )}
              </div>
              <div className="flex items-center gap-4">
                <Skeleton className="h-4 w-32 bg-muted rounded-sm" />
                <Skeleton className="h-9 w-[130px] bg-muted rounded-md" />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6 pt-0 space-y-4">
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-3 2xl:grid-cols-4 gap-2 md:gap-3">
            {[...Array(12)].map((_, i) => (
              <DashboardStatCardSkeleton key={i} />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className={`w-full h-full ${CARD_STYLES.base}`}>
        <CardHeader className="p-6 pb-4">
          <div className="flex flex-col space-y-2">
            <div className="flex justify-between items-start">
              <div>
                <CardTitle className="text-xl font-semibold text-foreground">
                  {title}
                </CardTitle>
                {description && (
                  <CardDescription className="mt-1 text-muted-foreground">
                    {description}
                  </CardDescription>
                )}
              </div>
              <div className="flex items-center gap-4">
                {lastUpdate && !loading && (
                  <span className="text-sm text-muted-foreground">
                    Last updated: {lastUpdate.toFormat("hh:mm a")}
                  </span>
                )}
                <BusinessRangeSelect value={timeRange} onValueChange={setTimeRange} />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6 pt-0">
          <DashboardErrorState error={`Failed to load stats: ${error}`} className="mx-0 my-0" />
        </CardContent>
      </Card>
    );
  }

  if (!stats) return null;

  const revenueTrend = calculateRevenueTrend();
  const orderTrend = calculateOrderTrend();
  const aovTrend = calculateAOVTrend();
  const isSingleDay = ["today", "yesterday"].includes(timeRange);

  return (
    <Card className={`w-full ${CARD_STYLES.base}`}>
      <CardHeader className="p-6">
        <div className="flex flex-col space-y-2">
          <div className="flex justify-between items-start">
            <div>
              <CardTitle className="text-xl font-semibold text-gray-900 dark:text-gray-100 flex items-baseline gap-1">
                {title}
                {lastUpdate && !loading && (
                <div className="text-xs text-muted-foreground font-medium">
                  Last updated {lastUpdate.toFormat("h:mm a")}
                  {projection?.confidence > 0 && !projectionLoading && (
                    <TooltipProvider>
                      <Tooltip delayDuration={300}>
                        <TooltipTrigger asChild>
                          <span className="ml-1 text-muted-foreground">
                            (
                            <span
                              style={{
                                color: `rgb(${255 * (1 - projection.confidence)}, ${
                                  255 * projection.confidence
                                }, 0)`,
                              }}
                            >
                              {Math.round(projection.confidence * 100)}%
                            </span>
                            )
                          </span>
                        </TooltipTrigger>
                        <TooltipContent className="max-w-[250px]">
                          <p>Confidence level of revenue projection based on historical data patterns</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  )}
                </div>
              )}
              </CardTitle>
         
            </div>
            
            <div className="flex items-center gap-4">
              <BusinessRangeSelect value={timeRange} onValueChange={setTimeRange} />
            </div>
          </div>
        </div>
      </CardHeader>
      <CardContent className="p-6 pt-0">
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-3 2xl:grid-cols-4 gap-2 md:gap-3 dashboard-stagger">
          <DashboardStatCard
            title="Revenue"
            value={formatCurrency(stats?.revenue || 0)}
            subtitle={
              stats?.periodProgress < 100 ? (
                <span className="flex items-center gap-1">
                  <span className="md:hidden">Proj: </span>
                  <span className="hidden md:inline">Projected: </span>
                  {projectionLoading ? (
                    <Skeleton className="h-4 w-16" />
                  ) : (
                    formatCurrency(projection?.projectedRevenue || stats.projectedRevenue)
                  )}
                </span>
              ) : (
                <span>Previous: {formatCurrency(stats?.prevPeriodRevenue || 0)}</span>
              )
            }
            trend={
              projectionLoading && stats?.periodProgress < 100
                ? undefined
                : revenueTrend?.value
                  ? { value: revenueTrend.trend === "up" ? revenueTrend.value : -revenueTrend.value, moreIsBetter: true }
                  : undefined
            }
            icon={DollarSign}
            iconColor="green"
            onClick={() => setSelectedMetric("revenue")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Orders"
            value={stats?.orderCount}
            subtitle={`${stats?.itemCount} total items`}
            trend={
              projectionLoading && stats?.periodProgress < 100
                ? undefined
                : orderTrend?.value
                  ? { value: orderTrend.trend === "up" ? orderTrend.value : -orderTrend.value, moreIsBetter: true }
                  : undefined
            }
            icon={ShoppingCart}
            iconColor="blue"
            onClick={() => setSelectedMetric("orders")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="AOV"
            value={stats?.averageOrderValue?.toFixed(2)}
            valuePrefix="$"
            subtitle={`${stats?.averageItemsPerOrder?.toFixed(1)} items per order`}
            trend={aovTrend?.value ? { value: aovTrend.trend === "up" ? aovTrend.value : -aovTrend.value, moreIsBetter: true } : undefined}
            icon={CircleDollarSign}
            iconColor="purple"
            onClick={() => setSelectedMetric("average_order")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Brands"
            value={stats?.brands?.total || 0}
            subtitle={`${stats?.categories?.total || 0} categories`}
            icon={Tags}
            iconColor="indigo"
            onClick={() => setSelectedMetric("brands_categories")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Shipped Orders"
            value={stats?.shipping?.shippedCount || 0}
            subtitle={`${stats?.shipping?.locations?.total || 0} locations`}
            icon={Package}
            iconColor="teal"
            onClick={() => setSelectedMetric("shipping")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Pre-Orders"
            value={
              stats?.orderCount > 0
                ? ((stats?.orderTypes?.preOrders?.count / stats?.orderCount) * 100).toFixed(1)
                : "0"
            }
            valueSuffix="%"
            subtitle={`${stats?.orderTypes?.preOrders?.count || 0} orders`}
            icon={Clock}
            iconColor="yellow"
            onClick={() => setSelectedMetric("pre_orders")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Local Pickup"
            value={
              stats?.orderCount > 0
                ? ((stats?.orderTypes?.localPickup?.count / stats?.orderCount) * 100).toFixed(1)
                : "0"
            }
            valueSuffix="%"
            subtitle={`${stats?.orderTypes?.localPickup?.count || 0} orders`}
            icon={Map}
            iconColor="cyan"
            onClick={() => setSelectedMetric("local_pickup")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="On Hold"
            value={
              stats?.orderCount > 0
                ? ((stats?.orderTypes?.heldItems?.count / stats?.orderCount) * 100).toFixed(1)
                : "0"
            }
            valueSuffix="%"
            subtitle={`${stats?.orderTypes?.heldItems?.count || 0} orders`}
            icon={AlertCircle}
            iconColor="red"
            onClick={() => setSelectedMetric("on_hold")}
            loading={loading || !stats}
          />

          {isSingleDay ? (
            <DashboardStatCard
              title="Peak Hour"
              value={stats?.peakOrderHour?.displayHour || "N/A"}
              subtitle={stats?.peakOrderHour ? `${stats?.peakOrderHour.count} orders` : undefined}
              icon={Clock}
              iconColor="pink"
              onClick={() => setSelectedMetric("peak_hour")}
              loading={loading || !stats}
            />
          ) : (
            <DashboardStatCard
              title="Best Revenue Day"
              value={stats?.bestRevenueDay?.amount?.toFixed(2) || "N/A"}
              valuePrefix="$"
              subtitle={
                stats?.bestRevenueDay?.displayDate
                  ? new Date(stats?.bestRevenueDay.displayDate).toLocaleDateString("en-US", {
                      month: "short",
                      day: "numeric",
                    })
                  : "N/A"
              }
              icon={TrendingUp}
              iconColor="emerald"
              loading={loading || !stats}
            />
          )}

          <DashboardStatCard
            title="Refunds"
            value={stats?.refunds?.total?.toFixed(2) || "0.00"}
            valuePrefix="$"
            subtitle={`${stats?.refunds?.count || 0} refund orders`}
            icon={RefreshCcw}
            iconColor="orange"
            onClick={() => setSelectedMetric("refunds")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Cancellations"
            value={stats?.canceledOrders?.total?.toFixed(2) || "0.00"}
            valuePrefix="$"
            subtitle={`${stats?.canceledOrders?.count || 0} canceled orders`}
            icon={XCircle}
            iconColor="rose"
            onClick={() => setSelectedMetric("cancellations")}
            loading={loading || !stats}
          />

          <DashboardStatCard
            title="Order Range"
            value={stats?.orderValueRange?.largest?.toFixed(2) || "0.00"}
            valuePrefix="$"
            subtitle={`Min: $${stats?.orderValueRange?.smallest?.toFixed(2) || "0.00"}`}
            icon={TrendingUp}
            iconColor="violet"
            onClick={() => setSelectedMetric("order_range")}
            loading={loading || !stats}
          />
        </div>

        <DetailDialog
          open={!!selectedMetric}
          onOpenChange={() => setSelectedMetric(null)}
          title={
            selectedMetric
              ? `${selectedMetric
                  .split("_")
                  .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                  .join(" ")} Details`
              : ""
          }
        >
          {getDetailComponent()}
        </DetailDialog>
      </CardContent>
    </Card>
  );
};

// Export components and utilities for MiniStatCards
export {
  RevenueDetails,
  OrdersDetails,
  AverageOrderDetails,
  ShippingDetails,
  DetailDialog,
  formatCurrency,
  formatPercentage,
};

export default StatCards;
