import { Badge } from "@/ui";

function stringToColorPair(str: string) {
  const TEXT_DARKEN_FACTOR = 0.7; // Factor para oscurecer el color del texto
  const BACKGROUND_LIGHTEN_FACTOR = 0.7; // Factor para aclarar el color de fondo

  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }

  let color = "#";
  for (let i = 0; i < 3; i++) {
    const value = (hash >> (i * 8)) & 0xff;
    color += ("00" + value.toString(16)).substr(-2);
  }

  // Convert the color from hex to RGB
  const r = parseInt(color.substr(1, 2), 16);
  const g = parseInt(color.substr(3, 2), 16);
  const b = parseInt(color.substr(5, 2), 16);

  // Generate a darker shade for the text color
  const textColor = `#${((r * TEXT_DARKEN_FACTOR) | 0).toString(16).padStart(2, "0")}${(
    (g * TEXT_DARKEN_FACTOR) |
    0
  )
    .toString(16)
    .padStart(2, "0")}${((b * TEXT_DARKEN_FACTOR) | 0).toString(16).padStart(2, "0")}`;

  // Generate a much lighter shade for the background color
  const bgColor = `#${Math.min(255, Math.floor(r + (255 - r) * BACKGROUND_LIGHTEN_FACTOR))
    .toString(16)
    .padStart(2, "0")}${Math.min(255, Math.floor(g + (255 - g) * BACKGROUND_LIGHTEN_FACTOR))
    .toString(16)
    .padStart(2, "0")}${Math.min(255, Math.floor(b + (255 - b) * BACKGROUND_LIGHTEN_FACTOR))
    .toString(16)
    .padStart(2, "0")}`;

  return [textColor, bgColor];
}

export type ColorBadgeProps = {
  label: string;
  className?: string;
  bgcolor?: string;
};

export const ColorBadge = ({ label, className }: ColorBadgeProps) => {
  const [color, backgroundColor] = stringToColorPair(label);

  return (
    <Badge className={className} style={className ? {} : { backgroundColor, color }}>
      {label}
    </Badge>
  );
};
