import React, { useState, useEffect, useCallback } from "react";
import { acotService } from "@/services/dashboard/acotService";
import {
  Card,
  CardContent,
} from "@/components/ui/card";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { AlertCircle, PiggyBank, Truck } from "lucide-react";
import { formatCurrency, processData } from "./SalesChart.jsx";
import { METRIC_COLORS } from "@/lib/dashboard/designTokens";
import {
  DashboardStatCardMini,
  DashboardStatCardMiniSkeleton,
  ChartSkeleton,
  TOOLTIP_THEMES,
} from "@/components/dashboard/shared";

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

  // Helper to calculate trend values (positive = up, negative = down)
  const getRevenueTrendValue = () => {
    const current = summaryStats.periodProgress < 100
      ? (projection?.projectedRevenue || summaryStats.totalRevenue)
      : summaryStats.totalRevenue;
    if (!summaryStats.prevRevenue) return 0;
    return ((current - summaryStats.prevRevenue) / summaryStats.prevRevenue) * 100;
  };

  const getOrdersTrendValue = () => {
    const projected = Math.round(summaryStats.totalOrders * (100 / summaryStats.periodProgress));
    const current = summaryStats.periodProgress < 100 ? projected : summaryStats.totalOrders;
    if (!summaryStats.prevOrders) return 0;
    return ((current - summaryStats.prevOrders) / summaryStats.prevOrders) * 100;
  };

  if (loading && !data) {
    return (
      <div className="space-y-2">
        {/* Stat Cards */}
        <div className="grid grid-cols-2 gap-2">
          <DashboardStatCardMiniSkeleton gradient="slate" />
          <DashboardStatCardMiniSkeleton gradient="slate" />
        </div>

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

  return (
    <div className="space-y-2">
      {/* Stat Cards */}
      <div className="grid grid-cols-2 gap-2">
        {loading && !data?.length ? (
          <>
            <DashboardStatCardMiniSkeleton gradient="slate" />
            <DashboardStatCardMiniSkeleton gradient="slate" />
          </>
        ) : (
          <>
            <DashboardStatCardMini
              title="30 Days Revenue"
              value={formatCurrency(summaryStats.totalRevenue, false)}
              subtitle={`Prev: ${formatCurrency(summaryStats.prevRevenue, false)}`}
              trend={{ value: getRevenueTrendValue() }}
              icon={PiggyBank}
              iconBackground="bg-emerald-400"
              gradient="slate"
              className={!visibleMetrics.revenue ? 'opacity-50' : ''}
              onClick={() => toggleMetric('revenue')}
            />
            <DashboardStatCardMini
              title="30 Days Orders"
              value={summaryStats.totalOrders.toLocaleString()}
              subtitle={`Prev: ${summaryStats.prevOrders.toLocaleString()}`}
              trend={{ value: getOrdersTrendValue() }}
              icon={Truck}
              iconBackground="bg-blue-400"
              gradient="slate"
              className={!visibleMetrics.orders ? 'opacity-50' : ''}
              onClick={() => toggleMetric('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 && !data?.length ? (
              <ChartSkeleton height="sm" withCard={false} />
            ) : (
              <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);
                        const styles = TOOLTIP_THEMES.stone;
                        return (
                          <div className={styles.container}>
                            <p className={styles.header}>
                              {timestamp.toLocaleDateString([], {
                                weekday: "short",
                                month: "short",
                                day: "numeric"
                              })}
                            </p>
                            <div className={styles.content}>
                              {payload
                                .filter(entry => visibleMetrics[entry.dataKey])
                                .map((entry, index) => (
                                  <div key={index} className={styles.row}>
                                    <span className={styles.name}>
                                      {entry.name}
                                    </span>
                                    <span className={styles.value}>
                                      {entry.dataKey === 'revenue'
                                        ? formatCurrency(entry.value)
                                        : entry.value.toLocaleString()}
                                    </span>
                                  </div>
                                ))}
                            </div>
                          </div>
                        );
                      }
                      return null;
                    }}
                  />
                  {visibleMetrics.revenue && (
                    <Line
                      yAxisId="revenue"
                      type="monotone"
                      dataKey="revenue"
                      name="Revenue"
                      stroke={METRIC_COLORS.revenue}
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                  {visibleMetrics.orders && (
                    <Line
                      yAxisId="orders"
                      type="monotone"
                      dataKey="orders"
                      name="Orders"
                      stroke={METRIC_COLORS.orders}
                      strokeWidth={2}
                      dot={false}
                    />
                  )}
                </LineChart>
              </ResponsiveContainer>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

export default MiniSalesChart; 