import React from "react";
import { useQuery } from "@tanstack/react-query";
import { TrendingUp, DollarSign, Percent, Briefcase } from "lucide-react";
import { DashboardMultiStatCardMini } from "@/components/dashboard/shared";
import { acotService } from "@/services/dashboard/acotService";
import config from "@/config";
import { apiFetch } from "@/utils/api";

const fmtK = (value) => {
  if (!value && value !== 0) return "$0";
  if (value >= 1000000) return `$${(value / 1000000).toFixed(1)}M`;
  if (value >= 1000) return `$${(value / 1000).toFixed(0)}K`;
  return `$${value.toFixed(0)}`;
};

const fmtDollars = (value) => {
  if (!value && value !== 0) return "$0";
  return `$${Math.round(value).toLocaleString("en-US")}`;
};

const fmtYear = (value) => {
  if (!value && value !== 0) return "$0";
  if (value >= 1000000) return `$${(value / 1000000).toFixed(2)}M`;
  if (value >= 1000) return `$${(value / 1000).toFixed(0)}K`;
  return `$${value.toFixed(0)}`;
};

const TrendSub = ({ label, trend, suffix = "%", invert = false, decimals = 0 }) => {
  if (label == null) return null;
  const isPositive = trend > 0;
  const isGood = invert ? !isPositive : isPositive;
  const arrow = trend > 0 ? "\u2191" : trend < 0 ? "\u2193" : "";
  const trendColor =
    trend == null || Math.abs(trend) < 0.1
      ? ""
      : isGood
        ? "text-emerald-300"
        : "text-rose-300";
  const formatted = decimals > 0
    ? Math.abs(trend).toFixed(decimals)
    : Math.abs(Math.round(trend));

  return (
    <span className="text-sm font-semibold text-gray-200">
      {label}
      {trend != null && Math.abs(trend) >= 0.1 && (
        <span className={`ml-1.5 ${trendColor}`}>
          {arrow}{formatted}{suffix}
        </span>
      )}
    </span>
  );
};

const MiniBusinessMetrics = () => {
  // 30d forecast revenue
  const { data: forecastData, isLoading: forecastLoading } = useQuery({
    queryKey: ["mini-forecast-30d"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/forecast/metrics`);
      if (!response.ok) throw new Error("Failed to fetch forecast");
      return response.json();
    },
    refetchInterval: 600000,
  });

  // Year revenue estimate (YTD + rest-of-year forecast)
  const { data: yearData, isLoading: yearLoading } = useQuery({
    queryKey: ["mini-year-estimate"],
    queryFn: async () => {
      const response = await apiFetch(`${config.apiUrl}/dashboard/year-revenue-estimate`);
      if (!response.ok) throw new Error("Failed to fetch year estimate");
      return response.json();
    },
    refetchInterval: 600000,
  });

  // Avg revenue per day (last 30 days via ACOT stats)
  const { data: revenueData, isLoading: revenueLoading } = useQuery({
    queryKey: ["mini-avg-revenue-30d"],
    queryFn: () =>
      acotService.getStatsDetails({
        timeRange: "last30days",
        metric: "revenue",
        daily: true,
      }),
    refetchInterval: 300000,
  });

  // Financials for profit margin (last 30 days)
  const { data: financialData, isLoading: financialLoading } = useQuery({
    queryKey: ["mini-financials-30d"],
    queryFn: () => acotService.getFinancials({ timeRange: "last30days" }),
    refetchInterval: 300000,
  });

  // Payroll FTE — use employee-metrics with timeRange for true 30d window
  const { data: fteData, isLoading: payrollLoading } = useQuery({
    queryKey: ["mini-fte-30d"],
    queryFn: () => acotService.getEmployeeMetrics({ timeRange: "last30days" }),
    refetchInterval: 300000,
  });

  const loading =
    forecastLoading || yearLoading || revenueLoading || financialLoading || payrollLoading;

  // --- Avg revenue per day ---
  let avgRevPerDay = 0;
  let prevAvgRevPerDay = 0;
  let revTrend = 0;
  if (revenueData?.stats) {
    const stats = Array.isArray(revenueData.stats) ? revenueData.stats : [];
    if (stats.length > 0) {
      avgRevPerDay = stats.reduce((sum, d) => sum + (d.revenue || 0), 0) / stats.length;
      prevAvgRevPerDay =
        stats.reduce((sum, d) => sum + (d.prevRevenue || 0), 0) / stats.length;
      revTrend =
        prevAvgRevPerDay > 0
          ? ((avgRevPerDay - prevAvgRevPerDay) / prevAvgRevPerDay) * 100
          : 0;
    }
  }

  // --- Profit margin ---
  let margin = 0;
  let prevMargin = null;
  let marginTrend = null;
  if (financialData?.totals) {
    const t = financialData.totals;
    if (Number.isFinite(t.margin)) {
      margin = t.margin;
    } else {
      const income =
        (t.grossSales || 0) - (t.refunds || 0) - (t.discounts || 0) + (t.shippingFees || 0);
      const profit = income - (t.cogs || 0);
      margin = income > 0 ? (profit / income) * 100 : 0;
    }

    const prev = financialData.previousTotals;
    if (prev) {
      if (Number.isFinite(prev.margin)) {
        prevMargin = prev.margin;
      } else {
        const prevIncome =
          (prev.grossSales || 0) -
          (prev.refunds || 0) -
          (prev.discounts || 0) +
          (prev.shippingFees || 0);
        const prevProfit = prevIncome - (prev.cogs || 0);
        prevMargin = prevIncome > 0 ? (prevProfit / prevIncome) * 100 : 0;
      }
    }

    if (financialData.comparison?.margin?.absolute != null) {
      marginTrend = financialData.comparison.margin.absolute;
    } else if (prevMargin != null) {
      marginTrend = margin - prevMargin;
    }
  }

  // --- Payroll FTE (true 30d window from employee-metrics) ---
  const fte = fteData?.totals?.fte ?? 0;
  const prevFte = fteData?.previousTotals?.fte ?? null;
  const fteTrend = fteData?.comparison?.fte?.percentage ?? null;

  const ready =
    !loading &&
    forecastData &&
    yearData &&
    revenueData?.stats &&
    financialData?.totals &&
    fteData?.totals;

  const entries = ready
    ? [
        {
          icon: TrendingUp,
          iconBg: "bg-blue-400",
          label: "Forecast",
          value: fmtK(forecastData.forecastRevenue),
          sub: (
            <span className="text-sm font-semibold text-gray-200">
              {fmtYear(yearData.yearTotal)} for year
            </span>
          ),
        },
        {
          icon: DollarSign,
          iconBg: "bg-emerald-400",
          label: "Avg Revenue/Day",
          value: fmtDollars(avgRevPerDay),
          sub: (
            <TrendSub
              label={`Prev: ${fmtDollars(prevAvgRevPerDay)}`}
              trend={revTrend}
            />
          ),
        },
        {
          icon: Percent,
          iconBg: "bg-purple-400",
          label: "Profit Margin",
          value: `${margin.toFixed(1)}%`,
          sub:
            prevMargin != null ? (
              <TrendSub
                label={`Prev: ${prevMargin.toFixed(1)}%`}
                trend={marginTrend}
                suffix="pp"
                decimals={1}
              />
            ) : undefined,
        },
        {
          icon: Briefcase,
          iconBg: "bg-orange-400",
          label: "Payroll FTE",
          value: fte.toFixed(1),
          sub:
            prevFte != null ? (
              <TrendSub
                label={`Prev: ${prevFte.toFixed(1)}`}
                trend={fteTrend}
              />
            ) : undefined,
        },
      ]
    : [];

  return (
    <DashboardMultiStatCardMini
      title="30 Days"
      entries={entries}
      gradient="custom"
      className="bg-gradient-to-br from-indigo-900/80 to-indigo-700/40"
      loading={!ready}
      skeletonRows={4}
    />
  );
};

export default MiniBusinessMetrics;
