"use client";

import * as React from "react";
import * as Recharts from "recharts";
import { cn } from "@/lib/utils";

// --------------------------------------------------
// 1) CHART CONTEXT
// --------------------------------------------------

export type ChartConfig = Record<
  string,
  {
    label?: React.ReactNode;
    icon?: React.ComponentType;
    color?: string;
  }
>;

const ChartContext = React.createContext<{ config: ChartConfig } | null>(null);

function useChart() {
  const ctx = React.useContext(ChartContext);
  if (!ctx) throw new Error("useChart must be inside ChartContainer");
  return ctx;
}

// --------------------------------------------------
// 2) CHART CONTAINER
// --------------------------------------------------

export const ChartContainer = React.forwardRef<
  HTMLDivElement,
  {
    config: ChartConfig;
    className?: string;
    children: React.ReactNode;
  }
>(({ config, className, children }, ref) => {
  return (
    <ChartContext.Provider value={{ config }}>
      <div ref={ref} className={cn("relative w-full h-full", className)}>
        <Recharts.ResponsiveContainer>
  {React.isValidElement(children)
    ? children
    : React.createElement(React.Fragment, null, children)}
</Recharts.ResponsiveContainer>
      </div>
    </ChartContext.Provider>
  );
});

ChartContainer.displayName = "ChartContainer";

// --------------------------------------------------
// 3) TOOLTIP (fully patched – no TS errors, no payload type checks)
// --------------------------------------------------

export const ChartTooltip = (Recharts.Tooltip as unknown) as React.FC<any>;

export const ChartTooltipContent = React.forwardRef<HTMLDivElement, any>(
  (props, ref) => {
    const { config } = useChart();

    const active = props?.active;
    const payload = Array.isArray(props?.payload) ? props.payload : [];
    const label = props?.label;
    const className = props?.className;
    const hideLabel = props?.hideLabel ?? false;
    const nameKey = props?.nameKey;
    const color = props?.color;

    if (!active || payload.length === 0) return null;

    const first = payload[0];

    const labelText =
      !hideLabel &&
      (config[first?.name]?.label ??
        config[label]?.label ??
        first?.name ??
        label);

    return (
      <div
        ref={ref}
        className={cn(
          "min-w-[8rem] rounded-md border border-border/40 bg-background p-2 text-xs shadow-xl",
          className
        )}
      >
        {labelText && (
          <div className="font-medium mb-1 text-foreground">{labelText}</div>
        )}

        <div className="flex flex-col gap-1">
          {payload.map((item: any, i: number) => {
            const k = nameKey || item?.dataKey || "value";
            const conf = config[k];
            const indicatorColor = color || item?.color || item?.payload?.fill;

            return (
              <div key={i} className="flex justify-between items-center gap-2">
                <div className="flex items-center gap-2">
                  <span
                    className="h-2.5 w-2.5 rounded-sm"
                    style={{ background: indicatorColor }}
                  />
                  <span className="text-muted-foreground">
                    {conf?.label ?? item?.name}
                  </span>
                </div>

                {item?.value !== undefined && (
                  <span className="font-mono text-foreground">
                    {item.value.toLocaleString()}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
);

ChartTooltipContent.displayName = "ChartTooltipContent";

// --------------------------------------------------
// 4) LEGEND (also patched for Recharts v3)
// --------------------------------------------------

export const ChartLegend = (Recharts.Legend as unknown) as React.FC<any>;

export const ChartLegendContent = React.forwardRef<HTMLDivElement, any>(
  (props, ref) => {
    const { config } = useChart();

    const payload = Array.isArray(props?.payload) ? props.payload : [];
    const nameKey = props?.nameKey;
    const className = props?.className;

    if (!payload.length) return null;

    return (
      <div
        ref={ref}
        className={cn(
          "flex items-center justify-center gap-4 py-2",
          className
        )}
      >
        {payload.map((item: any, i: number) => {
          const key = nameKey || item?.dataKey || "value";
          const conf = config[key];

          return (
            <div key={i} className="flex items-center gap-2">
              <span
                className="h-2.5 w-2.5 rounded-sm"
                style={{ background: item?.color }}
              />
              <span>{conf?.label ?? item?.value}</span>
            </div>
          );
        })}
      </div>
    );
  }
);

ChartLegendContent.displayName = "ChartLegendContent";

// --------------------------------------------------
// EXPORT
// --------------------------------------------------

export const ChartStyle = () => null;
