import type { CSSProperties } from 'react';
import type { Theme } from '@/styles/theme';
import { getChartAxisColors } from '@/features/dashboard/utils/chartColors';

export function truncateChartLabel(label: string, maxLength = 18): string {
  if (label.length <= maxLength) {
    return label;
  }
  return `${label.slice(0, maxLength - 1)}…`;
}

export function estimateCategoryAxisWidth(
  labels: string[],
  options?: { min?: number; max?: number; charWidth?: number },
): number {
  const min = options?.min ?? 56;
  const max = options?.max ?? 132;
  const charWidth = options?.charWidth ?? 6.5;
  const longest = labels.reduce((acc, label) => Math.max(acc, label.length), 0);
  return Math.min(max, Math.max(min, Math.ceil(longest * charWidth) + 20));
}

export function getBarChartHeight(
  itemCount: number,
  options?: { rowHeight?: number; padding?: number; max?: number; min?: number },
): number {
  const rowHeight = options?.rowHeight ?? 34;
  const padding = options?.padding ?? 44;
  const max = options?.max ?? 220;
  const min = options?.min ?? 104;
  if (itemCount <= 0) {
    return min;
  }
  return Math.min(max, Math.max(min, itemCount * rowHeight + padding));
}

export function getChartAxisTick(theme: Theme, textAnchor: 'end' | 'start' | 'middle' = 'end') {
  const colors = getChartAxisColors(theme);
  return {
    fill: colors.tick,
    fontSize: 11,
    fontWeight: 500,
    textAnchor,
  };
}

export function getChartGridProps(theme: Theme) {
  const colors = getChartAxisColors(theme);
  return {
    stroke: colors.grid,
    strokeDasharray: '4 6',
    vertical: false,
  };
}

export function getChartMargin(variant: 'default' | 'compact' | 'withLegend' = 'default') {
  switch (variant) {
    case 'compact':
      return { top: 6, right: 12, left: 4, bottom: 6 };
    case 'withLegend':
      return { top: 10, right: 12, left: 4, bottom: 32 };
    default:
      return { top: 10, right: 12, left: 4, bottom: 8 };
  }
}

export function getChartAnimationProps() {
  return {
    isAnimationActive: false,
  };
}

export function getChartCursorStyle(theme: Theme): CSSProperties {
  return {
    fill: theme.colors.primary,
    opacity: 0.06,
  };
}
