import { useMemo, useState } from "react";
import { ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid } from "recharts";
import { formatCompact } from "@/lib/format";

export type TimeframeKey = "7d" | "30d" | "3m" | "6m" | "1y" | "all";
export const TIMEFRAMES: { key: TimeframeKey; label: string; days: number | null }[] = [
  { key: "7d", label: "7D", days: 7 },
  { key: "30d", label: "30D", days: 30 },
  { key: "3m", label: "3M", days: 90 },
  { key: "6m", label: "6M", days: 180 },
  { key: "1y", label: "1Y", days: 365 },
  { key: "all", label: "All", days: null },
];

export type SeriesPoint = { t: number; value: number };

type Props = {
  title: string;
  subtitle?: string;
  data: SeriesPoint[];
  currency?: string;
  color?: string; // css var or hex
  height?: number;
  timeframe: TimeframeKey;
  onTimeframeChange: (k: TimeframeKey) => void;
  format?: "currency" | "number" | "percent";
  emptyLabel?: string;
};

export function TimeframeSwitcher({ value, onChange }: { value: TimeframeKey; onChange: (k: TimeframeKey) => void }) {
  return (
    <div className="glass rounded-full inline-flex p-1 gap-0.5">
      {TIMEFRAMES.map((t) => (
        <button
          key={t.key}
          onClick={() => onChange(t.key)}
          className={`px-2.5 py-1 text-[10px] font-medium rounded-full transition-all ${
            value === t.key ? "bg-gradient-to-br from-electric to-purple text-primary-foreground" : "text-muted-foreground hover:text-foreground"
          }`}
        >
          {t.label}
        </button>
      ))}
    </div>
  );
}

export function AuraLineChart({
  title, subtitle, data, currency = "USD", color = "var(--electric)", height = 180, timeframe, onTimeframeChange, format = "currency", emptyLabel = "Not enough data yet.",
}: Props) {
  const filtered = useMemo(() => {
    const days = TIMEFRAMES.find((t) => t.key === timeframe)?.days;
    if (!days) return data;
    const cutoff = Date.now() - days * 86_400_000;
    return data.filter((d) => d.t >= cutoff);
  }, [data, timeframe]);

  const gradId = `grad-${title.replace(/\s+/g, "-").toLowerCase()}`;
  const first = filtered[0]?.value ?? 0;
  const last = filtered.at(-1)?.value ?? 0;
  const delta = last - first;
  const pct = first !== 0 ? (delta / Math.abs(first)) * 100 : 0;

  const fmt = (n: number) =>
    format === "currency" ? formatCompact(n, currency)
    : format === "percent" ? `${n.toFixed(0)}%`
    : n.toLocaleString();

  return (
    <div className="glass rounded-3xl p-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-[10px] uppercase tracking-widest text-muted-foreground">{title}</p>
          <p className="text-xl font-semibold tabular-nums mt-0.5">{fmt(last)}</p>
          {subtitle && <p className="text-[11px] text-muted-foreground mt-0.5">{subtitle}</p>}
          {filtered.length > 1 && (
            <p className={`text-[11px] font-medium mt-0.5 ${delta >= 0 ? "text-success" : "text-destructive"}`}>
              {delta >= 0 ? "▲" : "▼"} {fmt(Math.abs(delta))} · {pct >= 0 ? "+" : ""}{pct.toFixed(1)}%
            </p>
          )}
        </div>
        <TimeframeSwitcher value={timeframe} onChange={onTimeframeChange} />
      </div>

      <div className="mt-3" style={{ height }}>
        {filtered.length < 2 ? (
          <div className="h-full grid place-items-center text-xs text-muted-foreground">{emptyLabel}</div>
        ) : (
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={filtered} margin={{ top: 6, right: 4, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor={color} stopOpacity={0.35} />
                  <stop offset="100%" stopColor={color} stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid stroke="color-mix(in oklab, var(--foreground) 6%, transparent)" strokeDasharray="3 3" vertical={false} />
              <XAxis dataKey="t" hide />
              <YAxis hide domain={["auto", "auto"]} />
              <Tooltip
                contentStyle={{
                  background: "color-mix(in oklab, var(--surface) 90%, transparent)",
                  border: "1px solid var(--border)",
                  borderRadius: 12,
                  fontSize: 12,
                  color: "var(--foreground)",
                }}
                labelFormatter={(v) => new Date(v as number).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })}
                formatter={(v: any) => [fmt(Number(v)), title]}
              />
              <Area type="monotone" dataKey="value" stroke={color} strokeWidth={2.2} fill={`url(#${gradId})`} isAnimationActive animationDuration={800} />
            </AreaChart>
          </ResponsiveContainer>
        )}
      </div>
    </div>
  );
}

export function useTimeframe(initial: TimeframeKey = "30d") {
  return useState<TimeframeKey>(initial);
}
