import type {
  ConditionalFormatRule,
  SpreadsheetColumnConfig,
} from '../types';
import { formatCellDisplay } from './useAutoMeasure';

export function shouldShowSuffix(displayText: string): boolean {
  if (!displayText) return false;
  if (displayText === '#ERROR' || displayText === '-') return false;
  return true;
}

export function formatCellWithSuffix(
  value: unknown,
  colCfg?: SpreadsheetColumnConfig,
): string {
  const cellType =
    colCfg?.cellType === 'formula' ? 'number' : (colCfg?.cellType ?? 'text');
  const base = formatCellDisplay(value, cellType);
  if (!shouldShowSuffix(base) || !colCfg?.suffix) return base;
  return base + colCfg.suffix;
}

function resolveRuleStyle(
  rule: ConditionalFormatRule,
): { bgColor?: string; textColor?: string } {
  const mode = rule.colorMode ?? 'background';
  if (mode === 'text') {
    return rule.textColor ? { textColor: rule.textColor } : {};
  }
  if (mode === 'both') {
    return {
      bgColor: rule.bgColor,
      textColor: rule.textColor,
    };
  }
  return rule.bgColor ? { bgColor: rule.bgColor } : {};
}

export function resolveConditionalStyle(
  colCfg: SpreadsheetColumnConfig,
  numericValue: number | null,
): { bgColor?: string; textColor?: string } | undefined {
  const rules = colCfg.conditionalFormat;
  if (rules == null || numericValue == null || Number.isNaN(numericValue)) {
    return undefined;
  }
  if (rules.gt && numericValue > rules.gt.threshold) {
    return resolveRuleStyle(rules.gt);
  }
  if (rules.lt && numericValue < rules.lt.threshold) {
    return resolveRuleStyle(rules.lt);
  }
  return undefined;
}
