import React, { useState, useEffect, useMemo, useCallback, 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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import {
  Loader2,
  TrendingUp,
  TrendingDown,
  Info,
  AlertCircle,
  ArrowUp,
  ArrowDown,
} from "lucide-react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  ReferenceLine,
} from "recharts";
import {
  TIME_RANGES,
  GROUP_BY_OPTIONS,
  formatDateForInput,
  parseDateFromInput,
} from "@/lib/constants";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Table,
  TableHeader,
  TableHead,
  TableRow,
  TableBody,
  TableCell,
} from "@/components/ui/table";
import { debounce } from "lodash";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";

const METRIC_IDS = {
  PLACED_ORDER: "Y8cqcF",
  PAYMENT_REFUNDED: "R7XUYh",
};

// Map current periods to their previous equivalents
const PREVIOUS_PERIOD_MAP = {
  today: "yesterday",
  thisWeek: "lastWeek",
  thisMonth: "lastMonth",
  last7days: "previous7days",
  last30days: "previous30days",
  last90days: "previous90days",
  yesterday: "twoDaysAgo",
};

// Add helper function to calculate previous period dates
const calculatePreviousPeriodDates = (timeRange, startDate, endDate) => {
  if (timeRange && timeRange !== "custom") {
    return {
      timeRange: PREVIOUS_PERIOD_MAP[timeRange],
    };
  } else if (startDate && endDate) {
    const start = new Date(startDate);
    const end = new Date(endDate);
    const duration = end.getTime() - start.getTime();

    const prevEnd = new Date(start.getTime() - 1);
    const prevStart = new Date(prevEnd.getTime() - duration);

    return {
      startDate: prevStart.toISOString(),
      endDate: prevEnd.toISOString(),
    };
  }
  return null;
};

// Enhanced helper function for consistent currency formatting with explicit rounding
const formatCurrency = (value, useFractionDigits = true) => {
  if (typeof value !== "number") return "$0.00";
  const roundedValue = parseFloat(value.toFixed(useFractionDigits ? 2 : 0));
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: useFractionDigits ? 2 : 0,
    maximumFractionDigits: useFractionDigits ? 2 : 0,
  }).format(roundedValue);
};

// Add a helper function for percentage formatting
const formatPercentage = (value) => {
  if (typeof value !== "number") return "0%";
  return `${Math.abs(Math.round(value))}%`;
};

// Add color mapping for metrics
const METRIC_COLORS = {
  revenue: "#8b5cf6",
  orders: "#10b981",
  avgOrderValue: "#9333ea",
  movingAverage: "#f59e0b",
  prevRevenue: "#f97316",
  prevOrders: "#0ea5e9",
  prevAvgOrderValue: "#f59e0b",
};

// Memoize the StatCard component
const StatCard = memo(
  ({
    title,
    value,
    description,
    trend,
    trendValue,
    valuePrefix = "",
    valueSuffix = "",
    trendPrefix = "",
    trendSuffix = "",
    className = "",
    colorClass = "text-gray-900 dark:text-gray-100",
  }) => (
    <Card className={className}>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
        <span className="text-sm text-muted-foreground">{title}</span>
        {trend && (
          <span
            className={`text-sm 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>
        )}
      </CardHeader>
      <CardContent className="p-4 pt-0">
        <div className={`text-2xl font-bold mb-1 ${colorClass}`}>
          {valuePrefix}
          {value}
          {valueSuffix}
        </div>
        {description && (
          <div className="text-sm text-muted-foreground">{description}</div>
        )}
      </CardContent>
    </Card>
  )
);

// Add display name for debugging
StatCard.displayName = "StatCard";

const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    const date = new Date(label);
    const formattedDate = date.toLocaleDateString("en-US", {
      weekday: "short",
      month: "short",
      day: "numeric",
      year: "numeric",
    });

    // Group metrics by type (current vs previous)
    const currentMetrics = payload.filter(
      (p) => !p.dataKey.toLowerCase().includes("prev")
    );
    const previousMetrics = payload.filter((p) =>
      p.dataKey.toLowerCase().includes("prev")
    );

    return (
      <Card className="p-3 shadow-lg bg-white dark:bg-gray-800 border-none">
        <CardContent className="p-0 space-y-2">
          <p className="font-medium text-sm border-b pb-1 mb-2">
            {formattedDate}
          </p>

          <div className="space-y-1">
            {currentMetrics.map((entry, index) => {
              const value =
                entry.dataKey.toLowerCase().includes("revenue") ||
                entry.dataKey === "avgOrderValue" ||
                entry.dataKey === "movingAverage" ||
                entry.dataKey === "aovMovingAverage"
                  ? formatCurrency(entry.value)
                  : entry.value.toLocaleString();

              return (
                <div
                  key={index}
                  className="flex justify-between items-center text-sm"
                >
                  <span
                    style={{
                      color:
                        entry.stroke ||
                        METRIC_COLORS[entry.dataKey.toLowerCase()],
                    }}
                  >
                    {entry.name}:
                  </span>
                  <span className="font-medium ml-4">{value}</span>
                </div>
              );
            })}
          </div>

          {previousMetrics.length > 0 && (
            <>
              <div className="border-t my-2"></div>
              <div className="space-y-1">
                <p className="text-xs text-muted-foreground mb-1">
                  Previous Period
                </p>
                {previousMetrics.map((entry, index) => {
                  const value =
                    entry.dataKey.toLowerCase().includes("revenue") ||
                    entry.dataKey.includes("avgOrderValue")
                      ? formatCurrency(entry.value)
                      : entry.value.toLocaleString();

                  return (
                    <div
                      key={index}
                      className="flex justify-between items-center text-sm"
                    >
                      <span
                        style={{
                          color:
                            entry.stroke ||
                            METRIC_COLORS[entry.dataKey.toLowerCase()],
                        }}
                      >
                        {entry.name.replace("Previous ", "")}:
                      </span>
                      <span className="font-medium ml-4">{value}</span>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </CardContent>
      </Card>
    );
  }
  return null;
};

const calculate7DayAverage = (data) => {
  if (!Array.isArray(data) || data.length === 0) return [];

  return data.map((day, index, array) => {
    // Get up to 7 days of data, including current day
    const startIndex = Math.max(0, index - 6);
    const window = array.slice(startIndex, index + 1);

    // Calculate averages for all metrics
    const validPoints = window.filter(
      (point) =>
        point &&
        typeof point.revenue === "number" &&
        typeof point.orders === "number" &&
        !isNaN(point.revenue) &&
        !isNaN(point.orders)
    );

    if (validPoints.length === 0) {
      return {
        ...day,
        movingAverage: 0,
        orderMovingAverage: 0,
        aovMovingAverage: 0,
      };
    }

    const revenueSum = validPoints.reduce((acc, curr) => acc + curr.revenue, 0);
    const orderSum = validPoints.reduce((acc, curr) => acc + curr.orders, 0);

    const revenueAvg = revenueSum / validPoints.length;
    const orderAvg = orderSum / validPoints.length;
    const aovAvg = orderAvg > 0 ? revenueAvg / orderAvg : 0;

    return {
      ...day,
      movingAverage: Number(revenueAvg.toFixed(2)),
      orderMovingAverage: Number(orderAvg.toFixed(2)),
      aovMovingAverage: Number(aovAvg.toFixed(2)),
    };
  });
};

const processData = (stats = []) => {
  if (!Array.isArray(stats)) return [];

  // First, convert the stats array into the base format
  const baseData = stats.map((day) => ({
    timestamp: day.date || day.timestamp,
    revenue: Number(day.revenue || 0),
    orders: Number(day.orders || 0),
    avgOrderValue: Number(
      day.averageOrderValue || (day.orders > 0 ? day.revenue / day.orders : 0)
    ),
    prevRevenue: Number(day.prevRevenue || 0),
    prevOrders: Number(day.prevOrders || 0),
    prevAvgOrderValue: Number(
      day.prevAvgOrderValue ||
        (day.prevOrders > 0 ? day.prevRevenue / day.prevOrders : 0)
    ),
    growth: {
      revenue: 0,
      orders: 0,
      avgOrderValue: 0,
    },
  }));

  // Calculate growth rates
  baseData.forEach((day) => {
    // Calculate growth
    day.growth = {
      revenue:
        day.prevRevenue > 0
          ? ((day.revenue - day.prevRevenue) / day.prevRevenue) * 100
          : 0,
      orders:
        day.prevOrders > 0
          ? ((day.orders - day.prevOrders) / day.prevOrders) * 100
          : 0,
      avgOrderValue:
        day.prevAvgOrderValue > 0
          ? ((day.avgOrderValue - day.prevAvgOrderValue) /
              day.prevAvgOrderValue) *
            100
          : 0,
    };
  });

  // Calculate 7-day moving averages
  return calculate7DayAverage(baseData);
};

const calculateSummaryStats = (data = []) => {
  if (!Array.isArray(data) || data.length === 0) return {};

  // Calculate current period totals
  const totalRevenue = data.reduce((sum, item) => sum + item.revenue, 0);
  const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
  const avgOrderValue = totalOrders ? totalRevenue / totalOrders : 0;

  // Calculate previous period totals
  const prevRevenue = data.reduce((sum, item) => sum + item.prevRevenue, 0);
  const prevOrders = data.reduce((sum, item) => sum + item.prevOrders, 0);
  const prevAvgOrderValue = prevOrders ? prevRevenue / prevOrders : 0;

  // Find best day
  const bestDay = data.reduce((best, current) => {
    if (current.revenue > (best?.revenue || 0)) {
      return {
        revenue: current.revenue,
        timestamp: current.timestamp,
        orders: current.orders,
        avgOrderValue: current.avgOrderValue,
      };
    }
    return best;
  }, null);

  // Calculate growth percentages
  const growth = {
    revenue: prevRevenue
      ? ((totalRevenue - prevRevenue) / prevRevenue) * 100
      : 0,
    orders: prevOrders ? ((totalOrders - prevOrders) / prevOrders) * 100 : 0,
    avgOrderValue: prevAvgOrderValue
      ? ((avgOrderValue - prevAvgOrderValue) / prevAvgOrderValue) * 100
      : 0,
  };

  return {
    totalRevenue,
    totalOrders,
    avgOrderValue,
    bestDay,
    prevRevenue,
    prevOrders,
    prevAvgOrderValue,
    growth,
    movingAverages: {
      revenue: data[data.length - 1]?.movingAverage || 0,
      orders: data[data.length - 1]?.orderMovingAverage || 0,
      avgOrderValue: data[data.length - 1]?.aovMovingAverage || 0,
    },
  };
};

// Add memoized SummaryStats component
const SummaryStats = memo(({ stats = {} }) => {
  const {
    totalRevenue = 0,
    totalOrders = 0,
    avgOrderValue = 0,
    bestDay = null,
    prevRevenue = 0,
    prevOrders = 0,
    prevAvgOrderValue = 0,
    growth = { revenue: 0, orders: 0, avgOrderValue: 0 },
  } = stats;

  return (
    <div className="grid grid-cols-4 gap-4 py-4 max-w-4xl">
      <StatCard
        title="Total Revenue"
        value={formatCurrency(totalRevenue, false)}
        description={`Previous: ${formatCurrency(prevRevenue, false)}`}
        trend={growth.revenue >= 0 ? "up" : "down"}
        trendValue={formatPercentage(growth.revenue)}
        info="Total revenue for the selected period"
        colorClass="text-green-600 dark:text-green-400"
      />

      <StatCard
        title="Total Orders"
        value={totalOrders.toLocaleString()}
        description={`Previous: ${prevOrders.toLocaleString()} orders`}
        trend={growth.orders >= 0 ? "up" : "down"}
        trendValue={formatPercentage(growth.orders)}
        info="Total number of orders for the selected period"
        colorClass="text-blue-600 dark:text-blue-400"
      />

      <StatCard
        title="AOV"
        value={formatCurrency(avgOrderValue)}
        description={`Previous: ${formatCurrency(prevAvgOrderValue)}`}
        trend={growth.avgOrderValue >= 0 ? "up" : "down"}
        trendValue={formatPercentage(growth.avgOrderValue)}
        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>
  );
});

SummaryStats.displayName = "SummaryStats";

// Add these skeleton components near the top of the file
const SkeletonChart = () => (
  <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">
        <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 SkeletonStats = () => (
  <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(4)].map((_, i) => (
      <Card key={i}>
        <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>
    ))}
  </div>
);

const SkeletonTable = () => (
  <div className="mt-4 overflow-x-auto rounded-lg border bg-card">
    <Table>
      <TableHeader>
        <TableRow>
          {[...Array(8)].map((_, i) => (
            <TableHead key={i}>
              <Skeleton className="h-4 w-20" />
            </TableHead>
          ))}
        </TableRow>
      </TableHeader>
      <TableBody>
        {[...Array(5)].map((_, i) => (
          <TableRow key={i}>
            {[...Array(8)].map((_, j) => (
              <TableCell key={j}>
                <Skeleton className="h-4 w-16" />
              </TableCell>
            ))}
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </div>
);

const SalesChart = ({
  timeRange = "last30days",
  title = "Sales Overview",
  description = "Track your sales performance over time",
}) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedTimeRange, setSelectedTimeRange] = useState(timeRange);
  const [showDailyTable, setShowDailyTable] = useState(false);
  const [metrics, setMetrics] = useState({
    revenue: true,
    orders: true,
    avgOrderValue: false,
    movingAverage: true,
    showPrevious: false,
  });
  const [summaryStats, setSummaryStats] = useState({});

  // Fetch data function
  const fetchData = useCallback(async (params) => {
    try {
      setLoading(true);
      setError(null);

      // Fetch data
      const response = await axios.get("/api/klaviyo/events/stats/details", {
        params: {
          ...params,
          metric: "revenue",
          daily: true,
        },
      });

      if (!response.data) {
        throw new Error("Invalid response format");
      }

      // Process the data
      const currentStats = Array.isArray(response.data)
        ? response.data
        : response.data.stats || [];

      // Process the data directly without remapping
      const processedData = processData(currentStats);
      const stats = calculateSummaryStats(processedData);

      setData(processedData);
      setSummaryStats(stats);
      setError(null);
    } catch (error) {
      console.error("Error fetching data:", error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  }, []);

  // Handle time range change
  const handleTimeRangeChange = useCallback(
    (value) => {
      setSelectedTimeRange(value);
      fetchData({ timeRange: value });
    },
    [fetchData]
  );

  // Initial load effect
  useEffect(() => {
    fetchData({ timeRange: selectedTimeRange });
  }, [selectedTimeRange, fetchData]);

  // Auto-refresh effect for 'today' view
  useEffect(() => {
    let intervalId = null;

    if (selectedTimeRange === "today") {
      // Initial fetch
      fetchData({ timeRange: "today" });

      // Set up interval
      intervalId = setInterval(() => {
        fetchData({ timeRange: "today" });
      }, 60000);
    }

    return () => {
      if (intervalId) {
        clearInterval(intervalId);
      }
    };
  }, [selectedTimeRange, fetchData]);

  const formatXAxis = (value) => {
    if (!value) return "";
    const date = new Date(value);
    return date.toLocaleDateString([], { month: "short", day: "numeric" });
  };

  const averageRevenue =
    data.length > 0
      ? data.reduce((sum, day) => sum + day.revenue, 0) / data.length
      : 0;

  return (
    <Card className="w-full bg-white dark:bg-gray-900/60 backdrop-blur-sm">
      <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>
            </div>
            <div className="flex items-center gap-4">
              {!error && (
                <Dialog>
                  <DialogTrigger asChild>
                    <Button variant="outline" className="h-9">
                      View Details
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="min-w-[600px] max-w-[90vw] w-fit max-h-[85vh] overflow-hidden flex flex-col">
                    <DialogHeader className="flex-none">
                      <DialogTitle>Daily Details</DialogTitle>
                      <div className="flex items-center justify-center gap-2 pt-4">
                        <div className="flex flex-wrap gap-1">
                          <Button
                            variant={metrics.revenue ? "default" : "outline"}
                            size="sm"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                revenue: !prev.revenue,
                              }))
                            }
                          >
                            Revenue
                          </Button>
                          <Button
                            variant={metrics.orders ? "default" : "outline"}
                            size="sm"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                orders: !prev.orders,
                              }))
                            }
                          >
                            Orders
                          </Button>
                          <Button
                            variant={metrics.movingAverage ? "default" : "outline"}
                            size="sm"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                movingAverage: !prev.movingAverage,
                              }))
                            }
                          >
                            7-Day Avg
                          </Button>
                          <Button
                            variant={metrics.avgOrderValue ? "default" : "outline"}
                            size="sm"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                avgOrderValue: !prev.avgOrderValue,
                              }))
                            }
                          >
                            AOV
                          </Button>
                        </div>

                        <Separator orientation="vertical" className="h-6" />

                        <Button
                          variant={metrics.showPrevious ? "default" : "outline"}
                          size="sm"
                          onClick={() =>
                            setMetrics((prev) => ({
                              ...prev,
                              showPrevious: !prev.showPrevious,
                            }))
                          }
                        >
                          Compare Prev Period
                        </Button>
                      </div>
                    </DialogHeader>
                    <div className="flex-1 overflow-y-auto mt-6">
                      <div className="rounded-lg border bg-card w-full">
                        <Table className="w-full">
                          <TableHeader>
                            <TableRow>
                              <TableHead className="text-center whitespace-nowrap px-6 w-[120px]">Date</TableHead>
                              {metrics.orders && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[100px]">Orders</TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6 min-w-[100px]">Prev Orders</TableHead>
                                  )}
                                </>
                              )}
                              {metrics.revenue && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[140px]">Revenue</TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6 min-w-[140px]">Prev Revenue</TableHead>
                                  )}
                                </>
                              )}
                              {metrics.avgOrderValue && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6 min-w-[120px]">AOV</TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6 min-w-[120px]">Prev AOV</TableHead>
                                  )}
                                </>
                              )}
                              {metrics.movingAverage && (
                                <TableHead className="text-center whitespace-nowrap px-6 min-w-[140px]">7-Day Avg</TableHead>
                              )}
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {data.map((day) => (
                              <TableRow key={day.timestamp}>
                                <TableCell className="text-center whitespace-nowrap px-6">{formatXAxis(day.timestamp)}</TableCell>
                                {metrics.orders && (
                                  <>
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {day.orders.toLocaleString()}
                                    </TableCell>
                                    {metrics.showPrevious && (
                                      <TableCell className="text-center whitespace-nowrap px-6">
                                        {day.prevOrders.toLocaleString()}
                                      </TableCell>
                                    )}
                                  </>
                                )}
                                {metrics.revenue && (
                                  <>
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {formatCurrency(day.revenue)}
                                    </TableCell>
                                    {metrics.showPrevious && (
                                      <TableCell className="text-center whitespace-nowrap px-6">
                                        {formatCurrency(day.prevRevenue)}
                                      </TableCell>
                                    )}
                                  </>
                                )}
                                {metrics.avgOrderValue && (
                                  <>
                                    <TableCell className="text-center whitespace-nowrap px-6">
                                      {formatCurrency(day.avgOrderValue)}
                                    </TableCell>
                                    {metrics.showPrevious && (
                                      <TableCell className="text-center whitespace-nowrap px-6">
                                        {formatCurrency(day.prevAvgOrderValue)}
                                      </TableCell>
                                    )}
                                  </>
                                )}
                                {metrics.movingAverage && (
                                  <TableCell className="text-center whitespace-nowrap px-6">
                                    {formatCurrency(day.movingAverage)}
                                  </TableCell>
                                )}
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </div>
                  </DialogContent>
                </Dialog>
              )}
              <Select
                value={selectedTimeRange}
                onValueChange={handleTimeRangeChange}
              >
                <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>

          {/* Show stats only if not in error state */}
          {!error && (loading ? <SkeletonStats /> : <SummaryStats stats={summaryStats} />)}

          {/* Show metric toggles only if not in error state */}
          {!error && (
            <div className="flex items-center gap-2 pt-2">
              <div className="flex flex-wrap gap-1">
                <Button
                  variant={metrics.revenue ? "default" : "outline"}
                  size="sm"
                  onClick={() =>
                    setMetrics((prev) => ({
                      ...prev,
                      revenue: !prev.revenue,
                    }))
                  }
                >
                  Revenue
                </Button>
                <Button
                  variant={metrics.orders ? "default" : "outline"}
                  size="sm"
                  onClick={() =>
                    setMetrics((prev) => ({
                      ...prev,
                      orders: !prev.orders,
                    }))
                  }
                >
                  Orders
                </Button>
                <Button
                  variant={metrics.movingAverage ? "default" : "outline"}
                  size="sm"
                  onClick={() =>
                    setMetrics((prev) => ({
                      ...prev,
                      movingAverage: !prev.movingAverage,
                    }))
                  }
                >
                  7-Day Avg
                </Button>
                <Button
                  variant={metrics.avgOrderValue ? "default" : "outline"}
                  size="sm"
                  onClick={() =>
                    setMetrics((prev) => ({
                      ...prev,
                      avgOrderValue: !prev.avgOrderValue,
                    }))
                  }
                >
                  AOV
                </Button>
              </div>

              <Separator orientation="vertical" className="h-6" />

              <Button
                variant={metrics.showPrevious ? "default" : "outline"}
                size="sm"
                onClick={() =>
                  setMetrics((prev) => ({
                    ...prev,
                    showPrevious: !prev.showPrevious,
                  }))
                }
              >
                Compare Prev Period
              </Button>
            </div>
          )}
        </div>
      </CardHeader>

      <CardContent className="p-6 pt-0">
        {loading ? (
          <div className="space-y-6">
            <SkeletonChart />
            <div className="mt-4 flex justify-end">
              <Skeleton className="h-9 w-24" />
            </div>
            {showDailyTable && <SkeletonTable />}
          </div>
        ) : error ? (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Error</AlertTitle>
            <AlertDescription>
              Failed to load sales data: {error}
            </AlertDescription>
          </Alert>
        ) : !data.length ? (
          <div className="flex items-center justify-center h-[400px] text-muted-foreground">
            <div className="text-center">
              <TrendingUp className="h-12 w-12 mx-auto mb-4" />
              <div className="font-medium mb-2">No sales data available</div>
              <div className="text-sm">
                Try selecting a different time range
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="h-[400px] mt-4 bg-card rounded-lg p-4 relative">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={data}
                  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    className="stroke-muted"
                  />
                  <XAxis
                    dataKey="timestamp"
                    tickFormatter={formatXAxis}
                    className="text-xs"
                    tick={{ fill: "currentColor" }}
                  />
                  <YAxis
                    yAxisId="revenue"
                    tickFormatter={(value) => formatCurrency(value, false)}
                    className="text-xs"
                    tick={{ fill: "currentColor" }}
                  />
                  <YAxis
                    yAxisId="orders"
                    orientation="right"
                    tickFormatter={(value) => value.toLocaleString()}
                    className="text-xs"
                    tick={{ fill: "currentColor" }}
                  />
                  <Tooltip content={<CustomTooltip />} />
                  <Legend />
                  <ReferenceLine
                    y={averageRevenue}
                    yAxisId="revenue"
                    stroke="currentColor"
                    strokeDasharray="3 3"
                    label={{
                      value: `Avg Revenue: ${formatCurrency(averageRevenue)}`,
                      fill: "currentColor",
                      fontSize: 12,
                    }}
                  />
                  {metrics.revenue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="revenue"
                      name="Revenue"
                      stroke="#8b5cf6"
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.revenue && metrics.showPrevious && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="prevRevenue"
                      name="Previous Revenue"
                      stroke="#f97316"
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.orders && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="orders"
                      name="Orders"
                      stroke="#10b981"
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.orders && metrics.showPrevious && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="prevOrders"
                      name="Previous Orders"
                      stroke="#0ea5e9"
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.avgOrderValue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="avgOrderValue"
                      name="Avg Order Value"
                      stroke="#9333ea"
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.avgOrderValue && metrics.showPrevious && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="prevAvgOrderValue"
                      name="Previous Avg Order"
                      stroke="#f59e0b"
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.movingAverage && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="movingAverage"
                      name="7-Day Average"
                      stroke="#f59e0b"
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                </LineChart>
              </ResponsiveContainer>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default SalesChart;
