import { TooltipProps } from '../Tooltip';
import { colors } from './colors';

export const blendHexColors = (colorA: string, colorB: string, amount = 0.5): string => {
  const [rA, gA, bA] = colorA.match(/\w\w/g)?.map((c) => parseInt(c, 16)) as number[];
  const [rB, gB, bB] = colorB.match(/\w\w/g)?.map((c) => parseInt(c, 16)) as number[];
  const r = Math.round(rA + (rB - rA) * amount)
    .toString(16)
    .padStart(2, '0');
  const g = Math.round(gA + (gB - gA) * amount)
    .toString(16)
    .padStart(2, '0');
  const b = Math.round(bA + (bB - bA) * amount)
    .toString(16)
    .padStart(2, '0');
  return `#${r}${g}${b}`;
};

export const getFirstChar = (str: string): string => {
  return (str[0] ?? '').toUpperCase();
};

export const getText = (name: string, lastName: string): string => {
  if (name && !lastName) return name[0] + name[1];
  if (lastName && !name) return lastName[0] + lastName[1];
  return name[0] + lastName[0];
};

export const isCyrillic = (str: string): boolean => /[а-яА-ЯЁё]/.test(str);

export const getColorByName = (name: string, lastName: string): string => {
  const nameLocale: keyof typeof colors = isCyrillic(name) ? 'ru' : 'en';
  const lastNameLocale: keyof typeof colors = isCyrillic(lastName) ? 'ru' : 'en';
  const nameFirstLetter = (getFirstChar(name) ?? 'A') as unknown as keyof typeof colors[typeof nameLocale];
  const lastNameFirstLetter = (getFirstChar(lastName) ?? 'A') as unknown as keyof typeof colors[typeof lastNameLocale];

  const colorA = colors[nameLocale][nameFirstLetter] ?? '#3d50b7';
  const colorB = colors[lastNameLocale][lastNameFirstLetter] ?? '#3d50b7';

  return blendHexColors(colorA, colorB, 0.5) ?? colors.en.B;
};

export const getTooltip = (
  name?: string,
  lastName?: string,
  count?: number,
  tooltip?: TooltipProps['title']
): TooltipProps['title'] => {
  if (tooltip) return tooltip;
  if (name || lastName) return `${name ?? ''} ${lastName ?? ''}`;
  return '';
};
