import React, { useState, useEffect, useCallback, Suspense, memo } from "react";
import axios from "axios";
import { acotService } from "@/services/dashboard/acotService";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/dashboard/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/dashboard/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/dashboard/ui/dialog";
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
  Legend,
  PieChart,
  Pie,
  Cell,
} 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,
  TrendingDown,
  ArrowDown,
  ArrowUp,
  AlertCircle,
  Box,
  RefreshCcw,
  CircleDollarSign,
  MapPin,
  Info,
  Loader2,
} from "lucide-react";
import { DateTime } from "luxon";
import { TIME_RANGES } from "@/lib/dashboard/constants";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/dashboard/ui/table";
import { Skeleton } from "@/components/dashboard/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/dashboard/ui/alert";
import { Button } from "@/components/dashboard/ui/button";
import { Progress } from "@/components/dashboard/ui/progress";
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from "@/components/dashboard/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="bg-background border rounded-lg shadow-lg p-3">
                  <p className="font-medium">
                    {DateTime.fromISO(label).toFormat("LLL d")}
                  </p>
                  {payload.map((entry, i) => (
                    <p key={i} className="text-sm">
                      {entry.name}: {valueFormatter(entry.value)}
                    </p>
                  ))}
                </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="
            "
          />
        </div>
      )}
    </>
  );
};

// Add additional chart components
const BarList = ({ data, valueFormatter = (v) => v }) => (
  <div className="space-y-2">
    {data.map((item, i) => (
      <div key={i} className="flex items-center gap-2">
        <div className="flex-1 flex items-center justify-between">
          <span className="font-medium">{item.name}</span>
          <span>{valueFormatter(item.value)}</span>
        </div>
        <div className="w-32 h-2 bg-muted rounded-full overflow-hidden">
          <div
            className="h-full bg-primary"
            style={{ width: `${item.percentage}%` }}
          />
        </div>
      </div>
    ))}
  </div>
);

const StatGrid = ({ stats }) => (
  <div className="grid grid-cols-2 gap-4">
    {stats.map((stat, i) => (
      <Card key={i} className="p-4">
        <div className="text-sm text-muted-foreground">{stat.label}</div>
        <div className="text-2xl font-bold mt-1">{stat.value}</div>
        {stat.description && (
          <div className="text-sm text-muted-foreground mt-1">
            {stat.description}
          </div>
        )}
      </Card>
    ))}
  </div>
);

// Add detail view components
const AverageOrderDetails = ({ data, orderCount }) => {
  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.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.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,
    count: day.count,
    value: day.value,
    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>
    );

  const hourlyData =
    data[0]?.hourlyOrders?.map((count, hour) => ({
      timestamp: hour, // Use raw hour number for x-axis
      orders: 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="bg-background border rounded-lg shadow-lg p-3">
                  <p className="font-medium">{time}</p>
                  <p className="text-sm">Orders: {payload[0].value}</p>
                </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="bg-background border rounded-lg shadow-lg p-3">
                        <p className="font-medium">{data.range}</p>
                        <p className="text-sm">
                          Orders: {data.count.toLocaleString()}
                        </p>
                        <p className="text-sm">
                          Revenue: {formatCurrency(data.total)}
                        </p>
                        <p className="text-sm">
                          % of Orders: {data.percentage}%
                        </p>
                        <p className="text-sm">
                          % of Revenue: {data.revenuePercentage}%
                        </p>
                      </div>
                    );
                  }}
                />
                <Bar
                  dataKey="percentage"
                  name="Percentage of Orders"
                  fill="hsl(262.1 83.3% 57.8%)"
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      )}
    </div>
  );
};

const StatCard = ({
  title,
  value,
  description,
  trend,
  trendValue,
  valuePrefix = "",
  valueSuffix = "",
  trendPrefix = "",
  trendSuffix = "",
  className = "",
  colorClass = "text-gray-900 dark:text-gray-100",
  titleClass,
  descriptionClass,
  icon: Icon,
  iconColor = "text-gray-500",
  iconBackground,
  onClick,
  info,
  onDetailsClick,
  isLoading = false,
  progress,
  variant = "default",
  background
}) => {
  const variants = {
    default: "bg-white dark:bg-gray-900/60",
    mini: background || "bg-gradient-to-br from-gray-800 to-gray-900 backdrop-blur-md"
  };

  const titleVariants = {
    default: "text-sm font-medium text-gray-600 dark:text-gray-300",
    mini: titleClass || "text-sm font-bold text-gray-100"
  };

  const valueVariants = {
    default: "text-2xl font-bold",
    mini: "text-3xl font-extrabold"
  };

  const descriptionVariants = {
    default: "text-sm text-muted-foreground",
    mini: descriptionClass || "text-sm font-semibold text-gray-200"
  };

  const trendColorVariants = {
    default: {
      up: "text-emerald-600 dark:text-emerald-400",
      down: "text-rose-600 dark:text-rose-400"
    },
    mini: {
      up: "text-emerald-900",
      down: "text-rose-900"
    }
  };

  const iconVariants = {
    default: iconColor,
    mini: iconColor || colorClass
  };

  return (
    <Card
      className={`${className} ${variants[variant]} ${
        onClick || onDetailsClick
          ? "cursor-pointer transition-all hover:brightness-110"
          : ""
      }`}
      onClick={onDetailsClick || onClick}
    >
      <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
        <div className="flex items-center gap-2">
          <CardTitle className={titleVariants[variant]}>
            {title}
          </CardTitle>
          {info && (
            <Info
              className={`w-4 h-4 ${variant === 'mini' ? 'text-gray-200' : 'text-muted-foreground'} cursor-help`}
              title={info}
            />
          )}
        </div>
        {Icon && (
          <div className={`${variant === 'mini' ? 'relative p-2' : ''}`}>
            {variant === 'mini' && iconBackground && (
              <div 
                className={`absolute inset-0 rounded-full ${iconBackground}`}
              />
            )}
            <Icon className={`h-5 w-5 ${iconVariants[variant]} relative`} />
          </div>
        )}
      </CardHeader>
      <CardContent className="p-4 pt-0">
        {isLoading ? (
          <>
            <Skeleton className="h-8 w-32 mb-2 bg-muted rounded-sm" />
            <Skeleton className="h-4 w-24 bg-muted rounded-sm" />
          </>
        ) : (
          <div className="space-y-2">
            <div>
              <div className={`${valueVariants[variant]} ${colorClass}`}>
                {valuePrefix}
                {value}
                {valueSuffix}
              </div>
              {description && (
                <div className={`mt-2 items-center justify-between flex ${descriptionVariants[variant]}`}>
                  {description}
                  {trend && (
                    <span
                      className={`flex items-center gap-0 px-1 py-0.5 ${
                        variant === 'mini' ? 'rounded-full' : ''
                      } ${
                        variant === 'mini' ? (
                          trend === 'up'
                            ? 'text-sm bg-emerald-300 text-emerald-900'
                            : 'text-sm bg-rose-300 text-rose-900'
                        ) : ''
                      } ${trendColorVariants[variant][trend]}`}
                    >
                      {trend === "up" ? (
                        <ArrowUp className="w-4 h-4" />
                      ) : (
                        <ArrowDown className="w-4 h-4" />
                      )}
                      {trendPrefix}
                      {trendValue}
                      {trendSuffix}
                    </span>
                  )}
                </div>
              )}
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

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

// Add this before the StatCards component
const useDebouncedEffect = (effect, deps, delay) => {
  useEffect(() => {
    const handler = setTimeout(() => effect(), delay);
    return () => clearTimeout(handler);
  }, [...deps, delay]);
};

// Add these skeleton components near the top of the file
const SkeletonCard = () => (
  <Card className="relative bg-white dark:bg-gray-900/60 backdrop-blur-sm">
    <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
      <div className="flex items-center gap-2">
        <Skeleton className="h-4 w-24 bg-muted" />
        <Skeleton className="h-4 w-4 rounded-full bg-muted" />
      </div>
      <Skeleton className="h-4 w-4 rounded-full bg-muted" />
    </CardHeader>
    <CardContent className="p-4 pt-0">
      <div className="space-y-2">
        <Skeleton className="h-8 w-24 bg-muted" />
        <div className="flex items-center gap-2">
          <Skeleton className="h-4 w-32 bg-muted" />
          <Skeleton className="h-4 w-16 bg-muted rounded-md" />
        </div>
      </div>
    </CardContent>
  </Card>
);

const SkeletonChart = ({ type = "line" }) => (
  <div className="h-[400px] w-full bg-white dark:bg-gray-900/60 backdrop-blur-sm rounded-lg p-6">
    <div className="h-full relative">
      {/* Grid lines */}
      {[...Array(5)].map((_, i) => (
        <div
          key={i}
          className="absolute w-full h-px bg-muted"
          style={{ top: `${(i + 1) * 20}%` }}
        />
      ))}
      {/* Y-axis labels */}
      <div className="absolute left-0 top-0 bottom-0 w-8 flex flex-col justify-between py-4">
        {[...Array(5)].map((_, i) => (
          <Skeleton key={i} className="h-3 w-6 bg-muted rounded-sm" />
        ))}
      </div>
      {/* X-axis labels */}
      <div className="absolute left-8 right-4 bottom-0 flex justify-between">
        {[...Array(6)].map((_, i) => (
          <Skeleton key={i} className="h-3 w-8 bg-muted rounded-sm" />
        ))}
      </div>
      {type === "bar" ? (
        <div className="absolute inset-x-8 bottom-6 top-4 flex items-end justify-between gap-1">
          {[...Array(24)].map((_, i) => (
            <div
              key={i}
              className="w-2 bg-muted rounded-sm"
              style={{ height: `${Math.random() * 80 + 10}%` }}
            />
          ))}
        </div>
      ) : (
        <div className="absolute inset-x-8 bottom-6 top-4">
          <div className="h-full w-full relative">
            <div
              className="absolute inset-0 bg-muted rounded-sm"
              style={{
                opacity: 0.5,
                clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
              }}
            />
          </div>
        </div>
      )}
    </div>
  </div>
);

const SkeletonTable = ({ rows = 8 }) => (
  <div className="rounded-lg border bg-white dark:bg-gray-900/60 backdrop-blur-sm">
    <Table>
      <TableHeader>
        <TableRow className="dark:border-gray-800">
          <TableHead>
            <Skeleton className="h-4 w-32 bg-muted rounded-sm" />
          </TableHead>
          <TableHead className="text-right">
            <Skeleton className="h-4 w-24 ml-auto bg-muted rounded-sm" />
          </TableHead>
          <TableHead className="text-right">
            <Skeleton className="h-4 w-24 ml-auto bg-muted rounded-sm" />
          </TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {[...Array(rows)].map((_, i) => (
          <TableRow key={i} className="dark:border-gray-800">
            <TableCell>
              <Skeleton className="h-4 w-48 bg-muted rounded-sm" />
            </TableCell>
            <TableCell className="text-right">
              <Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" />
            </TableCell>
            <TableCell className="text-right">
              <Skeleton className="h-4 w-16 ml-auto bg-muted rounded-sm" />
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </div>
);

const SummaryStats = memo(({ stats = {}, projection = null, projectionLoading = false }) => {
  const {
    totalRevenue = 0,
    totalOrders = 0,
    avgOrderValue = 0,
    bestDay = null,
    prevRevenue = 0,
    prevOrders = 0,
    prevAvgOrderValue = 0,
    periodProgress = 100
  } = stats;

  // Calculate projected values when period is incomplete
  const currentRevenue = periodProgress < 100 ? (projection?.projectedRevenue || totalRevenue) : totalRevenue;
  const revenueTrend = currentRevenue >= prevRevenue ? "up" : "down";
  const revenueDiff = Math.abs(currentRevenue - prevRevenue);
  const revenuePercentage = (revenueDiff / prevRevenue) * 100;

  // Calculate order trends
  const currentOrders = periodProgress < 100 ? Math.round(totalOrders * (100 / periodProgress)) : totalOrders;
  const ordersTrend = currentOrders >= prevOrders ? "up" : "down";
  const ordersDiff = Math.abs(currentOrders - prevOrders);
  const ordersPercentage = (ordersDiff / prevOrders) * 100;

  // Calculate AOV trends
  const currentAOV = currentOrders ? currentRevenue / currentOrders : avgOrderValue;
  const aovTrend = currentAOV >= prevAvgOrderValue ? "up" : "down";
  const aovDiff = Math.abs(currentAOV - prevAvgOrderValue);
  const aovPercentage = (aovDiff / prevAvgOrderValue) * 100;

  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4 max-w-3xl">
      <StatCard
        title="Total Revenue"
        value={formatCurrency(totalRevenue, false)}
        description={
          periodProgress < 100 
            ? `Projected: ${formatCurrency(currentRevenue, false)}`
            : `Previous: ${formatCurrency(prevRevenue, false)}`
        }
        trend={projectionLoading && periodProgress < 100 ? undefined : revenueTrend}
        trendValue={projectionLoading && periodProgress < 100 ? null : formatPercentage(revenuePercentage)}
        info="Total revenue for the selected period"
        colorClass="text-green-600 dark:text-green-400"
      />

      <StatCard
        title="Total Orders"
        value={totalOrders.toLocaleString()}
        description={
          periodProgress < 100 
            ? `Projected: ${currentOrders.toLocaleString()}`
            : `Previous: ${prevOrders.toLocaleString()}`
        }
        trend={projectionLoading && periodProgress < 100 ? undefined : ordersTrend}
        trendValue={projectionLoading && periodProgress < 100 ? null : formatPercentage(ordersPercentage)}
        info="Total number of orders for the selected period"
        colorClass="text-blue-600 dark:text-blue-400"
      />

      <StatCard
        title="AOV"
        value={formatCurrency(avgOrderValue)}
        description={
          periodProgress < 100 
            ? `Projected: ${formatCurrency(currentAOV)}`
            : `Previous: ${formatCurrency(prevAvgOrderValue)}`
        }
        trend={projectionLoading && periodProgress < 100 ? undefined : aovTrend}
        trendValue={projectionLoading && periodProgress < 100 ? null : formatPercentage(aovPercentage)}
        info="Average value per order for the selected period"
        colorClass="text-purple-600 dark:text-purple-400"
      />

      <StatCard
        title="Best Day"
        value={formatCurrency(bestDay?.revenue || 0, false)}
        description={
          bestDay?.timestamp
            ? `${new Date(bestDay.timestamp).toLocaleDateString("en-US", {
                month: "short",
                day: "numeric",
              })} - ${bestDay.orders} orders`
            : "No data"
        }
        info="Day with highest revenue in the selected period"
        colorClass="text-orange-600 dark:text-orange-400"
      />
    </div>
  );
});

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 [dateRange, setDateRange] = useState(null);
  const [detailDataLoading, setDetailDataLoading] = useState({});
  const [detailData, setDetailData] = useState({});
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [projection, setProjection] = useState(null);
  const [projectionLoading, setProjectionLoading] = useState(false);
  const { setCacheData, getCacheData, clearCache } = 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) {
        console.log(`Using cached data for ${metric}`);
        setDetailData((prev) => ({ ...prev, [metric]: cachedData }));
        return cachedData;
      }

      console.log(`Fetching detail data for ${metric}`);
      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;
          console.log("Fetched order range data:", data);
          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

    console.log('[RevenueTrend Debug]', {
      periodProgress: stats.periodProgress,
      currentRevenue,
      smartProjection: projection?.projectedRevenue,
      simpleProjection: stats.projectedRevenue,
      actualRevenue: stats.revenue,
      prevRevenue,
      isProjected: stats.periodProgress < 100
    });

    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;

    console.log('[RevenueTrend Result]', {
      trend,
      percentage,
      calculation: `(|${currentRevenue} - ${prevRevenue}| / ${prevRevenue}) * 100 = ${percentage}%`
    });

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

  const calculateOrderTrend = useCallback(() => {
    if (!stats?.prevPeriodOrders) return null;
    return calculateTrend(stats.orderCount, stats.prevPeriodOrders);
  }, [stats, 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;

        setDateRange(response.timeRange);
        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);
          setIsInitialLoad(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]);

  // Modified AsyncDetailView component
  const AsyncDetailView = memo(({ metric, type, orderCount }) => {
    const detailTimeRange = shouldUseLast30Days(metric)
      ? "last30days"
      : timeRange;
    const cachedData =
      detailData[metric] || getCacheData(detailTimeRange, metric);
    const isLoading = detailDataLoading[metric];
    const isOrderTypeMetric = [
      "pre_orders",
      "local_pickup",
      "on_hold",
    ].includes(metric);

    useEffect(() => {
      let isMounted = true;

      const loadData = async () => {
        if (!cachedData && !isLoading) {
          // Pass type only for order type metrics
          const data = await fetchDetailData(
            metric,
            isOrderTypeMetric ? metric : undefined
          );
          if (!isMounted) return;
          // The state updates are handled in fetchDetailData
        }
      };

      loadData();
      return () => {
        isMounted = false;
      };
    }, [metric, timeRange, isOrderTypeMetric]); // Depend on isOrderTypeMetric

    if (isLoading || (!cachedData && !error)) {
      switch (metric) {
        case "revenue":
        case "orders":
        case "average_order":
          return <SkeletonChart type="line" />;
        case "refunds":
        case "cancellations":
        case "order_range":
        case "pre_orders":
        case "local_pickup":
        case "on_hold":
          return <SkeletonChart type="bar" />;
        case "brands_categories":
        case "shipping":
          return <SkeletonTable rows={8} />;
        case "peak_hour":
          return <SkeletonChart type="bar" />;
        default:
          return <div className="text-muted-foreground">Loading...</div>;
      }
    }

    if (!cachedData && error) {
      return (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Error</AlertTitle>
          <AlertDescription>Failed to load stats: {error}</AlertDescription>
        </Alert>
      );
    }

    if (!cachedData)
      return (
        <div className="text-muted-foreground">
          No data available for the selected time range.
        </div>
      );

    switch (metric) {
      case "revenue":
        return <MemoizedRevenueDetails data={cachedData} />;
      case "orders":
        return <MemoizedOrdersDetails data={cachedData} />;
      case "average_order":
        return (
          <MemoizedAverageOrderDetails
            data={cachedData}
            orderCount={orderCount}
          />
        );
      case "refunds":
        return <MemoizedRefundDetails data={cachedData} />;
      case "cancellations":
        return <MemoizedCancellationsDetails data={cachedData} />;
      case "order_range":
        return <MemoizedOrderRangeDetails data={cachedData} />;
      case "pre_orders":
      case "local_pickup":
      case "on_hold":
        return <MemoizedOrderTypeDetails data={cachedData} type={type} />;
      default:
        return (
          <div className="text-muted-foreground">Invalid metric selected.</div>
        );
    }
  });

  AsyncDetailView.displayName = "AsyncDetailView";

  // Modified getDetailComponent to use memoized components
  const getDetailComponent = useCallback(() => {
    if (!selectedMetric || !stats) {
      return (
        <div className="text-muted-foreground">
          No data available for the selected time range.
        </div>
      );
    }

    const data = detailData[selectedMetric];
    const isLoading = detailDataLoading[selectedMetric];
    const isOrderTypeMetric = [
      "pre_orders",
      "local_pickup",
      "on_hold",
    ].includes(selectedMetric);

    if (isLoading) {
      return <SkeletonChart />;
    }

    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 bg-white dark:bg-gray-900/60 backdrop-blur-sm">
        <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-gray-900 dark:text-gray-100">
                  {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) => (
              <SkeletonCard key={i} />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="w-full bg-white dark:bg-gray-900/60 backdrop-blur-sm h-full">
        <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-gray-900 dark:text-gray-100">
                  {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>
                )}
                <Select value={timeRange} onValueChange={setTimeRange}>
                  <SelectTrigger className="w-[130px] h-9">
                    <SelectValue placeholder="Select time range" />
                  </SelectTrigger>
                  <SelectContent>
                    {TIME_RANGES.map((range) => (
                      <SelectItem key={range.value} value={range.value}>
                        {range.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6 pt-0">
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Error</AlertTitle>
            <AlertDescription>Failed to load stats: {error}</AlertDescription>
          </Alert>
        </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 bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <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">
                {title}
              </CardTitle>
              {lastUpdate && !loading && (
                <CardDescription className="text-xs">
                  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>
                  )}
                </CardDescription>
              )}
            </div>
            
            <div className="flex items-center gap-4">
              <Select value={timeRange} onValueChange={setTimeRange}>
                <SelectTrigger className="w-[130px] h-9">
                  <SelectValue placeholder="Select time range" />
                </SelectTrigger>
                <SelectContent>
                  {TIME_RANGES.map((range) => (
                    <SelectItem key={range.value} value={range.value}>
                      {range.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </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">
          <StatCard
            title="Total Revenue"
            value={formatCurrency(stats?.revenue || 0)}
            description={
              <div className="flex justify-between items-center w-full">
                <div className="flex flex-col">
                  {stats?.periodProgress < 100 ? (
                    <div className="flex items-center gap-1">
                      <span className="md:hidden">Proj: </span>
                      <span className="hidden md:inline">Projected: </span>
                      {projectionLoading ? (
                        <div className="w-20">
                          <Skeleton className="h-4 w-15" />
                        </div>
                      ) : (
                        formatCurrency(
                          projection?.projectedRevenue || stats.projectedRevenue
                        )
                      )}
                    </div>
                  ) : (
                    <div className="flex items-center gap-1">
                      <span className="md:hidden">Prev: </span>
                      <span className="hidden md:inline">Previous: </span>
                      {formatCurrency(stats.prevPeriodRevenue || 0)}
                    </div>
                  )}
                </div>
              </div>
            }
            progress={
              stats?.periodProgress < 100 ? stats.periodProgress : undefined
            }
            trend={projectionLoading && stats?.periodProgress < 100 ? undefined : revenueTrend?.trend}
            trendValue={
              projectionLoading && stats?.periodProgress < 100 ? (
                <div className="flex items-center gap-1">
                  <Skeleton className="h-4 w-4 rounded-full" />
                  <Skeleton className="h-4 w-8 inline-block" />
                </div>
              ) : revenueTrend?.value ? (
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <span>{formatPercentage(revenueTrend.value)}</span>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>Previous Period: {formatCurrency(stats.prevPeriodRevenue || 0)}</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              ) : null
            }
            colorClass="text-green-600 dark:text-green-400"
            icon={DollarSign}
            iconColor="text-green-500"
            iconBackground="bg-green-500"
            onDetailsClick={() => setSelectedMetric("revenue")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Orders"
            value={stats?.orderCount}
            description={`${stats?.itemCount} total items`}
            trend={orderTrend?.trend}
            trendValue={
              orderTrend?.value ? formatPercentage(orderTrend.value) : null
            }
            colorClass="text-blue-600 dark:text-blue-400"
            icon={ShoppingCart}
            iconColor="text-blue-500"
            iconBackground="bg-blue-500"
            onDetailsClick={() => setSelectedMetric("orders")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Average Order Value"
            value={stats?.averageOrderValue?.toFixed(2)}
            valuePrefix="$"
            description={`${stats?.averageItemsPerOrder?.toFixed(
              1
            )} items per order`}
            trend={aovTrend?.trend}
            trendValue={
              aovTrend?.value ? formatPercentage(aovTrend.value) : null
            }
            colorClass="text-purple-600 dark:text-purple-400"
            icon={CircleDollarSign}
            iconColor="text-purple-500"
            iconBackground="bg-purple-500"
            onDetailsClick={() => setSelectedMetric("average_order")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Brands & Categories"
            value={stats?.brands?.total || 0}
            description={`${stats?.categories?.total || 0} categories`}
            colorClass="text-indigo-600 dark:text-indigo-400"
            icon={Tags}
            iconColor="text-indigo-500"
            iconBackground="bg-indigo-500"
            onDetailsClick={() => setSelectedMetric("brands_categories")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Shipped Orders"
            value={stats?.shipping?.shippedCount || 0}
            description={`${stats?.shipping?.locations?.total || 0} locations`}
            colorClass="text-teal-600 dark:text-teal-400"
            icon={Package}
            iconColor="text-teal-500"
            iconBackground="bg-teal-500"
            onDetailsClick={() => setSelectedMetric("shipping")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Pre-Orders"
            value={
              (
                (stats?.orderTypes?.preOrders?.count / stats?.orderCount) *
                100
              )?.toFixed(1) || "0"
            }
            valueSuffix="%"
            description={`${stats?.orderTypes?.preOrders?.count || 0} orders`}
            colorClass="text-yellow-600 dark:text-yellow-400"
            icon={Clock}
            iconColor="text-yellow-500"
            iconBackground="bg-yellow-500"
            onDetailsClick={() => setSelectedMetric("pre_orders")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Local Pickup"
            value={
              (
                (stats?.orderTypes?.localPickup?.count / stats?.orderCount) *
                100
              )?.toFixed(1) || "0"
            }
            valueSuffix="%"
            description={`${stats?.orderTypes?.localPickup?.count || 0} orders`}
            colorClass="text-cyan-600 dark:text-cyan-400"
            icon={Map}
            iconColor="text-cyan-500"
            iconBackground="bg-cyan-500"
            onDetailsClick={() => setSelectedMetric("local_pickup")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="On Hold"
            value={
              (
                (stats?.orderTypes?.heldItems?.count / stats?.orderCount) *
                100
              )?.toFixed(1) || "0"
            }
            valueSuffix="%"
            description={`${stats?.orderTypes?.heldItems?.count || 0} orders`}
            colorClass="text-red-600 dark:text-red-400"
            icon={AlertCircle}
            iconColor="text-red-500"
            iconBackground="bg-red-500"
            onDetailsClick={() => setSelectedMetric("on_hold")}
            isLoading={loading || !stats}
          />

          {isSingleDay ? (
            <StatCard
              title="Peak Hour"
              value={stats?.peakOrderHour?.displayHour || "N/A"}
              description={
                stats?.peakOrderHour
                  ? `${stats?.peakOrderHour.count} orders`
                  : null
              }
              colorClass="text-pink-600 dark:text-pink-400"
              icon={Clock}
              iconColor="text-pink-500"
              iconBackground="bg-pink-500"
              onDetailsClick={() => setSelectedMetric("peak_hour")}
              isLoading={loading || !stats}
            />
          ) : (
            <StatCard
              title="Best Revenue Day"
              value={stats?.bestRevenueDay?.amount?.toFixed(2) || "N/A"}
              valuePrefix="$"
              description={
                stats?.bestRevenueDay?.displayDate
                  ? new Date(
                      stats?.bestRevenueDay.displayDate
                    ).toLocaleDateString("en-US", {
                      month: "short",
                      day: "numeric",
                    })
                  : "N/A"
              }
              colorClass="text-emerald-600 dark:text-emerald-400"
              icon={TrendingUp}
              iconColor="text-emerald-500"
              iconBackground="bg-emerald-500"
              isLoading={loading || !stats}
            />
          )}

          <StatCard
            title="Refunds"
            value={stats?.refunds?.total?.toFixed(2) || "0.00"}
            valuePrefix="$"
            description={`${stats?.refunds?.count || 0} refund orders`}
            colorClass="text-orange-600 dark:text-orange-400"
            icon={RefreshCcw}
            iconColor="text-orange-500"
            iconBackground="bg-orange-500"
            onDetailsClick={() => setSelectedMetric("refunds")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Cancellations"
            value={stats?.canceledOrders?.total?.toFixed(2) || "0.00"}
            valuePrefix="$"
            description={`${stats?.canceledOrders?.count || 0} canceled orders`}
            colorClass="text-rose-600 dark:text-rose-400"
            icon={XCircle}
            iconColor="text-rose-500"
            iconBackground="bg-rose-500"
            onDetailsClick={() => setSelectedMetric("cancellations")}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Order Range"
            value={stats?.orderValueRange?.largest?.toFixed(2) || "0.00"}
            valuePrefix="$"
            description={`Min: $${
              stats?.orderValueRange?.smallest?.toFixed(2) || "0.00"
            }`}
            colorClass="text-violet-600 dark:text-violet-400"
            icon={TrendingUp}
            iconColor="text-violet-500"
            iconBackground="bg-violet-500"
            onDetailsClick={() => setSelectedMetric("order_range")}
            isLoading={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,
  StatCard,
  DetailDialog,
  formatCurrency,
  formatPercentage,
  SkeletonCard,
  SkeletonChart,
  SkeletonTable,
};

export default StatCards;
