import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Line,
  LineChart,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  type TooltipContentProps,
  type TooltipPayloadEntry,
  type TooltipProps,
  XAxis,
  YAxis,
} from 'recharts';

import { ReactNode } from 'react';

interface ChartContainerProps {
  height?: number;
  children: ReactNode;
}

export function ChartContainer({ height = 300, children }: ChartContainerProps) {
  return (
    <ResponsiveContainer width="100%" height={height}>
      {children as React.ReactElement}
    </ResponsiveContainer>
  );
}

function ChartTooltipContent({ active, payload, label }: TooltipContentProps) {
  if (!active || !payload?.length) return null;

  return (
    <div className="rounded-lg border bg-popover p-3 text-popover-foreground shadow-md">
      <p className="mb-1 text-xs font-medium text-muted-foreground">{label}</p>
      {payload.map((entry: TooltipPayloadEntry, index: number) => (
        <p key={index} className="text-sm font-semibold">
          {String(entry.name)}: {String(entry.value)}
        </p>
      ))}
    </div>
  );
}

export function ChartTooltip(props: TooltipProps) {
  // When a custom formatter is provided, skip the default content component
  // so Recharts applies the formatter natively.
  if (props.formatter) {
    return <Tooltip {...props} />;
  }

  return (
    <Tooltip
      content={<ChartTooltipContent {...(props as TooltipContentProps)} />}
      {...props}
    />
  );
}

export {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Line,
  LineChart,
  Pie,
  PieChart,
  XAxis,
  YAxis,
};
export { CHART_COLORS } from './chart-colors';
