import React, { memo, ReactElement, useEffect, useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { ChevronUpIcon } from "@/assets/svgs";

const ComplexSelect = ({
  onSelect,
  showBorder = true,
  options = [],
  display = "display",
  value,
  selector = null,
  disabled = false,
  placeholder = "Select",
  maxHeight = "18.75rem",
}) => {
  const containerRef = useRef(null);
  const divRef = useRef(null);
  const spanRef = useRef(null);
  // const [selectedOption, setSelectedOption] = useState(null)
  const uniqueId = uuidv4({ namespace: "ComplexSelect" });
  const divUniqueId = uuidv4({ namespace: "ComplexSelect" });
  const spanUniqueId = uuidv4({ namespace: "ComplexSelect" });
  const [showLists, setShowLists] = useState(false);
  const [selectedOption, setSelectedOption] = useState(null);

  const handleSelect = (option) => {
    // setSelectedOption(option[display])
    if (!onSelect) {
      return;
    }
    setSelectedOption(() => option);

    setShowLists((prev) => !prev);
  };

  useEffect(() => {
    if (!selectedOption) {
      return;
    }
    if (selector) {
      onSelect(selectedOption[selector]);
    } else {
      onSelect(selectedOption);
    }
  }, [selectedOption && selectedOption[display]]);

  useEffect(() => {
    if (selector) {
      if (options?.length) {
        const position = options.findIndex(
          (option) => option[selector] === value
        );
        const option = options[position];

        setSelectedOption(() => option);
      }
    } else {
      setSelectedOption(() => value);
    }
  }, [options?.length]);

  useEffect(() => {
    if (selector) {
      if (options?.length) {
        const position = options.findIndex(
          (option) => option[selector] === value
        );
        if (position === -1) {
          return setSelectedOption(null);
        }

        const option = options[position];
        setSelectedOption(() => option);
      }
    } else {
      setSelectedOption(() => value);
    }
  }, [value]);

  useEffect(() => {
    window.addEventListener("click", (e) => {
      if (
        !containerRef.current ||
        !containerRef.current.id ||
        !(containerRef.current.id === e.target.id)
      ) {
        if (
          !divRef.current ||
          !divRef.current.id ||
          !(divRef.current.id === e.target.id)
        ) {
          if (
            !spanRef.current ||
            !spanRef.current.id ||
            !(spanRef.current.id === e.target.id)
          ) {
            setShowLists((prev) => {
              if (prev) {
                return !prev;
              }
              return prev;
            });
          }
        }
      }
    });

    return window.removeEventListener("click", (e) => {
      if (
        !containerRef.current ||
        !containerRef.current.id ||
        !(containerRef.current.id === e.target.id)
      ) {
        if (
          !divRef.current ||
          !divRef.current.id ||
          !(divRef.current.id === e.target.id)
        ) {
          if (
            !spanRef.current ||
            !spanRef.current.id ||
            !(spanRef.current.id === e.target.id)
          ) {
            setShowLists((prev) => {
              if (prev) {
                return !prev;
              }
              return prev;
            });
          }
        }
      }
    });
  }, []);

  return (
    <div
      className={`text-text-secondary relative w-full min-w-full max-w-full text-base  ${
        showBorder
          ? " rounded border-b border-b-[solid] border-b-primaryBlue"
          : ""
      }`}
    >
      {selectedOption && placeholder && (
        <label className=" text-sm font-bold text-gray-700">
          {placeholder}
        </label>
      )}
      <button
        disabled={disabled}
        id={uniqueId}
        ref={(ref) => {
          containerRef.current = ref;
        }}
        className={`showListButton flex max-h-[2rem] min-h-[2rem] w-full min-w-full max-w-full items-center justify-between gap-6 border-none leading-6`}
        onClick={() => setShowLists((prev) => !prev)}
        title={selectedOption && selectedOption[display]}
      >
        <div
          id={divUniqueId}
          ref={(ref) => {
            divRef.current = ref;
          }}
          className="truncate"
        >
          {selectedOption && selectedOption[display]}
          {/* {selectedOption && selectedOption[display] && (selectedOption[display]).length > 30 ? (selectedOption[display]).substring(0, 30) + "..." : selectedOption && (selectedOption[display]) && selectedOption[display]} */}
          <span
            id={spanUniqueId}
            ref={(ref) => {
              spanRef.current = ref;
            }}
            className={`text-text-disabled text-[.875rem] font-normal leading-[1.5rem] tracking-[.0313rem] text-[#636363]`}
          >
            {!selectedOption && placeholder}
          </span>
        </div>
        <span>
          <ChevronUpIcon className={`h-[.5919rem] w-[.9375rem] rotate-180`} />
        </span>
      </button>
      {showLists && (
        <div
          style={{ zIndex: 999999, maxHeight }}
          className={`absolute z-20 max-h-56 w-full overflow-auto rounded-b-md bg-white py-1 text-sm shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm`}
        >
          {options.length ? (
            options?.map((option, index) => {
              return (
                <div
                  key={index}
                  title={option && option[display]}
                  className={`h-[2.8rem] min-h-[2.8rem] cursor-pointer truncate px-3 py-2 text-sm font-normal text-gray-900 hover:bg-primary-light ${
                    selectedOption &&
                    option[display] === selectedOption[display]
                      ? "bg-primary-light"
                      : ""
                  } `}
                  onClick={() => handleSelect(option)}
                >
                  {option[display]}
                </div>
              );
            })
          ) : (
            <div
              className={`h-[2.8rem] min-h-[2.8rem] cursor-pointer truncate px-3 py-2 hover:bg-primary-light `}
            ></div>
          )}
        </div>
      )}
    </div>
  );
};

export default memo(ComplexSelect);
