import React, { useEffect, useRef, useState } from "react";
import { components } from "react-select";
import { Tooltip } from "../Tooltip";
import MUICheckbox from "@mui/material/Checkbox";
import { Checkbox } from "../Checkbox";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";

// Add helper function to get selected children count
const getSelectedChildrenCount = (parent, selectedOptions) => {
  if (!parent.children || !selectedOptions || !Array.isArray(selectedOptions))
    return 0;
  const selectedParent = selectedOptions.find(
    (sel) => sel.value === parent.value
  );
  return selectedParent ? selectedParent.children.length : 0;
};

// Helper to check if all children are selected
const areAllChildrenSelected = (option, selectedOptions) => {
  if (!option.children || !selectedOptions || !Array.isArray(selectedOptions))
    return false;
  const selectedParent = selectedOptions.find(
    (sel) => sel.value === option.value
  );
  return (
    selectedParent && selectedParent.children.length === option.children.length
  );
};

// Renders a label and only wraps it with Tooltip if it overflows its container
const OverflowTooltipLabel = ({ text, popperProps }) => {
  const labelRef = useRef(null);
  const [isOverflowed, setIsOverflowed] = useState(false);

  const checkOverflow = () => {
    const el = labelRef.current;
    if (!el) return;
    setIsOverflowed(el.scrollWidth > el.clientWidth);
  };

  useEffect(() => {
    checkOverflow();
  }, [text]);

  useEffect(() => {
    window.addEventListener("resize", checkOverflow);
    return () => window.removeEventListener("resize", checkOverflow);
  }, []);

  const content = <span ref={labelRef}>{text}</span>;

  return isOverflowed ? (
    <Tooltip
      title={text}
      orientation="right"
      variant="tertiary"
      className="select-tooltip"
      PopperProps={popperProps}
    >
      {content}
    </Tooltip>
  ) : (
    content
  );
};

export const Option = ({
  isLoadingOption,
  isDisabled,
  customOptionProps,
  ...props
}) => {
  const {
    data,
    isSelected,
    isMulti,
    isWithIcon,
    selectedOptions,
    initialOptions,
  } = props;

  const resolveComponent = (type) => {
    if (isMulti) {
      const hasChildren = data.children && data.children.length > 0;
      const selectedCount = hasChildren
        ? getSelectedChildrenCount(data, selectedOptions)
        : 0;
      const allChildrenSelected = hasChildren
        ? areAllChildrenSelected(data, selectedOptions)
        : false;

      const popperProps = {
        modifiers: [
          {
            name: "offset",
            options: {
              offset: [0, 18],
            },
          },
        ],
      };

      return (
        <Checkbox
          withoutFormLabel={true}
          label={
            <div className="select-label-with-icon">
              {data.children ? (
                <>
                  <OverflowTooltipLabel
                    text={data.label}
                    popperProps={popperProps}
                  />
                  {hasChildren && selectedCount > 0 && (
                    <span className="selected-children-count">
                      ({selectedCount})
                    </span>
                  )}
                </>
              ) : (
                <OverflowTooltipLabel
                  text={data.label}
                  popperProps={popperProps}
                />
              )}
            </div>
          }
          checked={isSelected}
          variant={
            hasChildren && selectedCount > 0 && !allChildrenSelected
              ? "dashed"
              : "default"
          }
          onChange={() => null}
          disabled={isLoadingOption || isDisabled}
        />
      );
    } else {
      // Handle non-multi case
      const isParentSelected =
        data.children &&
        data.children.some(
          (child) => selectedOptions && selectedOptions.value === child.value
        );
      const isOptionSelected = isSelected || isParentSelected;

      const popperProps = {
        modifiers: [
          {
            name: "offset",
            options: {
              offset: [0, 15],
            },
          },
        ],
      };

      return (
        <div
          className={`select-label-with-icon ${
            isOptionSelected ? "selected" : ""
          } ${isDisabled ? "disabled" : ""}`}
        >
          {data.children ? (
            <>
              <OverflowTooltipLabel
                text={data?.label}
                popperProps={popperProps}
              />
            </>
          ) : (
            <OverflowTooltipLabel text={data.label} popperProps={popperProps} />
          )}
        </div>
      );
    }
  };

  const optionIndex = props?.selectProps?.options?.findIndex?.(
    (o) => o.value === data.value
  ) ?? -1;
  const listboxId = props?.selectProps?.listboxId || "ia-select-listbox";
  const highlightedIndex = props?.selectProps?.highlightedIndex ?? -1;
  const isHighlighted = optionIndex >= 0 && optionIndex === highlightedIndex;
  const isKeyboardNav = props?.selectProps?.isKeyboardNav;
  const hasChildren = data.children && data.children.length > 0;

  const renderOption = (type) => (
    <components.Option {...props}>
      <div
        role="option"
        id={`${listboxId}-option-${optionIndex}`}
        aria-selected={!!isSelected}
        aria-expanded={hasChildren ? !!props?.selectProps?.submenuParent?.value === data.value : undefined}
        className={`select-option-content ${
          props.isSelected ||
          (data.children &&
            data.children.some(
              (child) =>
                selectedOptions && selectedOptions.value === child.value
            ))
            ? "selected"
            : ""
        }`}
        {...customOptionProps}
        onMouseEnter={(e) => {
          if (props?.selectProps?.setHighlightedIndex) {
            props.selectProps.setHighlightedIndex(optionIndex);
          }
          if (props?.selectProps?.setIsKeyboardNav) {
            props.selectProps.setIsKeyboardNav(false);
          }
          customOptionProps?.onMouseEnter?.(e);
        }}
      >
        {resolveComponent(type)}
        {hasChildren && (
          <ChevronRightIcon className="select-submenu-chevron" />
        )}
      </div>
    </components.Option>
  );

  if (props.selectProps.isMulti && props.selectProps.isWithIcon) {
    return renderOption("isMulti-with-icon");
  }

  if (props.selectProps.isMulti && !props.selectProps.isWithIcon) {
    return renderOption("isMulti");
  }

  if (!props.selectProps.isMulti && props.selectProps.isWithIcon) {
    return renderOption("with-icon");
  }

  return renderOption(props.isMulti ? "isMulti" : "default");
};
