"use client";

import { useTranslation } from "react-i18next";
import {
  CHART_BRAND_DARK,
  formatCellValue,
  formatXAxisTick,
} from "@/modules/ee/analysis/charts/lib/chart-utils";
import { formatCubeColumnHeader } from "@/modules/ee/analysis/lib/schema-definition";

interface TooltipPayloadItem {
  dataKey?: string;
  name?: string | number;
  value?: unknown;
  color?: string;
  payload?: { fill?: string; tooltipLabel?: string } & Record<string, unknown>;
}

interface RechartsTooltipProps {
  active?: boolean;
  payload?: TooltipPayloadItem[];
  label?: string | number;
  /** Formats the header (dimension value); defaults to the generic date/string formatting. */
  labelFormatter?: (value: unknown) => string;
  /** Suppress the header entirely for measure-only charts, where the label is a meaningless
   * fallback value (e.g. a stray "1") rather than a real category. */
  hideLabel?: boolean;
  /** Response base column on the hovered row, printed as "n = …" under the values. */
  responseBaseKey?: string;
  /** Display label per data key, for series whose key is synthetic (one series per group value). */
  seriesLabels?: Record<string, string>;
  /** Formats a hovered value by the measure it belongs to (NPS whole, CSAT percent, …). */
  valueFormatter?: (dataKey: string, value: unknown, row: Record<string, unknown> | undefined) => string;
}

export const PolishedChartTooltip = ({
  active,
  payload,
  label,
  labelFormatter,
  hideLabel = false,
  responseBaseKey,
  seriesLabels,
  valueFormatter,
}: Readonly<RechartsTooltipProps>) => {
  const { t } = useTranslation();
  if (!active || !payload?.length) return null;

  // Pies leave `label` empty and put the slice name on payload[0].name.
  const headerSource = label != null && String(label).length > 0 ? label : (payload[0]?.name ?? "");
  const formatHeader = labelFormatter ?? formatXAxisTick;
  const headerText = hideLabel ? "" : formatHeader(headerSource);
  // Skipped when the base is itself one of the plotted values (a breakdown of npsCount).
  const baseValue = responseBaseKey
    ? Number(payload[0]?.payload?.[responseBaseKey] ?? Number.NaN)
    : Number.NaN;
  const showBase = Number.isFinite(baseValue) && !payload.some((item) => item.dataKey === responseBaseKey);

  return (
    <div className="border-border/50 max-w-xs min-w-[180px] rounded-lg border bg-white px-3 py-2.5 shadow-lg dark:bg-gray-950">
      {headerText && <div className="text-foreground mb-2 text-sm font-medium break-words">{headerText}</div>}
      <div className="flex flex-col gap-1.5">
        {payload.map((item) => {
          const key = item.dataKey ?? String(item.name ?? "");
          // Rows pivoted from measures (see pivotMeasuresToCategories) carry their translated
          // label on the row itself; otherwise the dataKey is a Cube column we can format.
          const rowLabel =
            item.payload?.tooltipLabel ?? seriesLabels?.[key] ?? formatCubeColumnHeader(key, t);
          // payload.fill (per-row data.fill / pie <Cell>) wins over the Bar's series fallback.
          const indicatorColor = item.payload?.fill ?? item.color ?? CHART_BRAND_DARK;
          return (
            <div key={key} className="flex items-center justify-between gap-3">
              <div className="flex min-w-0 items-center gap-2">
                <div className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: indicatorColor }} />
                <span className="text-muted-foreground text-sm break-words">{rowLabel}</span>
              </div>
              <span className="text-foreground shrink-0 text-sm font-medium tabular-nums">
                {valueFormatter ? valueFormatter(key, item.value, item.payload) : formatCellValue(item.value)}
              </span>
            </div>
          );
        })}
      </div>
      {showBase && (
        <div className="text-muted-foreground mt-2 border-t border-slate-100 pt-1.5 text-xs tabular-nums">
          {t("workspace.analysis.charts.tooltip_response_base", { count: baseValue })}
        </div>
      )}
    </div>
  );
};
