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 } from "@/lib/dashboard/designTokens";
import {
  DashboardSectionHeader,
  DashboardStatCard,
  DashboardStatCardSkeleton,
  DashboardChartTooltip,
  ChartSkeleton,
  DashboardEmptyState,
  DashboardErrorState,
  METRIC_COLORS,
} from "@/components/dashboard/shared";

// Chart color mapping using semantic tokens
const CHART_COLORS = {
  revenue: METRIC_COLORS.revenue,
  prevRevenue: METRIC_COLORS.comparison,
  orders: METRIC_COLORS.orders,
  prevOrders: METRIC_COLORS.secondary,
  aov: METRIC_COLORS.aov,
  prevAov: METRIC_COLORS.comparison,
  movingAverage: METRIC_COLORS.comparison,
};

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

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

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

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

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

  // Convert trend direction to numeric value for DashboardStatCard
  const getNumericTrend = (trendDir, percentage) => {
    if (projectionLoading && periodProgress < 100) return undefined;
    if (!isFinite(percentage)) return undefined;
    return trendDir === "up" ? percentage : -percentage;
  };

  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4 dashboard-stagger w-full">
      <DashboardStatCard
        title="Total Revenue"
        value={formatCurrency(totalRevenue, false)}
        subtitle={
          periodProgress < 100
            ? `Projected: ${formatCurrency(projection?.projectedRevenue || totalRevenue, false)}`
            : `Previous: ${formatCurrency(prevRevenue, false)}`
        }
        trend={getNumericTrend(revenueTrend, revenuePercentage) !== undefined
          ? { value: getNumericTrend(revenueTrend, revenuePercentage) }
          : undefined}
        tooltip="Total revenue for the selected period"
        size="compact"
      />

      <DashboardStatCard
        title="Total Orders"
        value={totalOrders.toLocaleString()}
        subtitle={
          periodProgress < 100
            ? `Projected: ${(projection?.projectedOrders || totalOrders).toLocaleString()}`
            : `Previous: ${prevOrders.toLocaleString()}`
        }
        trend={getNumericTrend(ordersTrend, ordersPercentage) !== undefined
          ? { value: getNumericTrend(ordersTrend, ordersPercentage) }
          : undefined}
        tooltip="Total number of orders for the selected period"
        size="compact"
      />

      <DashboardStatCard
        title="AOV"
        value={formatCurrency(avgOrderValue)}
        subtitle={
          periodProgress < 100
            ? `Projected: ${formatCurrency(currentAOV)}`
            : `Previous: ${formatCurrency(prevAvgOrderValue)}`
        }
        trend={getNumericTrend(aovTrend, aovPercentage) !== undefined
          ? { value: getNumericTrend(aovTrend, aovPercentage) }
          : undefined}
        tooltip="Average value per order for the selected period"
        size="compact"
      />

      <DashboardStatCard
        title="Best Day"
        value={formatCurrency(bestDay?.revenue || 0, false)}
        subtitle={
          bestDay?.timestamp
            ? `${new Date(bestDay.timestamp).toLocaleDateString("en-US", {
                month: "short",
                day: "numeric",
              })} - ${bestDay.orders} orders`
            : "No data"
        }
        tooltip="Day with highest revenue in the selected period"
        size="compact"
      />
    </div>
  );
});

SummaryStats.displayName = "SummaryStats";

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

const SkeletonStats = () => (
  <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 py-4 max-w-3xl">
    {[...Array(4)].map((_, i) => (
      <DashboardStatCardSkeleton key={i} size="compact" hasIcon={false} hasSubtitle />
    ))}
  </div>
);

const SalesChart = ({ timeRange = "last30days", title = "Sales Overview" }) => {
  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" className="h-9">
                      Details
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="p-4 max-w-[95vw] w-fit max-h-[85vh] overflow-hidden flex flex-col bg-card">
                    <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={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
                        </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}
        timeSelector={timeSelector}
        actions={headerActions}
      />

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

        {/* Show metric toggles only if not in error state */}
        {!error && (
          <div className="flex items-center flex-col sm:flex-row gap-0 sm:gap-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 hidden sm:block"
            />
            <Separator
              orientation="horizontal"
              className="sm:hidden w-20 my-2"
            />

            <Button
              variant={metrics.showPrevious ? "default" : "outline"}
              size="sm"
              onClick={() =>
                setMetrics((prev) => ({
                  ...prev,
                  showPrevious: !prev.showPrevious,
                }))
              }
            >
              Compare Prev Period
            </Button>
          </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-[400px] mt-4 bg-card rounded-lg p-0 relative">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={data}
                  margin={{ top: 5, right: -30, left: -5, bottom: 5 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    className="stroke-muted"
                  />
                  <XAxis
                    dataKey="timestamp"
                    tickFormatter={formatXAxis}
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor" }}
                  />
                  <YAxis
                    yAxisId="revenue"
                    tickFormatter={(value) => formatCurrency(value, false)}
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor" }}
                  />
                  <YAxis
                    yAxisId="orders"
                    orientation="right"
                    tickFormatter={(value) => value.toLocaleString()}
                    className="text-xs text-muted-foreground"
                    tick={{ fill: "currentColor" }}
                  />
                  <Tooltip content={<DashboardChartTooltip valueFormatter={salesValueFormatter} labelFormatter={salesLabelFormatter} />} />
                  <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={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;
