import type { CSSProperties } from 'react';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import {
  PROSTHESIS_FALLBACK_COLORS,
  PROSTHESIS_TYPE_COLORS,
  resolveCatalogTypeColor,
} from '@/components/shared/catalog-type-colors';

/**
 * Prosthesis-type colors for lab-facing surfaces (Tasks list, Cases detail group
 * headers / badges). Uses a dedicated pastel map (unique per prosthesis code).
 *
 * Clinic-facing dispatch flows intentionally do NOT use these colors.
 */

/** Dark ink that stays readable on every pastel in the palette. */
const BADGE_INK = '#14253d';

/** Stable catalog index for fallback colors — use sortOrder, not list row position. */
export function prosthesisCatalogColorIndex(
  code: string,
  catalog: readonly Pick<ProsthesisCatalogEntry, 'code' | 'sortOrder'>[],
): number {
  const entry = catalog.find((e) => e.code === code);
  if (entry) return Math.max(0, entry.sortOrder - 1);
  const idx = catalog.findIndex((e) => e.code === code);
  return idx >= 0 ? idx : 0;
}

export function prosthesisTypeColor(code: string, index = 0): string {
  return resolveCatalogTypeColor(code, PROSTHESIS_TYPE_COLORS, index, PROSTHESIS_FALLBACK_COLORS);
}

export function prosthesisTypeColorFromCatalog(
  code: string,
  catalog: readonly Pick<ProsthesisCatalogEntry, 'code' | 'sortOrder'>[],
): string {
  return prosthesisTypeColor(code, prosthesisCatalogColorIndex(code, catalog));
}

/** Filled swatch (small indicator dots). */
export function prosthesisTypeSwatchStyle(code: string, index = 0): CSSProperties {
  return { backgroundColor: prosthesisTypeColor(code, index), borderColor: 'rgba(0, 0, 0, 0.18)' };
}

export function prosthesisTypeSwatchStyleFromCatalog(
  code: string,
  catalog: readonly Pick<ProsthesisCatalogEntry, 'code' | 'sortOrder'>[],
): CSSProperties {
  return prosthesisTypeSwatchStyle(code, prosthesisCatalogColorIndex(code, catalog));
}

/** Pastel pill / banner fill with readable dark text (group headers, badges). */
export function prosthesisTypeBadgeStyle(code: string, index = 0): CSSProperties {
  return {
    backgroundColor: prosthesisTypeColor(code, index),
    borderColor: 'rgba(0, 0, 0, 0.16)',
    color: BADGE_INK,
  };
}

export function prosthesisTypeBadgeStyleFromCatalog(
  code: string,
  catalog: readonly Pick<ProsthesisCatalogEntry, 'code' | 'sortOrder'>[],
): CSSProperties {
  return prosthesisTypeBadgeStyle(code, prosthesisCatalogColorIndex(code, catalog));
}

export function formatToothList(teeth: string[]): string {
  return teeth.join(', ');
}
