import React, { useState, useEffect, useCallback, memo } from "react";
import { acotService } from "@/services/dashboard/acotService";
import { Card, CardContent } from "@/components/ui/card";
import { BusinessRangeSelect } from "@/components/dashboard/shared/BusinessRangeSelect";
import { Button } from "@/components/ui/button";
import { TrendingUp } from "lucide-react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Legend,
  ReferenceLine,
} from "recharts";
import {
  Table,
  TableHeader,
  TableHead,
  TableRow,
  TableBody,
  TableCell,
} from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Skeleton } from "@/components/ui/skeleton";
import { Separator } from "@/components/ui/separator";
import { CARD_STYLES, STUDIO_COLORS } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  DashboardChartTooltip,
  ChartSkeleton,
  DashboardEmptyState,
  DashboardErrorState,
  MetricPill,
} from "@/components/dashboard/shared";

// Chart color mapping — Sorbet Studio series hues (prev-* stay dashed in the
// chart; the lighter prev tones are only legal alongside that dash)
const CHART_COLORS = {
  revenue: STUDIO_COLORS.coral,
  prevRevenue: STUDIO_COLORS.teal,
  orders: STUDIO_COLORS.violet,
  prevOrders: "#9c92de",
  aov: STUDIO_COLORS.amber,
  prevAov: "#c9a45b",
  movingAverage: "#a8a29a",
};

// Move formatCurrency to top and export it
export 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);
};

// Sales chart tooltip formatter - formats revenue/AOV as currency, others as numbers
const salesValueFormatter = (value, name) => {
  const nameLower = (name || "").toLowerCase();
  if (nameLower.includes('revenue') || nameLower.includes('order value') || nameLower.includes('average')) {
    return formatCurrency(value);
  }
  return typeof value === 'number' ? value.toLocaleString() : value;
};

// Sales chart label formatter - formats timestamp as readable date
const salesLabelFormatter = (label) => {
  const date = new Date(label);
  return date.toLocaleDateString("en-US", {
    weekday: "short",
    month: "short",
    day: "numeric",
  });
};

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

// Export processData
export 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);

  // Get period progress from the last day
  const periodProgress = data[data.length - 1]?.periodProgress || 100;

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

// Compact inline totals — replaces the old four-card summary row. The hero
// tiles above the fold already carry the headline numbers; this line just
// anchors the chart to its period totals.
const SummaryStats = memo(({ stats = {}, projection = null, projectionLoading = false }) => {
  const {
    totalRevenue = 0,
    totalOrders = 0,
    avgOrderValue = 0,
    prevRevenue = 0,
    prevOrders = 0,
    periodProgress = 100,
  } = stats;

  const currentRevenue =
    periodProgress < 100 ? projection?.projectedRevenue || totalRevenue : totalRevenue;
  const currentOrders =
    periodProgress < 100 ? projection?.projectedOrders || totalOrders : totalOrders;
  const showTrends = !(projectionLoading && periodProgress < 100);
  const revPct = prevRevenue > 0 ? ((currentRevenue - prevRevenue) / prevRevenue) * 100 : null;
  const ordPct = prevOrders > 0 ? ((currentOrders - prevOrders) / prevOrders) * 100 : null;

  const Delta = ({ pct }) => {
    if (!showTrends || pct == null || !isFinite(pct) || Math.abs(pct) < 0.1) return null;
    return (
      <span className={pct > 0 ? "text-[#237a4d]" : "text-[#b3503f]"}>
        {" "}
        {pct > 0 ? "↑" : "↓"}
        {Math.abs(pct).toFixed(1)}%
      </span>
    );
  };

  return (
    <div className="text-xs text-[#7c7870]">
      Revenue{" "}
      <span className="font-bold tabular-nums text-[#2b2925]">
        {formatCurrency(totalRevenue, false)}
      </span>
      <Delta pct={revPct} />
      <span className="mx-1.5 text-[#d8d4cd]">·</span>
      Orders{" "}
      <span className="font-bold tabular-nums text-[#2b2925]">
        {totalOrders.toLocaleString()}
      </span>
      <Delta pct={ordPct} />
      <span className="mx-1.5 text-[#d8d4cd]">·</span>
      AOV{" "}
      <span className="font-bold tabular-nums text-[#2b2925]">
        {formatCurrency(avgOrderValue)}
      </span>
    </div>
  );
});

SummaryStats.displayName = "SummaryStats";

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

const SkeletonStats = () => (
  <div className="h-4 w-64 animate-pulse rounded bg-[#f0eeea]" />
);

const SalesChart = ({ timeRange = "last30days", title = "Sales" }) => {
  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({});
  const [projection, setProjection] = useState(null);
  const [projectionLoading, setProjectionLoading] = useState(false);

  // Add function to fetch projection
  const fetchProjection = useCallback(async (params) => {
    if (!params) return;
    
    try {
      setProjectionLoading(true);
      const response = await acotService.getProjection(params);
      setProjection(response);
    } catch (error) {
      console.error("Error loading projection:", error);
    } finally {
      setProjectionLoading(false);
    }
  }, []);

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

      // Fetch data
      const response = await acotService.getStatsDetails({
        ...params,
        metric: "revenue",
        daily: true,
      });

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

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

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

      setData(processedData);
      setSummaryStats(stats);
      setError(null);

      // Fetch projection if needed
      if (stats.periodProgress < 100) {
        fetchProjection(params);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
      setError(error.message);
    } finally {
      setLoading(false);
    }
  }, [fetchProjection]);

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

  // Initial load and auto-refresh effect
  useEffect(() => {
    let intervalId = null;

    // Initial fetch
    fetchData({ timeRange: selectedTimeRange });

    // Set up auto-refresh only for 'today' view
    if (selectedTimeRange === "today") {
      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;

  // Time selector for DashboardSectionHeader
  const timeSelector = (
    <BusinessRangeSelect
      value={selectedTimeRange}
      onValueChange={handleTimeRangeChange}
    />
  );

  // Actions (Details dialog) for DashboardSectionHeader
  const headerActions = !error ? (
    <Dialog>
                  <DialogTrigger asChild>
                    <Button
                      variant="outline"
                      size="sm"
                      className="h-8 rounded-full border-[#e7e5e1] text-xs font-semibold text-[#2b2925] shadow-none hover:bg-[#faf9f7]"
                    >
                      Details
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="p-4 max-w-[95vw] w-fit max-h-[85vh] overflow-hidden flex flex-col rounded-[14px] border-[#e7e5e1] bg-white">
                    <DialogHeader className="flex-none">
                      <DialogTitle className="text-foreground">
                        Daily Details
                      </DialogTitle>
                      <div className="flex items-center justify-center gap-2 pt-4">
                        <div className="flex flex-wrap gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            className={`h-7 rounded-full px-3 text-xs font-medium ${metrics.revenue ? "bg-[#f0eeea] text-[#2b2925] hover:bg-[#eae7e2]" : "text-[#7c7870] hover:bg-[#f5f3f0] hover:text-[#2b2925]"}`}
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                revenue: !prev.revenue,
                              }))
                            }
                          >
                            Revenue
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className={`h-7 rounded-full px-3 text-xs font-medium ${metrics.orders ? "bg-[#f0eeea] text-[#2b2925] hover:bg-[#eae7e2]" : "text-[#7c7870] hover:bg-[#f5f3f0] hover:text-[#2b2925]"}`}
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                orders: !prev.orders,
                              }))
                            }
                          >
                            Orders
                          </Button>
                          <Button
                            variant={
                              metrics.movingAverage ? "secondary" : "ghost"
                            }
                            size="sm"
                            className="h-7 text-xs"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                movingAverage: !prev.movingAverage,
                              }))
                            }
                          >
                            7-Day Avg
                          </Button>
                          <Button
                            variant={
                              metrics.avgOrderValue ? "secondary" : "ghost"
                            }
                            size="sm"
                            className="h-7 text-xs"
                            onClick={() =>
                              setMetrics((prev) => ({
                                ...prev,
                                avgOrderValue: !prev.avgOrderValue,
                              }))
                            }
                          >
                            AOV
                          </Button>
                        </div>

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

                        <Button
                          variant="ghost"
                          size="sm"
                          className={`h-7 rounded-full px-3 text-xs font-medium ${metrics.showPrevious ? "bg-[#f0eeea] text-[#2b2925] hover:bg-[#eae7e2]" : "text-[#7c7870] hover:bg-[#f5f3f0] hover:text-[#2b2925]"}`}
                          onClick={() =>
                            setMetrics((prev) => ({
                              ...prev,
                              showPrevious: !prev.showPrevious,
                            }))
                          }
                        >
                          Compare Prev
                        </Button>
                      </div>
                    </DialogHeader>
                    <div className="flex-1 overflow-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">
                                Date
                              </TableHead>

                              {metrics.revenue && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6">
                                    Revenue
                                  </TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6">
                                      Prev Revenue
                                    </TableHead>
                                  )}
                                </>
                              )}
                              {metrics.orders && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6">
                                    Orders
                                  </TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6">
                                      Prev Orders
                                    </TableHead>
                                  )}
                                </>
                              )}
                              {metrics.avgOrderValue && (
                                <>
                                  <TableHead className="text-center whitespace-nowrap px-6">
                                    AOV
                                  </TableHead>
                                  {metrics.showPrevious && (
                                    <TableHead className="text-center whitespace-nowrap px-6">
                                      Prev AOV
                                    </TableHead>
                                  )}
                                </>
                              )}
                              {metrics.movingAverage && (
                                <TableHead className="text-center whitespace-nowrap px-6">
                                  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.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.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.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>
  ) : null;

  return (
    <Card className={`w-full ${CARD_STYLES.elevated}`}>
      <DashboardSectionHeader
        title={title}
        size="large"
        timeSelector={timeSelector}
        actions={headerActions}
      />

      <CardContent className="p-4 pt-3 space-y-3">
        {/* Show stats only if not in error state */}
        {!error && (
          loading ? (
            <SkeletonStats />
          ) : (
            <SummaryStats
              stats={summaryStats}
              projection={projection}
              projectionLoading={projectionLoading}
            />
          )
        )}

        {/* Metric toggle pills — the pill dot doubles as the series legend */}
        {!error && (
          <div className="flex flex-wrap items-center gap-0.5">
            <MetricPill
              active={metrics.revenue}
              color={CHART_COLORS.revenue}
              onClick={() => setMetrics((prev) => ({ ...prev, revenue: !prev.revenue }))}
            >
              Revenue
            </MetricPill>
            <MetricPill
              active={metrics.orders}
              color={CHART_COLORS.orders}
              onClick={() => setMetrics((prev) => ({ ...prev, orders: !prev.orders }))}
            >
              Orders
            </MetricPill>
            <MetricPill
              active={metrics.avgOrderValue}
              color={CHART_COLORS.aov}
              onClick={() => setMetrics((prev) => ({ ...prev, avgOrderValue: !prev.avgOrderValue }))}
            >
              AOV
            </MetricPill>
            <MetricPill
              active={metrics.movingAverage}
              color={CHART_COLORS.movingAverage}
              dashed
              onClick={() => setMetrics((prev) => ({ ...prev, movingAverage: !prev.movingAverage }))}
            >
              7-day avg
            </MetricPill>
            <span className="mx-1.5 h-4 w-px bg-[#eceae5]" />
            <MetricPill
              active={metrics.showPrevious}
              color={CHART_COLORS.prevRevenue}
              dashed
              onClick={() => setMetrics((prev) => ({ ...prev, showPrevious: !prev.showPrevious }))}
            >
              vs previous
            </MetricPill>
          </div>
        )}
        {loading ? (
          <div className="space-y-6">
            <ChartSkeleton height="default" withCard={false} />
            <div className="mt-4 flex justify-end">
              <Skeleton className="h-9 w-24 bg-muted rounded-sm" />
            </div>
            {showDailyTable && <TableSkeleton rows={7} columns={3} />}
          </div>
        ) : error ? (
          <DashboardErrorState error={`Failed to load sales data: ${error}`} className="mx-0 my-0" />
        ) : !data.length ? (
          <DashboardEmptyState
            icon={TrendingUp}
            title="No sales data available"
            description="Try selecting a different time range"
          />
        ) : (
          <>
            <div className="h-[340px] relative">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={data}
                  margin={{ top: 8, right: 0, left: -8, bottom: 0 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 4"
                    stroke="#efede9"
                    vertical={false}
                  />
                  <XAxis
                    dataKey="timestamp"
                    tickFormatter={formatXAxis}
                    tick={{ fill: "#a09b92", fontSize: 11 }}
                    tickLine={false}
                    axisLine={{ stroke: "#eceae5" }}
                  />
                  <YAxis
                    yAxisId="revenue"
                    tickFormatter={(value) => formatCurrency(value, false)}
                    tick={{ fill: "#a09b92", fontSize: 11 }}
                    tickLine={false}
                    axisLine={false}
                  />
                  <YAxis
                    yAxisId="orders"
                    orientation="right"
                    tickFormatter={(value) => value.toLocaleString()}
                    tick={{ fill: "#a09b92", fontSize: 11 }}
                    tickLine={false}
                    axisLine={false}
                  />
                  <Tooltip content={<DashboardChartTooltip valueFormatter={salesValueFormatter} labelFormatter={salesLabelFormatter} />} />
                  <ReferenceLine
                    y={averageRevenue}
                    yAxisId="revenue"
                    stroke="#d8d4cd"
                    strokeDasharray="3 4"
                    label={{
                      value: `avg ${formatCurrency(averageRevenue, false)}`,
                      fill: "#a09b92",
                      fontSize: 10,
                      position: "insideBottomRight",
                    }}
                  />
                  {metrics.revenue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="revenue"
                      name="Revenue"
                      stroke={CHART_COLORS.revenue}
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.revenue && metrics.showPrevious && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="prevRevenue"
                      name="Previous Revenue"
                      stroke={CHART_COLORS.prevRevenue}
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.orders && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="orders"
                      name="Orders"
                      stroke={CHART_COLORS.orders}
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.orders && metrics.showPrevious && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="prevOrders"
                      name="Previous Orders"
                      stroke={CHART_COLORS.prevOrders}
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.avgOrderValue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="avgOrderValue"
                      name="Avg Order Value"
                      stroke={CHART_COLORS.aov}
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {metrics.avgOrderValue && metrics.showPrevious && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="prevAvgOrderValue"
                      name="Previous Avg Order"
                      stroke={CHART_COLORS.prevAov}
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                  {metrics.movingAverage && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="movingAverage"
                      name="7-Day Average"
                      stroke={CHART_COLORS.movingAverage}
                      strokeWidth={2}
                      dot={false}
                      strokeDasharray="5 5"
                    />
                  )}
                </LineChart>
              </ResponsiveContainer>
            </div>
          </>
        )}
      </CardContent>
    </Card>
  );
};

export default SalesChart;
