import React, { useState, useEffect, useCallback, memo } from "react";
import axios from "axios";
import { acotService } from "@/services/dashboard/acotService";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/dashboard/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/dashboard/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/dashboard/ui/dialog";
import { DateTime } from "luxon";
import { TIME_RANGES } from "@/lib/dashboard/constants";
import { Alert, AlertDescription, AlertTitle } from "@/components/dashboard/ui/alert";
import {
  DollarSign,
  ShoppingCart,
  Package,
  AlertCircle,
  CircleDollarSign,
  Loader2,
} from "lucide-react";
import { Skeleton } from "@/components/dashboard/ui/skeleton";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
  TooltipProvider,
} from "@/components/dashboard/ui/tooltip";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/dashboard/ui/table";

// Import the detail view components and utilities from StatCards
import {
  RevenueDetails,
  OrdersDetails,
  AverageOrderDetails,
  ShippingDetails,
  StatCard,
  DetailDialog,
  formatCurrency,
  formatPercentage,
  SkeletonCard,
} from "./StatCards";

// Mini skeleton components
const MiniSkeletonChart = ({ type = "line" }) => (
  <div className={`h-[230px] w-full ${
    type === 'revenue' ? 'bg-emerald-50/10' :
    type === 'orders' ? 'bg-blue-50/10' :
    type === 'average_order' ? 'bg-violet-50/10' :
    'bg-orange-50/10'
  } rounded-lg p-4`}>
    <div className="h-full relative">
      {/* Grid lines */}
      {[...Array(5)].map((_, i) => (
        <div
          key={i}
          className={`absolute w-full h-px ${
            type === 'revenue' ? 'bg-emerald-200/20' :
            type === 'orders' ? 'bg-blue-200/20' :
            type === 'average_order' ? 'bg-violet-200/20' :
            'bg-orange-200/20'
          }`}
          style={{ top: `${(i + 1) * 20}%` }}
        />
      ))}
      {/* Y-axis labels */}
      <div className="absolute left-0 top-0 bottom-0 w-8 flex flex-col justify-between py-4">
        {[...Array(5)].map((_, i) => (
          <Skeleton key={i} className={`h-3 w-6 ${
            type === 'revenue' ? 'bg-emerald-200/20' :
            type === 'orders' ? 'bg-blue-200/20' :
            type === 'average_order' ? 'bg-violet-200/20' :
            'bg-orange-200/20'
          } rounded-sm`} />
        ))}
      </div>
      {/* X-axis labels */}
      <div className="absolute left-8 right-4 bottom-0 flex justify-between">
        {[...Array(6)].map((_, i) => (
          <Skeleton key={i} className={`h-3 w-8 ${
            type === 'revenue' ? 'bg-emerald-200/20' :
            type === 'orders' ? 'bg-blue-200/20' :
            type === 'average_order' ? 'bg-violet-200/20' :
            'bg-orange-200/20'
          } rounded-sm`} />
        ))}
      </div>
      {type === "bar" ? (
        <div className="absolute inset-x-8 bottom-6 top-4 flex items-end justify-between gap-1">
          {[...Array(24)].map((_, i) => (
            <div
              key={i}
              className={`w-2 ${
                type === 'revenue' ? 'bg-emerald-200/20' :
                type === 'orders' ? 'bg-blue-200/20' :
                type === 'average_order' ? 'bg-violet-200/20' :
                'bg-orange-200/20'
              } rounded-sm`}
              style={{ height: `${Math.random() * 80 + 10}%` }}
            />
          ))}
        </div>
      ) : (
        <div className="absolute inset-x-8 bottom-6 top-4">
          <div className="h-full w-full relative">
            <div
              className={`absolute inset-0 ${
                type === 'revenue' ? 'bg-emerald-200/20' :
                type === 'orders' ? 'bg-blue-200/20' :
                type === 'average_order' ? 'bg-violet-200/20' :
                'bg-orange-200/20'
              } rounded-sm`}
              style={{
                opacity: 0.5,
                clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
              }}
            />
          </div>
        </div>
      )}
    </div>
  </div>
);

const MiniSkeletonTable = ({ rows = 8, colorScheme = "orange" }) => (
  <div className={`rounded-lg border ${
    colorScheme === 'orange' ? 'bg-orange-50/10 border-orange-200/20' :
    colorScheme === 'emerald' ? 'bg-emerald-50/10 border-emerald-200/20' :
    colorScheme === 'blue' ? 'bg-blue-50/10 border-blue-200/20' :
    'bg-violet-50/10 border-violet-200/20'
  }`}>
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>
            <Skeleton className={`h-4 w-32 ${
              colorScheme === 'orange' ? 'bg-orange-200/20' :
              colorScheme === 'emerald' ? 'bg-emerald-200/20' :
              colorScheme === 'blue' ? 'bg-blue-200/20' :
              'bg-violet-200/20'
            } rounded-sm`} />
          </TableHead>
          <TableHead className="text-right">
            <Skeleton className={`h-4 w-24 ml-auto ${
              colorScheme === 'orange' ? 'bg-orange-200/20' :
              colorScheme === 'emerald' ? 'bg-emerald-200/20' :
              colorScheme === 'blue' ? 'bg-blue-200/20' :
              'bg-violet-200/20'
            } rounded-sm`} />
          </TableHead>
          <TableHead className="text-right">
            <Skeleton className={`h-4 w-24 ml-auto ${
              colorScheme === 'orange' ? 'bg-orange-200/20' :
              colorScheme === 'emerald' ? 'bg-emerald-200/20' :
              colorScheme === 'blue' ? 'bg-blue-200/20' :
              'bg-violet-200/20'
            } rounded-sm`} />
          </TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {[...Array(rows)].map((_, i) => (
          <TableRow key={i}>
            <TableCell>
              <Skeleton className={`h-4 w-48 ${
                colorScheme === 'orange' ? 'bg-orange-200/20' :
                colorScheme === 'emerald' ? 'bg-emerald-200/20' :
                colorScheme === 'blue' ? 'bg-blue-200/20' :
                'bg-violet-200/20'
              } rounded-sm`} />
            </TableCell>
            <TableCell className="text-right">
              <Skeleton className={`h-4 w-16 ml-auto ${
                colorScheme === 'orange' ? 'bg-orange-200/20' :
                colorScheme === 'emerald' ? 'bg-emerald-200/20' :
                colorScheme === 'blue' ? 'bg-blue-200/20' :
                'bg-violet-200/20'
              } rounded-sm`} />
            </TableCell>
            <TableCell className="text-right">
              <Skeleton className={`h-4 w-16 ml-auto ${
                colorScheme === 'orange' ? 'bg-orange-200/20' :
                colorScheme === 'emerald' ? 'bg-emerald-200/20' :
                colorScheme === 'blue' ? 'bg-blue-200/20' :
                'bg-violet-200/20'
              } rounded-sm`} />
            </TableCell>
          </TableRow>
        ))}
      </TableBody>
    </Table>
  </div>
);

const MiniStatCards = ({
  timeRange: initialTimeRange = "today",
  startDate,
  endDate,
  title = "Quick Stats",
  description = "",
  compact = false,
}) => {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [lastUpdate, setLastUpdate] = useState(null);
  const [timeRange, setTimeRange] = useState(initialTimeRange);
  const [selectedMetric, setSelectedMetric] = useState(null);
  const [detailDataLoading, setDetailDataLoading] = useState({});
  const [detailData, setDetailData] = useState({});
  const [projection, setProjection] = useState(null);
  const [projectionLoading, setProjectionLoading] = useState(false);

  // Reuse the trend calculation functions
  const calculateTrend = useCallback((current, previous) => {
    if (!current || !previous) return null;
    const trend = current >= previous ? "up" : "down";
    const diff = Math.abs(current - previous);
    const percentage = (diff / previous) * 100;

    return {
      trend,
      value: percentage,
      current,
      previous,
    };
  }, []);

  const calculateRevenueTrend = useCallback(() => {
    if (!stats?.prevPeriodRevenue && stats?.prevPeriodRevenue !== 0) return null;

    // If period is complete, use actual revenue
    // If period is incomplete, use smart projection when available, fallback to simple projection
    const currentRevenue = stats.periodProgress < 100 
      ? (projection?.projectedRevenue || stats.projectedRevenue) 
      : stats.revenue;
    const prevRevenue = stats.prevPeriodRevenue;  // Previous period's total revenue

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

    if (!currentRevenue || !prevRevenue) return null;

    // Calculate absolute difference percentage
    const trend = currentRevenue >= prevRevenue ? "up" : "down";
    const diff = Math.abs(currentRevenue - prevRevenue);
    const percentage = (diff / prevRevenue) * 100;

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

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

  const calculateOrderTrend = useCallback(() => {
    if (!stats?.prevPeriodOrders) return null;
    return calculateTrend(stats.orderCount, stats.prevPeriodOrders);
  }, [stats, calculateTrend]);

  const calculateAOVTrend = useCallback(() => {
    if (!stats?.prevPeriodAOV) return null;
    return calculateTrend(stats.averageOrderValue, stats.prevPeriodAOV);
  }, [stats, calculateTrend]);

  // Initial load effect
  useEffect(() => {
    let isMounted = true;

    const loadData = async () => {
      try {
        setLoading(true);
        setStats(null);

        const params =
          timeRange === "custom" ? { startDate, endDate } : { timeRange };
        const response = await acotService.getStats(params);

        if (!isMounted) return;

        setStats(response.stats);
        setLastUpdate(DateTime.now().setZone("America/New_York"));
        setError(null);
      } catch (error) {
        console.error("Error loading data:", error);
        if (isMounted) {
          setError(error.message);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    loadData();
    return () => {
      isMounted = false;
    };
  }, [timeRange, startDate, endDate]);

  // Load smart projection separately
  useEffect(() => {
    let isMounted = true;

    const loadProjection = async () => {
      if (!stats?.periodProgress || stats.periodProgress >= 100) return;

      try {
        setProjectionLoading(true);
        const params =
          timeRange === "custom" ? { startDate, endDate } : { timeRange };
        const response = await acotService.getProjection(params);

        if (!isMounted) return;
        setProjection(response);
      } catch (error) {
        console.error("Error loading projection:", error);
      } finally {
        if (isMounted) {
          setProjectionLoading(false);
        }
      }
    };

    loadProjection();
    return () => {
      isMounted = false;
    };
  }, [timeRange, startDate, endDate, stats?.periodProgress]);

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

    const interval = setInterval(async () => {
      try {
        const [statsResponse, projectionResponse] = await Promise.all([
          acotService.getStats({ timeRange: "today" }),
          acotService.getProjection({ timeRange: "today" }),
        ]);

        setStats(statsResponse.stats);
        setProjection(projectionResponse);
        setLastUpdate(DateTime.now().setZone("America/New_York"));
      } catch (error) {
        console.error("Error auto-refreshing stats:", error);
      }
    }, 60000);

    return () => clearInterval(interval);
  }, [timeRange]);

  // Add function to fetch detail data
  const fetchDetailData = useCallback(
    async (metric) => {
      if (detailData[metric]) return;

      setDetailDataLoading((prev) => ({ ...prev, [metric]: true }));
      try {
              const response = await acotService.getStatsDetails({
        timeRange: "last30days",
        metric,
        daily: true,
      });

      setDetailData((prev) => ({ ...prev, [metric]: response.stats }));
      } catch (error) {
        console.error(`Error fetching detail data for ${metric}:`, error);
      } finally {
        setDetailDataLoading((prev) => ({ ...prev, [metric]: false }));
      }
    },
    [detailData]
  );

  // Add effect to load detail data when metric is selected
  useEffect(() => {
    if (selectedMetric) {
      fetchDetailData(selectedMetric);
    }
  }, [selectedMetric, fetchDetailData]);

  // Add preload effect with throttling
  useEffect(() => {
    // Preload detail data with throttling to avoid overwhelming the server
    const preloadData = async () => {
      const metrics = ["revenue", "orders", "average_order", "shipping"];
      for (const metric of metrics) {
        try {
          await fetchDetailData(metric);
          // Small delay between requests
          await new Promise(resolve => setTimeout(resolve, 25));
        } catch (error) {
          console.error(`Error preloading ${metric}:`, error);
        }
      }
    };
    
    preloadData();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  if (loading && !stats) {
    return (
      <div className="grid grid-cols-4 gap-2">
        <Card className="h-[150px] bg-gradient-to-br from-emerald-900 to-emerald-800 backdrop-blur-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
            <CardTitle className="text-emerald-100 font-bold text-md">
              <Skeleton className="h-4 w-24 bg-emerald-700" />
            </CardTitle>
            <div className="relative p-2">
              <div className="absolute inset-0 rounded-full bg-emerald-300" />
              <Skeleton className="h-5 w-5 bg-emerald-700 relative rounded-full" />
            </div>
          </CardHeader>
          <CardContent className="p-4 pt-0">
            <div className="space-y-2">
              <Skeleton className="h-8 w-20 bg-emerald-700" />
              <div className="flex justify-between items-center">
                <Skeleton className="h-4 w-24 bg-emerald-700" />
                <Skeleton className="h-4 w-12 bg-emerald-700 rounded-full" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="h-[150px] bg-gradient-to-br from-blue-900 to-blue-800 backdrop-blur-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
            <CardTitle className="text-blue-100 font-bold text-md">
              <Skeleton className="h-4 w-24 bg-blue-700" />
            </CardTitle>
            <div className="relative p-2">
              <div className="absolute inset-0 rounded-full bg-blue-300" />
              <Skeleton className="h-5 w-5 bg-blue-700 relative rounded-full" />
            </div>
          </CardHeader>
          <CardContent className="p-4 pt-0">
            <div className="space-y-2">
              <Skeleton className="h-8 w-20 bg-blue-700" />
              <div className="flex justify-between items-center">
                <Skeleton className="h-4 w-24 bg-blue-700" />
                <Skeleton className="h-4 w-12 bg-blue-700 rounded-full" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="h-[150px] bg-gradient-to-br from-violet-900 to-violet-800 backdrop-blur-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
            <CardTitle className="text-violet-100 font-bold text-md">
              <Skeleton className="h-4 w-24 bg-violet-700" />
            </CardTitle>
            <div className="relative p-2">
              <div className="absolute inset-0 rounded-full bg-violet-300" />
              <Skeleton className="h-5 w-5 bg-violet-700 relative rounded-full" />
            </div>
          </CardHeader>
          <CardContent className="p-4 pt-0">
            <div className="space-y-2">
              <Skeleton className="h-8 w-20 bg-violet-700" />
              <div className="flex justify-between items-center">
                <Skeleton className="h-4 w-24 bg-violet-700" />
                <Skeleton className="h-4 w-12 bg-violet-700 rounded-full" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="h-[150px] bg-gradient-to-br from-orange-900 to-orange-800 backdrop-blur-sm">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
            <CardTitle className="text-orange-100 font-bold text-md">
              <Skeleton className="h-4 w-24 bg-orange-700" />
            </CardTitle>
            <div className="relative p-2">
              <div className="absolute inset-0 rounded-full bg-orange-300" />
              <Skeleton className="h-5 w-5 bg-orange-700 relative rounded-full" />
            </div>
          </CardHeader>
          <CardContent className="p-4 pt-0">
            <div className="space-y-2">
              <Skeleton className="h-8 w-20 bg-orange-700" />
              <div className="flex justify-between items-center">
                <Skeleton className="h-4 w-24 bg-orange-700" />
                <Skeleton className="h-4 w-12 bg-orange-700 rounded-full" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

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

  if (!stats) return null;

  const revenueTrend = calculateRevenueTrend();
  const orderTrend = calculateOrderTrend();
  const aovTrend = calculateAOVTrend();

  return (
    <>
      <div className="grid grid-cols-4 gap-2">
        <StatCard
          title="Today's Revenue"
          value={formatCurrency(stats?.revenue || 0)}
          description={
            stats?.periodProgress < 100 ? (
              <div className="flex items-center gap-1">
                <span>Proj: </span>
                {projectionLoading ? (
                  <div className="w-20">
                    <Skeleton className="h-4 w-15 bg-emerald-700" />
                  </div>
                ) : (
                  formatCurrency(
                    projection?.projectedRevenue || stats.projectedRevenue
                  )
                )}
              </div>
            ) : null
          }
          progress={stats?.periodProgress < 100 ? stats.periodProgress : undefined}
          trend={projectionLoading && stats?.periodProgress < 100 ? undefined : revenueTrend?.trend}
          trendValue={
            projectionLoading && stats?.periodProgress < 100 ? (
              <div className="flex items-center gap-1">
                <Skeleton className="h-4 w-4 bg-emerald-700 rounded-full" />
                <Skeleton className="h-4 w-8 bg-emerald-700" />
              </div>
            ) : revenueTrend?.value ? (
              formatPercentage(revenueTrend.value)
            ) : null
          }
          colorClass="text-emerald-200"
          titleClass="text-emerald-100 font-bold text-md"
          descriptionClass="text-emerald-200 text-md font-semibold"
          icon={DollarSign}
          iconColor="text-emerald-900"
          iconBackground="bg-emerald-300"
          onDetailsClick={() => setSelectedMetric("revenue")}
          isLoading={loading || !stats}
          variant="mini"
          background="h-[150px] bg-gradient-to-br from-emerald-900 to-emerald-800"
        />

        <StatCard
          title="Today's Orders"
          value={stats?.orderCount}
          description={`${stats?.itemCount} total items`}
          trend={orderTrend?.trend}
          trendValue={orderTrend?.value ? formatPercentage(orderTrend.value) : null}
          colorClass="text-blue-200"
          titleClass="text-blue-100 font-bold text-md"
          descriptionClass="text-blue-200 text-md font-semibold"
          icon={ShoppingCart}
          iconColor="text-blue-900"
          iconBackground="bg-blue-300"
          onDetailsClick={() => setSelectedMetric("orders")}
          isLoading={loading || !stats}
          variant="mini"
          background="h-[150px] bg-gradient-to-br from-blue-900 to-blue-800"
        />

        <StatCard
          title="Today's AOV"
          value={stats?.averageOrderValue?.toFixed(2)}
          valuePrefix="$"
          description={`${stats?.averageItemsPerOrder?.toFixed(1)} items per order`}
          trend={aovTrend?.trend}
          trendValue={aovTrend?.value ? formatPercentage(aovTrend.value) : null}
          colorClass="text-violet-200"
          titleClass="text-violet-100 font-bold text-md"
          descriptionClass="text-violet-200 text-md font-semibold"
          icon={CircleDollarSign}
          iconColor="text-violet-900"
          iconBackground="bg-violet-300"
          onDetailsClick={() => setSelectedMetric("average_order")}
          isLoading={loading || !stats}
          variant="mini"
          background="h-[150px] bg-gradient-to-br from-violet-900 to-violet-800"
        />

        <StatCard
          title="Shipped Today"
          value={stats?.shipping?.shippedCount || 0}
          description={`${stats?.shipping?.locations?.total || 0} locations`}
          colorClass="text-orange-200"
          titleClass="text-orange-100 font-bold text-md"
          descriptionClass="text-orange-200 text-md font-semibold"
          icon={Package}
          iconColor="text-orange-900"
          iconBackground="bg-orange-300"
          onDetailsClick={() => setSelectedMetric("shipping")}
          isLoading={loading || !stats}
          variant="mini"
          background="h-[150px] bg-gradient-to-br from-orange-900 to-orange-800"
        />
      </div>

      <Dialog
        open={!!selectedMetric}
        onOpenChange={() => setSelectedMetric(null)}
      >
        <DialogContent className={`w-[80vw] h-[80vh] max-w-none p-0 ${
          selectedMetric === 'revenue' ? 'bg-emerald-50 dark:bg-emerald-950/30' :
          selectedMetric === 'orders' ? 'bg-blue-50 dark:bg-blue-950/30' :
          selectedMetric === 'average_order' ? 'bg-violet-50 dark:bg-violet-950/30' :
          selectedMetric === 'shipping' ? 'bg-orange-50 dark:bg-orange-950/30' :
          'bg-white dark:bg-gray-950'
        } backdrop-blur-md border-none`}>
          <div className="transform scale-[2] origin-top-left h-[40vh] w-[40vw]">
            <div className="h-full w-full p-6">
              <DialogHeader>
                <DialogTitle className={`text-2xl font-bold ${
                  selectedMetric === 'revenue' ? 'text-emerald-900 dark:text-emerald-100' :
                  selectedMetric === 'orders' ? 'text-blue-900 dark:text-blue-100' :
                  selectedMetric === 'average_order' ? 'text-violet-900 dark:text-violet-100' :
                  selectedMetric === 'shipping' ? 'text-orange-900 dark:text-orange-100' :
                  'text-gray-900 dark:text-gray-100'
                }`}>
                  {selectedMetric
                    ? `${selectedMetric
                        .split("_")
                        .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                        .join(" ")} Details`
                    : ""}
                </DialogTitle>
              </DialogHeader>
              <div className="mt-4 h-[calc(40vh-4rem)] overflow-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:'none'] [scrollbar-width:'none']">
                {detailDataLoading[selectedMetric] ? (
                  <div className="space-y-4 h-full">
                    {selectedMetric === "shipping" ? (
                      <MiniSkeletonTable 
                        rows={8} 
                        colorScheme={
                          selectedMetric === 'revenue' ? 'emerald' :
                          selectedMetric === 'orders' ? 'blue' :
                          selectedMetric === 'average_order' ? 'violet' :
                          'orange'
                        }
                      />
                    ) : (
                      <>
                        <MiniSkeletonChart
                          type={selectedMetric === "orders" ? "bar" : "line"}
                          metric={selectedMetric}
                        />
                        {selectedMetric === "orders" && (
                          <div className="mt-8">
                            <h3 className={`text-lg font-medium mb-4 ${
                              selectedMetric === 'revenue' ? 'text-emerald-900 dark:text-emerald-200' :
                              selectedMetric === 'orders' ? 'text-blue-900 dark:text-blue-200' :
                              selectedMetric === 'average_order' ? 'text-violet-900 dark:text-violet-200' :
                              selectedMetric === 'shipping' ? 'text-orange-900 dark:text-orange-200' :
                              'text-gray-900 dark:text-gray-200'
                            }`}>
                              Hourly Distribution
                            </h3>
                            <MiniSkeletonChart type="bar" metric={selectedMetric} />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                ) : (
                  <div className="h-full">
                    {selectedMetric === "revenue" && (
                      <RevenueDetails 
                        data={detailData.revenue || []} 
                        colorScheme="emerald"
                      />
                    )}
                    {selectedMetric === "orders" && (
                      <OrdersDetails 
                        data={detailData.orders || []} 
                        colorScheme="blue"
                      />
                    )}
                    {selectedMetric === "average_order" && (
                      <AverageOrderDetails
                        data={detailData.average_order || []}
                        orderCount={stats.orderCount}
                        colorScheme="violet"
                      />
                    )}
                    {selectedMetric === "shipping" && (
                      <ShippingDetails 
                        data={[stats]} 
                        timeRange={timeRange}
                        colorScheme="orange"
                      />
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
};

export default MiniStatCards;
