"use client";

import * as React from "react";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { adminReportsTexts } from "@/lib/i18n/admin-reports";

/**
 * The two chart shapes every report tab uses. Data always arrives as plain
 * server-aggregated arrays — no Decimal, no Date, no fetching in here.
 * Palette per CONVENTIONS §9: blue-600 / cyan-500 / emerald-500.
 */

export const REPORT_COLORS = {
  blue: "#2563eb",
  cyan: "#06b6d4",
  emerald: "#10b981",
  amber: "#f59e0b",
  rose: "#f43f5e",
} as const;

export type ReportSeries = {
  /** Key inside each data point. */
  key: string;
  label: string;
  color: string;
  format?: "money" | "number";
  /** Which Y axis the series belongs to. */
  axis?: "left" | "right";
};

export type ReportPoint = { label: string; [key: string]: string | number };

const nf = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });

function formatValue(value: unknown, format: ReportSeries["format"]): string {
  const n = typeof value === "number" ? value : Number(value ?? 0);
  if (!Number.isFinite(n)) return "—";
  return format === "money" ? `$${nf.format(n)}` : nf.format(n);
}

function ChartTooltip({
  active,
  payload,
  label,
  series,
}: {
  active?: boolean;
  payload?: Array<{ payload?: ReportPoint }>;
  label?: string | number;
  series: ReportSeries[];
}) {
  if (!active || !payload?.length) return null;
  const point = payload[0]?.payload;
  if (!point) return null;
  return (
    <div className="rounded-lg border bg-card px-2.5 py-2 text-xs text-foreground shadow-md">
      <p className="mb-1 font-medium">{label}</p>
      {series.map((s) => (
        <p key={s.key} className="flex items-center gap-1.5">
          <span
            className="size-2 shrink-0 rounded-full"
            style={{ background: s.color }}
          />
          {s.label}
          <span className="ml-auto pl-4 font-mono tabular-nums">
            {formatValue(point[s.key], s.format)}
          </span>
        </p>
      ))}
    </div>
  );
}

function Legend({ series }: { series: ReportSeries[] }) {
  return (
    <div className="mb-1 flex flex-wrap items-center gap-x-4 gap-y-1">
      {series.map((s) => (
        <span
          key={s.key}
          className="inline-flex items-center gap-1.5 text-[11px] text-muted-foreground"
        >
          <span
            className="size-2 rounded-full"
            style={{ background: s.color }}
          />
          {s.label}
        </span>
      ))}
    </div>
  );
}

function EmptyChart({ height }: { height: string }) {
  return (
    <div
      className="flex flex-col items-center justify-center gap-1 rounded-xl border border-dashed text-center"
      style={{ height }}
    >
      <p className="text-sm font-medium">{adminReportsTexts.common.noData}</p>
      <p className="text-xs text-muted-foreground">
        {adminReportsTexts.common.noDataHint}
      </p>
    </div>
  );
}

function hasAnyValue(data: ReportPoint[], series: ReportSeries[]): boolean {
  return data.some((point) =>
    series.some((s) => {
      const n = Number(point[s.key] ?? 0);
      return Number.isFinite(n) && n !== 0;
    }),
  );
}

/** Time-series area chart (deposits/day, orders/day, profit/day, signups/day). */
export function ReportAreaChart({
  data,
  series,
  height = 260,
}: {
  data: ReportPoint[];
  series: ReportSeries[];
  height?: number;
}) {
  if (data.length === 0 || !hasAnyValue(data, series)) {
    return <EmptyChart height={`${height}px`} />;
  }

  return (
    <div className="w-full text-muted-foreground">
      <Legend series={series} />
      <div style={{ height }}>
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -14 }}>
            <defs>
              {series.map((s) => (
                <linearGradient
                  key={s.key}
                  id={`rpt-fill-${s.key}`}
                  x1="0"
                  y1="0"
                  x2="0"
                  y2="1"
                >
                  <stop offset="0%" stopColor={s.color} stopOpacity={0.32} />
                  <stop offset="100%" stopColor={s.color} stopOpacity={0} />
                </linearGradient>
              ))}
            </defs>

            <CartesianGrid
              strokeDasharray="3 3"
              vertical={false}
              stroke="currentColor"
              strokeOpacity={0.15}
            />
            <XAxis
              dataKey="label"
              tickLine={false}
              axisLine={false}
              interval="preserveStartEnd"
              minTickGap={20}
              tick={{ fontSize: 11, fill: "currentColor" }}
            />
            <YAxis
              yAxisId="left"
              tickLine={false}
              axisLine={false}
              width={46}
              tick={{ fontSize: 11, fill: "currentColor" }}
            />
            <YAxis yAxisId="right" orientation="right" hide />
            <Tooltip
              content={<ChartTooltip series={series} />}
              cursor={{ stroke: REPORT_COLORS.blue, strokeOpacity: 0.2 }}
            />

            {series.map((s) => (
              <Area
                key={s.key}
                yAxisId={s.axis === "right" ? "right" : "left"}
                type="monotone"
                dataKey={s.key}
                stroke={s.color}
                strokeWidth={2}
                fill={`url(#rpt-fill-${s.key})`}
                dot={false}
                activeDot={{ r: 3 }}
              />
            ))}
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

/** Ranking bar chart (profit by provider, top services). Horizontal by default. */
export function ReportBarChart({
  data,
  series,
  horizontal = true,
  height,
}: {
  data: ReportPoint[];
  series: ReportSeries[];
  horizontal?: boolean;
  height?: number;
}) {
  const computed = height ?? (horizontal ? Math.max(180, data.length * 30 + 40) : 260);

  if (data.length === 0 || !hasAnyValue(data, series)) {
    return <EmptyChart height={`${computed}px`} />;
  }

  return (
    <div className="w-full text-muted-foreground">
      <Legend series={series} />
      <div style={{ height: computed }}>
        <ResponsiveContainer width="100%" height="100%">
          <BarChart
            data={data}
            layout={horizontal ? "vertical" : "horizontal"}
            margin={{ top: 4, right: 12, bottom: 0, left: horizontal ? 4 : -14 }}
            barGap={2}
          >
            <CartesianGrid
              strokeDasharray="3 3"
              horizontal={!horizontal}
              vertical={horizontal}
              stroke="currentColor"
              strokeOpacity={0.15}
            />
            {horizontal ? (
              <XAxis
                type="number"
                tickLine={false}
                axisLine={false}
                tick={{ fontSize: 11, fill: "currentColor" }}
              />
            ) : (
              <XAxis
                dataKey="label"
                tickLine={false}
                axisLine={false}
                tick={{ fontSize: 11, fill: "currentColor" }}
              />
            )}
            {horizontal ? (
              <YAxis
                type="category"
                dataKey="label"
                tickLine={false}
                axisLine={false}
                width={140}
                tick={{ fontSize: 11, fill: "currentColor" }}
              />
            ) : (
              <YAxis
                tickLine={false}
                axisLine={false}
                width={46}
                tick={{ fontSize: 11, fill: "currentColor" }}
              />
            )}
            <Tooltip
              content={<ChartTooltip series={series} />}
              cursor={{ fill: "currentColor", fillOpacity: 0.06 }}
            />
            {series.map((s) => (
              <Bar
                key={s.key}
                dataKey={s.key}
                fill={s.color}
                radius={horizontal ? [0, 4, 4, 0] : [4, 4, 0, 0]}
                maxBarSize={horizontal ? 14 : 34}
              />
            ))}
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
