"use client";

import { useDashboardStats } from "@/features/dashboard/overview-data";
import { useI18n, useT } from "@/i18n";
import { formatCurrency, formatNumber } from "@/lib/format";
import {
  CHART_PAD,
  CHART_W,
  ChartFrame,
  baselineY,
  compactAxisLabel,
  formatChartDate,
  niceCeil,
  scaleY,
} from "./charts";

export function RevenueTrendWidget() {
  const t = useT();
  const { locale } = useI18n();
  const { data } = useDashboardStats();
  const series = data?.trends.series ?? [];

  if (series.length === 0) {
    return <p className="py-8 text-center text-sm text-muted-foreground">{t("dashboard.trendEmpty")}</p>;
  }

  const max = niceCeil(Math.max(...series.map((p) => p.revenue)));
  const groupW = (CHART_W - CHART_PAD.left - CHART_PAD.right) / series.length;
  const labelStep = Math.max(1, Math.ceil(series.length / 7));
  const baseline = baselineY();

  const points = series.map((p, i) => ({
    date: p.date,
    x: CHART_PAD.left + i * groupW + groupW / 2,
    y: scaleY(p.revenue, max),
  }));

  const line = points.map((p, i) => `${i === 0 ? "M" : "L"}${p.x.toFixed(2)},${p.y.toFixed(2)}`).join(" ");
  const area = `${line} L${points[points.length - 1].x.toFixed(2)},${baseline} L${points[0].x.toFixed(2)},${baseline} Z`;
  const total = series.reduce((sum, p) => sum + p.revenue, 0);
  const last = points[points.length - 1];

  const xLabels = series.map((p, i) => ({
    x: CHART_PAD.left + i * groupW + groupW / 2,
    text: i % labelStep === 0 || i === series.length - 1 ? formatChartDate(p.date, locale) : "",
  }));

  return (
    <div>
      <div className="mb-3 flex flex-wrap items-end justify-between gap-3">
        <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
          {t("widgets.revenueTrend.range", { days: String(data?.trends.days ?? series.length) })}
        </p>
        <p className="numeric text-2xl font-bold tracking-tight text-foreground">
          {formatCurrency(total, "SAR", locale)}
        </p>
      </div>

      <ChartFrame
        max={max}
        yLabel={(v) => compactAxisLabel(v, locale)}
        xLabels={xLabels}
        label={t("widgets.revenueTrend.title")}
      >
        <defs>
          <linearGradient id="kapitano-revenue-fill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="currentColor" stopOpacity={0.22} />
            <stop offset="100%" stopColor="currentColor" stopOpacity={0} />
          </linearGradient>
        </defs>
        <path d={area} fill="url(#kapitano-revenue-fill)" className="text-accent" />
        <path
          d={line}
          fill="none"
          stroke="currentColor"
          strokeWidth={2}
          strokeLinecap="round"
          strokeLinejoin="round"
          vectorEffect="non-scaling-stroke"
          className="text-accent"
        />
        <circle
          cx={last.x}
          cy={last.y}
          r={4}
          fill="currentColor"
          stroke="var(--surface)"
          strokeWidth={4}
          className="text-accent"
        >
          <title>{`${formatChartDate(last.date, "en")}: ${formatNumber(series[series.length - 1].revenue, "en")}`}</title>
        </circle>
      </ChartFrame>

      <p className="mt-3 flex items-center gap-1.5 text-xs text-muted-foreground">
        <span className="h-2.5 w-2.5 rounded-full bg-accent" aria-hidden />
        {t("widgets.revenueTrend.today")}:{" "}
        <span className="numeric font-semibold text-foreground">
          {formatCurrency(series[series.length - 1].revenue, "SAR", locale)}
        </span>
      </p>
    </div>
  );
}