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 {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { DateTime } from "luxon";
import { Skeleton } from "@/components/dashboard/ui/skeleton";
import { Alert, AlertDescription, AlertTitle } from "@/components/dashboard/ui/alert";
import { AlertCircle, TrendingUp, DollarSign, ShoppingCart, Truck, PiggyBank, ArrowUp,ArrowDown, Banknote, Package } from "lucide-react";
import { formatCurrency, CustomTooltip, processData, StatCard } from "./SalesChart.jsx";

const SkeletonChart = () => (
  <div className="h-[216px]">
    <div className="h-full w-full relative">
      {/* Grid lines */}
      {[...Array(5)].map((_, i) => (
        <div
          key={i}
          className="absolute w-full h-px bg-slate-600"
          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 bg-slate-600 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 bg-slate-600 rounded-sm" />
        ))}
      </div>
      {/* Chart lines */}
      <div className="absolute inset-x-8 bottom-6 top-4">
        <div className="h-full w-full relative">
          <div
            className="absolute inset-0 bg-slate-600 rounded-sm"
            style={{
              opacity: 0.5,
              clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
            }}
          />
        </div>
      </div>
    </div>
  </div>
);

const MiniStatCard = memo(({ 
  title, 
  value, 
  icon: Icon, 
  colorClass, 
  iconColor, 
  iconBackground, 
  background,
  previousValue,
  trend,
  trendValue,
  onClick,
  active = true,
  titleClass = "text-sm font-bold text-gray-100",
  descriptionClass = "text-sm font-semibold text-gray-200"
}) => (
  <Card 
    className={`w-full bg-gradient-to-br from-slate-700 to-slate-600 backdrop-blur-sm ${
      onClick ? 'cursor-pointer transition-all hover:brightness-110' : ''
    } ${!active ? 'opacity-50' : ''}`}
    onClick={onClick}
  >
    <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
      <CardTitle className={titleClass}>
        {title}
      </CardTitle>
      {Icon && (
        <div className="relative p-2">
          <div className={`absolute inset-0 rounded-full ${iconBackground}`} />
          <Icon className={`h-5 w-5 ${iconColor} relative`} />
        </div>
      )}
    </CardHeader>
    <CardContent className="p-4 pt-0">
      <div className="space-y-2">
        <div>
          <div className={`text-3xl font-extrabold ${colorClass}`}>
            {value}
          </div>
          <div className="mt-2 items-center justify-between flex">
            <span className={descriptionClass}>Prev: {previousValue}</span>
            {trend && (
              <span
                className={`flex items-center gap-0 px-1 py-0.5 rounded-full ${
                  trend === 'up'
                    ? 'text-sm font-bold bg-emerald-300 text-emerald-900'
                    : 'text-sm font-bold bg-rose-300 text-rose-900'
                }`}
              >
                {trend === "up" ? (
                  <ArrowUp className="w-4 h-4" />
                ) : (
                  <ArrowDown className="w-4 h-4" />
                )}
                {trendValue}
              </span>
            )}
          </div>
        </div>
      </div>
    </CardContent>
  </Card>
));

MiniStatCard.displayName = "MiniStatCard";

const SkeletonCard = ({ colorScheme = "emerald" }) => (
  <Card className="w-full h-[150px] bg-gradient-to-br from-slate-700 to-slate-600 backdrop-blur-sm">
    <CardHeader className="flex flex-row items-center justify-between space-y-0 p-4 pb-2">
      <CardTitle>
        <div className="space-y-2">
          <Skeleton className={`h-4 w-24 bg-${colorScheme}-300`} />
        </div>
      </CardTitle>
      <div className="relative p-2">
        <div className={`absolute inset-0 rounded-full bg-${colorScheme}-300`} />
        <Skeleton className={`h-5 w-5 bg-${colorScheme}-300 relative rounded-full`} />
      </div>
    </CardHeader>
    <CardContent className="p-4 pt-0">
      <div className="space-y-2">
        <Skeleton className={`h-8 w-20 bg-${colorScheme}-300`} />
        <div className="flex justify-between items-center">
          <Skeleton className={`h-4 w-24 bg-${colorScheme}-300`} />
          <Skeleton className={`h-4 w-12 bg-${colorScheme}-300 rounded-full`} />
        </div>
      </div>
    </CardContent>
  </Card>
);

const MiniSalesChart = ({ className = "" }) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [visibleMetrics, setVisibleMetrics] = useState({
    revenue: true,
    orders: true
  });
  const [summaryStats, setSummaryStats] = useState({
    totalRevenue: 0,
    totalOrders: 0,
    prevRevenue: 0,
    prevOrders: 0,
    periodProgress: 100
  });
  const [projection, setProjection] = useState(null);
  const [projectionLoading, setProjectionLoading] = useState(false);

  const fetchProjection = useCallback(async () => {
    if (summaryStats.periodProgress >= 100) return;
    
    try {
      setProjectionLoading(true);
      const response = await acotService.getProjection({ timeRange: "last30days" });
      setProjection(response);
    } catch (error) {
      console.error("Error loading projection:", error);
    } finally {
      setProjectionLoading(false);
    }
  }, [summaryStats.periodProgress]);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await acotService.getStatsDetails({
        timeRange: "last30days",
        metric: "revenue",
        daily: true,
      });

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

      const stats = Array.isArray(response.stats)
        ? response.stats
        : [];

      const processedData = processData(stats);

      // Calculate totals and growth
      const totals = stats.reduce((acc, day) => ({
        totalRevenue: acc.totalRevenue + (Number(day.revenue) || 0),
        totalOrders: acc.totalOrders + (Number(day.orders) || 0),
        prevRevenue: acc.prevRevenue + (Number(day.prevRevenue) || 0),
        prevOrders: acc.prevOrders + (Number(day.prevOrders) || 0),
        periodProgress: day.periodProgress || 100,
      }), { 
        totalRevenue: 0, 
        totalOrders: 0,
        prevRevenue: 0,
        prevOrders: 0,
        periodProgress: 100
      });

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

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

  useEffect(() => {
    fetchData();
    const intervalId = setInterval(fetchData, 300000);
    return () => clearInterval(intervalId);
  }, [fetchData]);

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

  const toggleMetric = (metric) => {
    setVisibleMetrics(prev => ({
      ...prev,
      [metric]: !prev[metric]
    }));
  };

  if (error) {
    return (
      <Alert variant="destructive" className="bg-white/10 backdrop-blur-sm">
        <AlertCircle className="h-4 w-4" />
        <AlertTitle>Error</AlertTitle>
        <AlertDescription>Failed to load sales data: {error}</AlertDescription>
      </Alert>
    );
  }

  if (loading && !data) {
    return (
      <div className="space-y-2">
        {/* Stat Cards */}
        <div className="grid grid-cols-2 gap-2">
          <SkeletonCard colorScheme="emerald" />
          <SkeletonCard colorScheme="blue" />
        </div>

        {/* Chart Card */}
        <Card className="bg-gradient-to-br from-slate-700 to-slate-600 backdrop-blur-sm">
          <CardContent className="p-4">
            <SkeletonChart />
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {/* Stat Cards */}
      <div className="grid grid-cols-2 gap-2">
        {loading ? (
          <>
            <SkeletonCard colorScheme="emerald" />
            <SkeletonCard colorScheme="blue" />
          </>
        ) : (
          <>
            <MiniStatCard
              title="30 Days Revenue"
              value={formatCurrency(summaryStats.totalRevenue, false)}
              previousValue={formatCurrency(summaryStats.prevRevenue, false)}
              trend={
                summaryStats.periodProgress < 100 
                  ? ((projection?.projectedRevenue || summaryStats.totalRevenue) >= summaryStats.prevRevenue ? "up" : "down")
                  : (summaryStats.totalRevenue >= summaryStats.prevRevenue ? "up" : "down")
              }
              trendValue={
                summaryStats.periodProgress < 100
                  ? `${Math.abs(Math.round(((projection?.projectedRevenue || summaryStats.totalRevenue) - summaryStats.prevRevenue) / summaryStats.prevRevenue * 100))}%`
                  : `${Math.abs(Math.round(((summaryStats.totalRevenue - summaryStats.prevRevenue) / summaryStats.prevRevenue) * 100))}%`
              }
              colorClass="text-emerald-300"
              titleClass="text-emerald-300 font-bold text-md"
              descriptionClass="text-emerald-300 text-md font-semibold pb-1"
              icon={PiggyBank}
              iconColor="text-emerald-900"
              iconBackground="bg-emerald-300"
              onClick={() => toggleMetric('revenue')}
              active={visibleMetrics.revenue}
            />
            <MiniStatCard
              title="30 Days Orders"
              value={summaryStats.totalOrders.toLocaleString()}
              previousValue={summaryStats.prevOrders.toLocaleString()}
              trend={
                summaryStats.periodProgress < 100 
                  ? ((Math.round(summaryStats.totalOrders * (100 / summaryStats.periodProgress))) >= summaryStats.prevOrders ? "up" : "down")
                  : (summaryStats.totalOrders >= summaryStats.prevOrders ? "up" : "down")
              }
              trendValue={
                summaryStats.periodProgress < 100
                  ? `${Math.abs(Math.round(((Math.round(summaryStats.totalOrders * (100 / summaryStats.periodProgress))) - summaryStats.prevOrders) / summaryStats.prevOrders * 100))}%`
                  : `${Math.abs(Math.round(((summaryStats.totalOrders - summaryStats.prevOrders) / summaryStats.prevOrders) * 100))}%`
              }
              colorClass="text-blue-300"
              titleClass="text-blue-300 font-bold text-md"
              descriptionClass="text-blue-300 text-md font-semibold pb-1"
              icon={Truck}
              iconColor="text-blue-900"
              iconBackground="bg-blue-300"
              onClick={() => toggleMetric('orders')}
              active={visibleMetrics.orders}
            />
          </>
        )}
      </div>

      {/* Chart Card */}
      <Card className="bg-gradient-to-br from-slate-700 to-slate-600 backdrop-blur-sm">
        <CardContent className="p-4">
          <div className="h-[216px]">
            {loading ? (
              <div className="h-full w-full relative">
                {/* Grid lines */}
                {[...Array(5)].map((_, i) => (
                  <div
                    key={i}
                    className="absolute w-full h-px bg-slate-600"
                    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 bg-slate-600 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 bg-slate-600 rounded-sm" />
                  ))}
                </div>
                {/* Chart lines */}
                <div className="absolute inset-x-8 bottom-6 top-4">
                  <div className="h-full w-full relative">
                    <div
                      className="absolute inset-0 bg-slate-600 rounded-sm"
                      style={{
                        opacity: 0.5,
                        clipPath: "polygon(0 50%, 100% 20%, 100% 100%, 0 100%)",
                      }}
                    />
                  </div>
                </div>
              </div>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <LineChart
                  data={data}
                  margin={{ top: 0, right: -30, left: -5, bottom: -10 }}
                >
                  <CartesianGrid strokeDasharray="3 3" className="stroke-stone-700" />
                  <XAxis
                    dataKey="timestamp"
                    tickFormatter={formatXAxis}
                    className="text-xs"
                    tick={{ fill: "#f5f5f4" }}
                  />
                  {visibleMetrics.revenue && (
                    <YAxis
                      yAxisId="revenue"
                      tickFormatter={(value) => formatCurrency(value, false)}
                      className="text-xs"
                      tick={{ fill: "#f5f5f4" }}
                    />
                  )}
                  {visibleMetrics.orders && (
                    <YAxis
                      yAxisId="orders"
                      orientation="right"
                      className="text-xs"
                      tick={{ fill: "#f5f5f4" }}
                    />
                  )}
                  <Tooltip
                    content={({ active, payload }) => {
                      if (active && payload && payload.length) {
                        const timestamp = new Date(payload[0].payload.timestamp);
                        return (
                          <Card className="p-2 shadow-lg bg-stone-800 border-none">
                            <CardContent className="p-0 space-y-1">
                              <p className="font-medium text-sm text-stone-100 border-b border-stone-700 pb-1 mb-1">
                                {timestamp.toLocaleDateString([], {
                                  weekday: "short",
                                  month: "short",
                                  day: "numeric"
                                })}
                              </p>
                              {payload
                                .filter(entry => visibleMetrics[entry.dataKey])
                                .map((entry, index) => (
                                  <div key={index} className="flex justify-between items-center text-sm">
                                    <span className="text-stone-200">
                                      {entry.name}:
                                    </span>
                                    <span className="font-medium ml-4 text-stone-100">
                                      {entry.dataKey === 'revenue' 
                                        ? formatCurrency(entry.value)
                                        : entry.value.toLocaleString()}
                                    </span>
                                  </div>
                                ))}
                            </CardContent>
                          </Card>
                        );
                      }
                      return null;
                    }}
                  />
                  {visibleMetrics.revenue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="revenue"
                      name="Revenue"
                      stroke="#10b981"
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {visibleMetrics.orders && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="orders"
                      name="Orders"
                      stroke="#3b82f6"
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                </LineChart>
              </ResponsiveContainer>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default MiniSalesChart; 