import React from "react";
import { Tag, EntityType } from "../types";
import { Checkbox } from "../../Checkbox";
import { InlineTagsProps } from "./types";
import "./styles.scss";

const Inline: React.FC<InlineTagsProps> = ({
  tags = [],
  value = [],
  onChange,
  disabled = false,
  disableUntaggedSelection = false,
}) => {
  // Función para determinar si un tag está seleccionado
  const isTagSelected = (tagId: number): boolean => {
    return value?.some((v: any) => v.id === tagId);
  };

  // Función para manejar el cambio de selección
  const handleTagChange = (tag: Tag) => {
    if (disabled) return;

    const exists = value?.some((v: any) => v.id === tag.id);
    let newSelected: any[] = [];

    if (exists) {
      // Deseleccionar el tag
      newSelected = value?.filter((v: any) => v.id !== tag.id) || [];
    } else {
      // Seleccionar el tag
      const tagToAdd = {
        id: tag.id,
        label: tag.label,
        color: tag.color,
        name: EntityType.Tag,
        path: tag.path,
      };
      newSelected = [...(value || []), tagToAdd];
    }

    if (onChange) {
      onChange(newSelected);
    }
  };

  // Función para obtener los tags hijos de un tag padre
  const getChildTags = (parentId: number): Tag[] => {
    return tags.filter((tag) => tag.parentId === parentId);
  };

  // Función recursiva para renderizar un tag y sus hijos
  const renderTag = (tag: Tag, level: number = 0): JSX.Element | null => {
    if (tag.id === -1 && disableUntaggedSelection) {
      return null;
    }
    const childTags = getChildTags(tag.id);
    const isSelected = isTagSelected(tag.id);

    return (
      <div key={tag.id} className="inline-tag-container">
        <div className="inline-tag-item">
          <Checkbox
            id={`tag-${tag.id}`}
            checked={isSelected}
            value={isSelected ? "true" : "false"}
            isDisabled={disabled || tag.disabled}
            onChange={() => handleTagChange(tag)}
          />
          <span
            className="tag-icon"
            style={{
              backgroundColor: `#${tag.color}`,
              opacity: level > 0 ? 0.7 : 1,
            }}
          >
            <i className="material-icons">local_offer</i>
          </span>
          <div >
            <span className="tag-label">{tag.label}</span>
            {childTags.length > 0 && (
              <span className="tag-children-label">{childTags.map((childTag) => `/${childTag.label}`  )}</span>
            )}
          </div>
        </div>
      </div>
    );
  };

  // Obtener solo los tags padre (nivel 0)
  const parentTags = tags.filter(
    (tag) =>
      tag.level === 0 || (tag.level === undefined && tag.parentId === null)
  );

  return (
    <div className="inline-tags-wrapper">
      {parentTags.map((tag) => renderTag(tag, 0))}
    </div>
  );
};

export default Inline;
