import React from "react";
import { useQuery } from "@tanstack/react-query";
import { acotService } from "@/services/dashboard/acotService";
import { Card, CardContent } from "@/components/ui/card";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { AlertCircle, PiggyBank, ShoppingCart } from "lucide-react";
import { formatCurrency } from "./SalesChart.jsx";
import { PHASE_CONFIG, PHASE_KEYS_WITH_UNKNOWN as PHASE_KEYS } from "@/utils/lifecyclePhases";
import config from "@/config";
import { apiFetch } from "@/utils/api";
import {
  DashboardStatCardMini,
  DashboardStatCardMiniSkeleton,
  ChartSkeleton,
  TOOLTIP_THEMES,
} from "@/components/dashboard/shared";

const formatCompactCurrency = (value) => {
  if (!value || isNaN(value)) return "$0";
  if (value >= 1_000_000) return `$${(value / 1_000_000).toFixed(1)}M`;
  if (value >= 1_000) return `$${(value / 1_000).toFixed(1)}k`;
  return `$${Math.round(value)}`;
};

const formatFullCurrency = (value) => {
  if (!value || isNaN(value)) return "$0";
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
};

const MiniSalesChart = ({ className = "" }) => {
  const { data: revenueStats, isLoading: statsLoading } = useQuery({
    queryKey: ["mini-sales-stats-30d"],
    queryFn: async () => {
      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 : [];
      return 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 }
      );
    },
    refetchInterval: 300000,
  });

  const summaryStats = revenueStats ?? {
    totalRevenue: 0, totalOrders: 0, prevRevenue: 0, prevOrders: 0, periodProgress: 100,
  };

  const { data: projection } = useQuery({
    queryKey: ["mini-sales-projection-30d"],
    queryFn: () => acotService.getProjection({ timeRange: "last30days" }),
    enabled: summaryStats.periodProgress < 100,
    refetchInterval: 300000,
  });

  const { data: chartData, isLoading: chartLoading, error } = useQuery({
    queryKey: ["mini-sales-chart-30d"],
    queryFn: async () => {
      const now = new Date();
      const thirtyDaysAgo = new Date(now);
      thirtyDaysAgo.setDate(now.getDate() - 30);
      const params = new URLSearchParams({
        startDate: thirtyDaysAgo.toISOString(),
        endDate: now.toISOString(),
      });
      const response = await apiFetch(`${config.apiUrl}/dashboard/sales/metrics?${params}`);
      if (!response.ok) throw new Error("Failed to fetch sales metrics");
      return response.json();
    },
    refetchInterval: 300000,
  });

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

  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.message}</AlertDescription>
      </Alert>
    );
  }

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

  const dailyPhase = chartData?.dailySalesByPhase || [];
  const phaseBreakdown = chartData?.phaseBreakdown || [];

  const activePhases = phaseBreakdown
    .filter((p) => p.revenue > 0)
    .sort((a, b) => b.revenue - a.revenue);

  return (
    <div className="space-y-2">
      {/* Stat Cards */}
      <div className="grid grid-cols-2 gap-2">
        {statsLoading ? (
          <>
            <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"
            />
            <DashboardStatCardMini
              title="30 Days Orders"
              value={summaryStats.totalOrders.toLocaleString()}
              subtitle={`Prev: ${summaryStats.prevOrders.toLocaleString()}`}
              trend={{ value: getOrdersTrendValue() }}
              icon={ShoppingCart}
              iconBackground="bg-blue-400"
              gradient="slate"
            />
          </>
        )}
      </div>

      {/* Chart Card */}
      <Card className="bg-gradient-to-br from-slate-800/70 to-slate-700/50 backdrop-blur-xl border-white/[0.08] ring-1 ring-white/[0.05] shadow-lg shadow-black/20">
        <CardContent className="p-4">
          {chartLoading ? (
            <>
              <div className="h-[180px]">
                <ChartSkeleton type="area" height="sm" withCard={false} />
              </div>
              <div className="mt-2 space-y-1.5">
                <div className="h-2 rounded-full bg-white/[0.06] animate-pulse" />
                <div className="flex justify-center gap-x-3 gap-y-0.5">
                  {[48, 40, 56, 52, 44].map((w, i) => (
                    <div key={i} className="flex items-center gap-1">
                      <div className="h-2 w-2 rounded-sm bg-white/[0.08] animate-pulse" />
                      <div className="h-2.5 rounded bg-white/[0.06] animate-pulse" style={{ width: w }} />
                    </div>
                  ))}
                </div>
              </div>
            </>
          ) : (
            <>
              <div className="h-[180px]">
                <ResponsiveContainer width="100%" height="100%">
                  <AreaChart
                    data={dailyPhase}
                    margin={{ top: 0, right: 0, left: -5, bottom: -10 }}
                  >
                    <XAxis
                      dataKey="date"
                      tickFormatter={formatXAxis}
                      className="text-xs"
                      tick={{ fill: "#e2e8f0" }}
                      tickLine={false}
                      axisLine={false}
                    />
                    <YAxis
                      tickFormatter={formatCompactCurrency}
                      className="text-xs"
                      tick={{ fill: "#e2e8f0" }}
                      tickLine={false}
                      axisLine={false}
                    />
                    <Tooltip
                      content={({ active, payload }) => {
                        if (!active || !payload?.length) return null;
                        const dateStr = payload[0]?.payload?.date;
                        const date = dateStr ? new Date(dateStr) : null;
                        const styles = TOOLTIP_THEMES.stone;
                        const items = payload
                          .filter((entry) => entry.value > 0)
                          .sort((a, b) => b.value - a.value);
                        const total = items.reduce((sum, entry) => sum + (entry.value || 0), 0);
                        return (
                          <div className={styles.container}>
                            {date && (
                              <p className={styles.header}>
                                {date.toLocaleDateString([], {
                                  weekday: "short",
                                  month: "short",
                                  day: "numeric",
                                })}
                              </p>
                            )}
                            <div className={styles.content}>
                              {items.map((entry, index) => {
                                const cfg = PHASE_CONFIG[entry.dataKey] || {};
                                return (
                                  <div key={index} className={styles.row}>
                                    <span className="flex items-center gap-1.5">
                                      <span
                                        className="inline-block h-2 w-2 rounded-full shrink-0"
                                        style={{ backgroundColor: entry.color }}
                                      />
                                      <span className={styles.name}>
                                        {cfg.label || entry.name}
                                      </span>
                                    </span>
                                    <span className={styles.value}>
                                      {formatFullCurrency(entry.value)}
                                    </span>
                                  </div>
                                );
                              })}
                              {items.length > 1 && (
                                <div className={`${styles.row} border-t border-white/10 pt-1 mt-1`}>
                                  <span className={styles.name}>Total</span>
                                  <span className={styles.value}>
                                    {formatFullCurrency(total)}
                                  </span>
                                </div>
                              )}
                            </div>
                          </div>
                        );
                      }}
                    />
                    {PHASE_KEYS.map((phase) => {
                      const cfg = PHASE_CONFIG[phase];
                      return (
                        <Area
                          key={phase}
                          type="monotone"
                          dataKey={phase}
                          name={phase}
                          stackId="a"
                          stroke={cfg.color}
                          fill={cfg.color}
                          fillOpacity={0.7}
                        />
                      );
                    })}
                  </AreaChart>
                </ResponsiveContainer>
              </div>

              {/* Phase breakdown bar + legend */}
              {activePhases.length > 0 && (
                <div className="mt-2 space-y-1.5">
                  {(() => {
                    let pos = 0;
                    const stops = activePhases.flatMap((p) => {
                      const cfg = PHASE_CONFIG[p.phase] || { color: "#94A3B8" };
                      const start = pos;
                      pos += p.percentage;
                      return [`${cfg.color} ${start}%`, `${cfg.color} ${pos}%`];
                    });
                    return (
                      <div
                        className="h-2 rounded-full ring-1 ring-white/20"
                        style={{ background: `linear-gradient(to right, ${stops.join(', ')})` }}
                      />
                    );
                  })()}
                  <div className="flex justify-center gap-x-3">
                    {activePhases.slice(0, 5).map((p) => {
                      const cfg = PHASE_CONFIG[p.phase] || { label: p.phase, color: "#94A3B8" };
                      return (
                        <span key={p.phase} className="flex items-center gap-1 text-[11.5px] text-slate-200/80 whitespace-nowrap">
                          <span
                            className="inline-block h-2 w-2 rounded-sm shrink-0"
                            style={{ backgroundColor: cfg.color }}
                          />
                          {cfg.label}
                        </span>
                      );
                    })}
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default MiniSalesChart;
