import React, { useState, useRef, useEffect } from "react";
import { Tooltip } from "../Tooltip";
import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";

export default function PanelSidebar({ filters, active, setActive }) {
  return (
    <div className="impact_drawer_filter_container_left_panel">
      <div className="impact_drawer_filter_left_filters_tabs">
        {filters.map((item, index) => {
          return (
            <SidebarItems
              key={index}
              item={item}
              active={active}
              setActive={setActive}
            />
          );
        })}
      </div>
    </div>
  );
}

const SidebarItems = ({ item, active, setActive }) => {
  const textRef = useRef(null);
  const [showTooltip, setShowTooltip] = useState(false);

  useEffect(() => {
    const checkEllipsis = () => {
      if (textRef.current) {
        const isEllipsis =
          textRef.current.scrollWidth > textRef.current.clientWidth;
        setShowTooltip(isEllipsis);
      }
    };

    checkEllipsis();
    // Recheck on window resize
    window.addEventListener("resize", checkEllipsis);
    return () => window.removeEventListener("resize", checkEllipsis);
  }, [item.title]);

  if (item.type === "separator") {
    return <div className="impact-drawer-filter-separator" />;
  }

  const tabContent = (
    <div
      className={`impact_drawer_filter_tab ${
        active == item.value ? "filter_tab_active" : ""
      } ${item?.disabled ? "filter_tab_disabled" : ""}`}
      role="button"
      onClick={() => {
        if (!item?.disabled) setActive(item.value);
      }}
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          if (!item?.disabled) setActive(item.value);
        }
      }}
    >
      <div className="impact_drawer_filter_tab_content">
        <div className="impact_drawer_filter_tab_icon">{item.icon}</div>
        <div className="impact_drawer_filter_tab_label">
          <span ref={textRef}>{item.title}</span>
          {item.required && (
            <span className="impact_drawer_filter_tab_label-required">*</span>
          )}
        </div>
      </div>
      {item?.error ? (
        <ErrorOutlineIcon fontSize="small" color="error" />
      ) : (
        typeof item.numberOfFilter === "number" && (
          <div className="impact_drawer_filter_tab_badges">
            {item.numberOfFilter}
          </div>
        )
      )}
    </div>
  );

  return showTooltip ? (
    <Tooltip title={item.title} orientation="left" variant="tertiary">
      {tabContent}
    </Tooltip>
  ) : (
    tabContent
  );
};
