import React, { useState, useEffect, useCallback, Suspense, memo } from 'react';
import axios from 'axios';
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  PieChart,
  Pie,
  Cell
} 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/constants";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";

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 hourNum = parseInt(hour);
  if (hourNum === 0) return "12am";
  if (hourNum === 12) return "12pm";
  if (hourNum > 12) return `${hourNum - 12}pm`;
  return `${hourNum}am`;
};

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

  return (
    <div className="h-[400px] w-full">
      <ResponsiveContainer width="100%" height={height}>
        <ChartComponent data={data} margin={{ top: 10, right: 30, 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"
          />
          <Tooltip
            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 />
          <DataComponent
            type="monotone"
            dataKey={dataKey}
            name={name}
            stroke={color}
            fill={color}
            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-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));

  // Calculate summary statistics
  const totalRevenue = chartData.reduce((sum, day) => sum + day.revenue, 0);
  const averageDailyRevenue = totalRevenue / chartData.length;
  const maxRevenue = Math.max(...chartData.map(day => day.revenue));
  const minRevenue = Math.min(...chartData.map(day => day.revenue));

  return (
    <div className="space-y-8">
      <TimeSeriesChart
        data={chartData}
        dataKey="revenue"
        name="Revenue"
        color="hsl(142.1 76.2% 36.3%)"
        valueFormatter={(value) => formatCurrency(value)}
        height={400}
      />
      
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title="Total Revenue"
          value={formatCurrency(totalRevenue)}
          description={`${chartData.length} days`}
          colorClass="text-green-600 dark:text-green-400"
          icon={DollarSign}
        />
        <StatCard
          title="Average Daily Revenue"
          value={formatCurrency(averageDailyRevenue)}
          description="per day"
          colorClass="text-green-600 dark:text-green-400"
          icon={TrendingUp}
        />
        <StatCard
          title="Highest Day"
          value={formatCurrency(maxRevenue)}
          description={chartData.find(d => d.revenue === maxRevenue)?.date}
          colorClass="text-green-600 dark:text-green-400"
          icon={ArrowUp}
        />
        <StatCard
          title="Lowest Day"
          value={formatCurrency(minRevenue)}
          description={chartData.find(d => d.revenue === minRevenue)?.date}
          colorClass="text-green-600 dark:text-green-400"
          icon={ArrowDown}
        />
      </div>
    </div>
  );
};

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 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)}
      />
      <div className="mt-8">
        <StatGrid
          stats={[
            {
              label: "Average Items per Order",
              value: data[0]?.averageItemsPerOrder?.toFixed(1) || "0",
              description: "items"
            },
            {
              label: "Total Orders",
              value: orderCount?.toLocaleString() || "0",
              description: "orders"
            }
          ]}
        />
      </div>
    </>
  );
};

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,
      percentage: (count / cancelData.count) * 100
    }))
    .sort((a, b) => b.count - a.count);

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title="Total Cancellations"
          value={formatCurrency(cancelData.total)}
          description={`${cancelData.count.toLocaleString()} orders`}
          colorClass="text-rose-600 dark:text-rose-400"
          icon={XCircle}
        />
        <StatCard
          title="Average Cancellation"
          value={formatCurrency(cancelData.total / (cancelData.count || 1))}
          description="per order"
          colorClass="text-rose-600 dark:text-rose-400"
          icon={DollarSign}
        />
      </div>

      <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>
                  <TableHead className="text-right">% of Total</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>
                    <TableCell className="text-right">{item.percentage.toFixed(1)}%</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 brandData = data[0]?.brands?.list?.map(brand => ({
    name: brand.name,
    count: brand.count,
    revenue: brand.revenue,
    percentage: (brand.count / data[0]?.itemCount * 100) || 0
  }))?.sort((a, b) => b.count - a.count) || [];

  const categoryData = data[0]?.categories?.list?.map(category => ({
    name: category.name,
    count: category.count,
    revenue: category.revenue,
    percentage: (category.count / data[0]?.itemCount * 100) || 0
  }))?.sort((a, b) => b.count - a.count) || [];

  if (!brandData.length && !categoryData.length) {
    return <div className="text-muted-foreground">No brands or categories data available.</div>;
  }

  return (
    <div className="space-y-8">
      {brandData.length > 0 && (
        <div>
          <h3 className="text-lg font-medium mb-4">All Brands</h3>
          <div className="rounded-lg border bg-card max-h-[400px] 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>
                  <TableHead className="text-right">% of Total</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {brandData.map((brand, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">{brand.name}</TableCell>
                    <TableCell className="text-right">{brand.count.toLocaleString()}</TableCell>
                    <TableCell className="text-right">{formatCurrency(brand.revenue)}</TableCell>
                    <TableCell className="text-right">{brand.percentage.toFixed(1)}%</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>
      )}
      
      {categoryData.length > 0 && (
        <div>
          <h3 className="text-lg font-medium mb-4">All Categories</h3>
          <div className="rounded-lg border bg-card max-h-[400px] 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>
                  <TableHead className="text-right">% of Total</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {categoryData.map((category, index) => (
                  <TableRow key={index}>
                    <TableCell className="font-medium">{category.name}</TableCell>
                    <TableCell className="text-right">{category.count.toLocaleString()}</TableCell>
                    <TableCell className="text-right">{formatCurrency(category.revenue)}</TableCell>
                    <TableCell className="text-right">{category.percentage.toFixed(1)}%</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 || [];

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title="Total Shipped Orders"
          value={shippedCount.toLocaleString()}
          description="orders"
          colorClass="text-teal-600 dark:text-teal-400"
          icon={Package}
        />
        <StatCard
          title="Shipping Locations"
          value={locations.total || 0}
          description="unique locations"
          colorClass="text-teal-600 dark:text-teal-400"
          icon={MapPin}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Shipping Methods Distribution</h3>
        <div className="h-[400px] w-full">
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie
                data={methodStats}
                dataKey="value"
                nameKey="name"
                cx="50%"
                cy="50%"
                outerRadius={150}
                fill="hsl(171.2 77.2% 53.3%)"
                label={({ name, percent }) => `${name} (${(percent * 100).toFixed(1)}%)`}
              >
                {methodStats.map((entry, index) => (
                  <Cell
                    key={`cell-${index}`}
                    fill={`hsl(171.2 77.2% ${53.3 - (index * 10)}%)`}
                  />
                ))}
              </Pie>
              <Tooltip
                formatter={(value, name) => [
                  `${value.toLocaleString()} orders (${((value / shippedCount) * 100).toFixed(1)}%)`,
                  name
                ]}
              />
            </PieChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Shipping Locations</h3>
        <div className="max-h-[400px] overflow-y-auto pr-2">
          <div className="space-y-2">
            {locations.byState?.map((location) => (
              <div
                key={location.state}
                className="flex justify-between items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg"
              >
                <div>
                  <span className="font-medium">{location.state}</span>
                  <span className="text-sm text-muted-foreground ml-2">
                    {location.country}
                  </span>
                </div>
                <div className="text-sm">
                  <span className="font-medium">
                    {location.count.toLocaleString()}
                  </span>
                  <span className="text-muted-foreground ml-2">
                    ({location.percentage.toFixed(1)}%)
                  </span>
                </div>
              </div>
            ))}
          </div>
        </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>;

  // Access the correct daily data using the 'type' prop
  const timeSeriesData = data.map(day => ({
    timestamp: day.timestamp,
    count: day.count,
    value: day.value,
    percentage: day.percentage
  }));

  const typeLabels = {
    'pre_orders': 'Pre-Orders',
    'local_pickup': 'Local Pickup',
    'on_hold': 'On Hold'
  };

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title={`Total ${typeLabels[type]}`}
          value={data[0]?.totalOrders?.toLocaleString() || 0}
          description={`${data[0]?.percentage?.toFixed(1) || 0}% of all orders`}
          colorClass="text-blue-600 dark:text-blue-400"
          icon={ShoppingCart}
        />
        <StatCard
          title="Total Value"
          value={formatCurrency(data[0]?.value || 0)}
          description={`Avg: ${formatCurrency((data[0]?.value || 0) / (data[0]?.count || 1))}`}
          colorClass="text-green-600 dark:text-green-400"
          icon={DollarSign}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Daily Order Count</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="count"
          name="Orders"
          type="bar"
          color="hsl(221.2 83.2% 53.3%)"
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Daily Value</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="value"
          name="Value"
          color="hsl(142.1 76.2% 36.3%)"
          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="hsl(262.1 83.3% 57.8%)"
          valueFormatter={(value) => `${value.toFixed(1)}%`}
        />
      </div>
    </div>
  );
};

const PeakHourDetails = ({ data }) => {
  const hourlyData = data[0]?.hourlyOrders?.map((count, hour) => ({
    hour: formatHour(hour),
    orders: count,
    percentage: (count / data[0]?.orderCount * 100) || 0
  })) || [];

  return (
    <>
      <TimeSeriesChart
        data={hourlyData}
        dataKey="orders"
        name="Orders"
        type="bar"
        color="hsl(322.7 73.9% 64.7%)"
      />
      <div className="mt-8">
        <StatGrid
          stats={[
            {
              label: "Peak Hour",
              value: formatHour(data[0]?.peakOrderHour?.hour || 0),
              description: `${data[0]?.peakOrderHour?.count || 0} orders`
            },
            {
              label: "Average Orders per Hour",
              value: (data[0]?.orderCount / 24).toFixed(1),
              description: "orders"
            }
          ]}
        />
      </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,
      percentage: (count / refundData.count) * 100
    }))
    .sort((a, b) => b.count - a.count);

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title="Total Refunds"
          value={formatCurrency(refundData.total)}
          description={`${refundData.count.toLocaleString()} orders`}
          colorClass="text-orange-600 dark:text-orange-400"
          icon={RefreshCcw}
        />
        <StatCard
          title="Average Refund"
          value={formatCurrency(refundData.total / (refundData.count || 1))}
          description="per order"
          colorClass="text-orange-600 dark:text-orange-400"
          icon={DollarSign}
        />
      </div>

      <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>
                  <TableHead className="text-right">% of Total</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>
                    <TableCell className="text-right">{item.percentage.toFixed(1)}%</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>;

  const rangeData = data[0]?.orderValueRange || {
    largest: 0,
    smallest: 0,
    largestOrderId: null,
    smallestOrderId: null,
    distribution: {
      under25: { count: 0, total: 0 },
      under50: { count: 0, total: 0 },
      under100: { count: 0, total: 0 },
      under200: { count: 0, total: 0 },
      over200: { count: 0, total: 0 }
    }
  };

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

  const distributionData = [
    { range: 'Under $25', ...rangeData.distribution.under25 },
    { range: '$25-$50', ...rangeData.distribution.under50 },
    { range: '$50-$100', ...rangeData.distribution.under100 },
    { range: '$100-$200', ...rangeData.distribution.under200 },
    { range: 'Over $200', ...rangeData.distribution.over200 }
  ];

  const totalOrders = distributionData.reduce((sum, range) => sum + (range.count || 0), 0);
  const totalRevenue = distributionData.reduce((sum, range) => sum + (range.total || 0), 0);

  return (
    <div className="space-y-8">
      <div className="grid grid-cols-2 gap-4">
        <StatCard
          title="Largest Order"
          value={formatCurrency(rangeData.largest)}
          description={rangeData.largestOrderId ? `Order #${rangeData.largestOrderId}` : null}
          colorClass="text-violet-600 dark:text-violet-400"
          icon={TrendingUp}
        />
        <StatCard
          title="Smallest Order"
          value={formatCurrency(rangeData.smallest)}
          description={rangeData.smallestOrderId ? `Order #${rangeData.smallestOrderId}` : null}
          colorClass="text-violet-600 dark:text-violet-400"
          icon={TrendingDown}
        />
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Order Value Range Over Time</h3>
        <TimeSeriesChart
          data={timeSeriesData}
          dataKey="largest"
          name="Largest Order"
          color="hsl(262.1 83.3% 57.8%)"
          valueFormatter={(value) => formatCurrency(value)}
        />
      </div>

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

      <div>
        <h3 className="text-lg font-medium mb-4">Order Value Distribution</h3>
        <div className="grid grid-cols-2 gap-4 mb-4">
          <StatCard
            title="Total Orders"
            value={totalOrders.toLocaleString()}
            description="orders analyzed"
            colorClass="text-violet-600 dark:text-violet-400"
            icon={ShoppingCart}
          />
          <StatCard
            title="Total Revenue"
            value={formatCurrency(totalRevenue)}
            description="from all orders"
            colorClass="text-violet-600 dark:text-violet-400"
            icon={DollarSign}
          />
        </div>
        <div className="rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>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">Avg. Order Value</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {distributionData.map((range, index) => (
                <TableRow key={index}>
                  <TableCell className="font-medium">{range.range}</TableCell>
                  <TableCell className="text-right">{range.count?.toLocaleString() || 0}</TableCell>
                  <TableCell className="text-right">{formatCurrency(range.total || 0)}</TableCell>
                  <TableCell className="text-right">
                    {((range.count / totalOrders) * 100).toFixed(1)}%
                  </TableCell>
                  <TableCell className="text-right">
                    {formatCurrency((range.total || 0) / (range.count || 1))}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      <div>
        <h3 className="text-lg font-medium mb-4">Distribution Chart</h3>
        <TimeSeriesChart
          data={distributionData}
          dataKey="count"
          name="Orders"
          type="bar"
          color="hsl(262.1 83.3% 57.8%)"
        />
      </div>
    </div>
  );
};

const StatCard = ({ 
  title, 
  value, 
  description, 
  trend, 
  trendValue,
  valuePrefix = "",
  valueSuffix = "",
  trendPrefix = "",
  trendSuffix = "",
  className = "",
  colorClass = "text-gray-900 dark:text-gray-100",
  icon: Icon,
  iconColor = "text-gray-500",
  onClick,
  info,
  onDetailsClick,
  isLoading = false
}) => (
  <Card 
    className={`${className} ${onClick || onDetailsClick ? "cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors" : ""}`} 
    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="text-sm font-medium text-gray-600 dark:text-gray-300">
          {title}
        </CardTitle>
        {info && (
          <Info
            className="w-4 h-4 text-muted-foreground cursor-help"
            title={info}
          />
        )}
      </div>
      {Icon && <Icon className={`h-4 w-4 ${iconColor}`} />}
    </CardHeader>
    <CardContent className="p-4 pt-0">
      {isLoading ? (
        <>
          <Skeleton className="h-8 w-32 mb-2" />
          <Skeleton className="h-4 w-24" />
        </>
      ) : (
        <>
          <div className={`text-2xl font-bold ${colorClass}`}>
            {valuePrefix}{value}{valueSuffix}
          </div>
          {description && (
            <div className="text-sm text-muted-foreground mt-2 items-center gap-2 flex">
              {description}
              {trend && (
                <span className={`flex items-center gap-1 ${trend === 'up' ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'}`}>
                  {trend === 'up' ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
                  {trendPrefix}{trendValue}{trendSuffix}
                </span>
              )}
            </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>
    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
      <Skeleton className="h-4 w-24" />
      <Skeleton className="h-4 w-4 rounded-full" />
    </CardHeader>
    <CardContent>
      <Skeleton className="h-8 w-32 mb-2" />
      <Skeleton className="h-4 w-24" />
    </CardContent>
  </Card>
);

const SkeletonChart = ({ type = "line" }) => (
  <div className="h-[400px] w-full bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
    <div className="h-full flex flex-col">
      <div className="flex-1 relative">
        {type === "bar" ? (
          <div className="h-full flex items-end justify-between gap-1">
            {[...Array(24)].map((_, i) => (
              <div
                key={i}
                className="w-full bg-gray-200 dark:bg-gray-700 rounded-t animate-pulse"
                style={{ height: `${15 + Math.random() * 70}%` }}
              />
            ))}
          </div>
        ) : (
          <div className="h-full w-full relative">
            {[...Array(5)].map((_, i) => (
              <div
                key={i}
                className="absolute w-full h-px bg-gray-200 dark:bg-gray-700"
                style={{ top: `${20 + i * 20}%` }}
              />
            ))}
            <div
              className="absolute inset-0 bg-gray-300 dark:bg-gray-600 animate-pulse"
              style={{
                opacity: 0.2,
                clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
              }}
            />
          </div>
        )}
      </div>
    </div>
  </div>
);

const SkeletonTable = ({ rows = 5 }) => (
  <div className="space-y-2">
    <div className="grid grid-cols-3 gap-4 pb-2">
      {[...Array(3)].map((_, i) => (
        <Skeleton key={i} className="h-5 w-full" />
      ))}
    </div>
    {[...Array(rows)].map((_, i) => (
      <div key={i} className="grid grid-cols-3 gap-4 py-2">
        {[...Array(3)].map((_, j) => (
          <Skeleton key={j} className="h-4 w-full" />
        ))}
      </div>
    ))}
  </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 { 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 axios.get('/api/klaviyo/events/stats', { params });
        const data = [response.data.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 axios.get('/api/klaviyo/events/stats/details', { 
          params: {
            ...params,
            orderType: orderType
          }
        });
        const data = response.data.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 axios.get('/api/klaviyo/events/stats/details', { 
          params: {
            ...params,
            eventType: metric === 'refunds' ? 'PAYMENT_REFUNDED' : 'CANCELED_ORDER'
          }
        });
        const data = response.data.stats;
        setCacheData(detailTimeRange, metric, data);
        setDetailData(prev => ({ ...prev, [metric]: data }));
        setError(null);
        return data;
      }

      // For order range
      if (metric === 'order_range') {
        const response = await axios.get('/api/klaviyo/events/stats/details', { params });
        const data = response.data.stats.map(day => ({
          ...day,
          orderValueRange: {
            ...day.orderValueRange,
            distribution: day.orderValueRange?.distribution || {
              under25: { count: 0, total: 0 },
              under50: { count: 0, total: 0 },
              under100: { count: 0, total: 0 },
              under200: { count: 0, total: 0 },
              over200: { count: 0, total: 0 }
            }
          }
        }));
        setCacheData(detailTimeRange, metric, data);
        setDetailData(prev => ({ ...prev, [metric]: data }));
        setError(null);
        return data;
      }

      // For all other metrics
      const response = await axios.get('/api/klaviyo/events/stats/details', { params });
      const data = response.data.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]);
  // Corrected preloadDetailData function
  const preloadDetailData = useCallback(() => {
    const metrics = [
      'revenue',
      'orders',
      'average_order',
      'refunds',
      'cancellations',
      'order_range',
      'pre_orders',
      'local_pickup',
      'on_hold'
    ];

    // Await all fetchDetailData calls
    return Promise.all(metrics.map(metric => fetchDetailData(metric, metric))).catch(error => {
      console.error('Error during detail data preload:', 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;
    
    // For incomplete periods, compare projected revenue to previous period
    // For complete periods, compare actual revenue to previous period
    const currentRevenue = stats.periodProgress < 100 ? stats.projectedRevenue : stats.revenue;
    const prevRevenue = stats.prevPeriodRevenue;
    
    if (!currentRevenue || !prevRevenue) return null;
    
    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]);

  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 axios.get('/api/klaviyo/events/stats', { params });
        
        if (!isMounted) return;

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

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

    const interval = setInterval(async () => {
      try {
        const response = await axios.get('/api/klaviyo/events/stats', {
          params: { timeRange: 'today' }
        });
        setStats(response.data.stats);
        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 '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 '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]} />;
      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">
          <div className="flex flex-col space-y-2">
            <div className="flex justify-between items-start">
              <div>
                <Skeleton className="h-6 w-48 mb-2" />
                <Skeleton className="h-4 w-64" />
              </div>
              <div className="flex items-center gap-4">
                <Skeleton className="h-4 w-32" />
                <Skeleton className="h-9 w-[130px]" />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-6 pt-0">
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {[...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">{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")}</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-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          <StatCard
            title="Total Revenue"
            value={formatCurrency(stats?.revenue || 0)}
            description={
              stats?.periodProgress < 100
                ? `${stats.periodProgress.toFixed(1)}% complete • Projected: ${formatCurrency(stats.projectedRevenue)}`
                : `Previous: ${formatCurrency(stats.prevPeriodRevenue)}`
            }
            trend={revenueTrend?.trend}
            trendValue={revenueTrend?.value ? formatPercentage(revenueTrend.value) : null}
            colorClass="text-green-600 dark:text-green-400"
            icon={DollarSign}
            iconColor="text-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"
            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"
            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"
            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"
            onDetailsClick={() => setSelectedMetric('shipping')}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Pre-Orders"
            value={stats?.orderTypes?.preOrders?.percentage?.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"
            onDetailsClick={() => setSelectedMetric('pre_orders')}
            isLoading={loading || !stats}
          />

          <StatCard
            title="Local Pickup"
            value={stats?.orderTypes?.localPickup?.percentage?.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"
            onDetailsClick={() => setSelectedMetric('local_pickup')}
            isLoading={loading || !stats}
          />

          <StatCard
            title="On Hold"
            value={stats?.orderTypes?.heldItems?.percentage?.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"
            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"
              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"
              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"
            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"
            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"
            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 default StatCards; 
