import React, { useState, CSSProperties, useEffect, useRef } from 'react';
import LoaderCustom from '../customLoader';
import {
  ControlInput,
  DropDownContainer,
  DropDownContent,
  DropDownControls,
  DropDownHeader,
  DropDownItem,
} from './styles';

/**
 * @param {{
 * dropdownData: Array,
 * header: string,
 * searchable: boolean,
 * className: string,
 * onSelect: Function,
 * inputPlaceHolder: string,
 * default: {name:  string | number, [key: string]: string | number}
 * valueSelect: {name:  string | number, [key: string]: string | number}
 * toggleOnHover: boolean
 * loadMoreData: Function
 * isLoading: boolean,
 * showLoader: boolean,
 * }} props - properties of the dropdown component
 */

const DropDownComponent = (props) => {
  // select state that dictates the current value.
  const [selected, setSelected] = useState(props.default);

  // dropdown state that dictates if dropdown is dropped or not.
  const [dropdown, setDropdown] = useState();

  //search params
  const [searchParam, setSearchParam] = useState();
  const { isLoading, showLoader = false } = props;

  // dropdown menu ref
  const dropdownRef = useRef(null);
  const dropdownListRef = useRef(null);

  // click outside closes the dropdown menu
  const handleClickOutside = (event) => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
      setDropdown(false);
    }
  };
  useEffect(() => {
    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);

  // useEffect to return a function value onChange
  useEffect(() => {
    props?.onSelect && props?.onSelect(selected);
  }, [selected]);
  const handleDropdownToggle = () => {
    setDropdown((prevDropdown) => !prevDropdown);
  };
  const handleScroll = (e) => {
    const { scrollTop, scrollHeight, clientHeight } = e.target;
    const isBottom = scrollTop + clientHeight >= scrollHeight - 10; // Adjusted threshold to 10px
    if (isBottom) {
      //console.log("Near bottom, loading more data.");
      props.loadMoreData();
    }
  };
  useEffect(() => {
    const listElement = dropdownListRef.current;
    if (listElement) {
      listElement.addEventListener('scroll', handleScroll);
      return () => listElement.removeEventListener('scroll', handleScroll);
    }
  }, [props.dropdownData]);
  return (
    <DropDownContainer
      className={props?.className}
      ref={dropdownRef}
      onMouseEnter={() => props.toggleOnHover && setDropdown(true)}
      onMouseLeave={() => props.toggleOnHover && setDropdown(false)}
    >
      <DropDownHeader>{props?.header}</DropDownHeader>
      <DropDownControls>
        {props?.searchable ? (
          <ControlInput
            placeholder={props?.inputPlaceHolder || 'Select Dropdown'}
            type="text"
            value={
              props?.findText
                ? props?.findText(props?.valueSelect?.name || selected?.name)
                : props?.valueSelect?.name || selected?.name
            }
            onChange={(e) => {
              setSearchParam(e.target.value);
            }}
            // onClick={() => setDropdown(true)}
            onClick={handleDropdownToggle}
          />
        ) : (
          // <p onClick={() => setDropdown(!dropdown)}>
          <p onClick={handleDropdownToggle}>
            {props?.findText
              ? props?.findText(
                  props?.valueSelect?.name ||
                    selected?.name ||
                    props?.inputPlaceHolder,
                )
              : props?.valueSelect?.name ||
                selected?.name ||
                props?.inputPlaceHolder}
          </p>
        )}
        {/* <DownIcon onClick={() => setDropdown(!dropdown)} /> */}
        <DownIcon onClick={handleDropdownToggle} />
        {searchParam && dropdown && (
          <DropDownContent onScroll={handleScroll} ref={dropdownListRef}>
            {props?.dropdownData?.map((dropdownItem, idx) => {
              if (
                props?.dropdownData[idx]?.name
                  ?.toLowerCase()
                  .includes(searchParam?.toLowerCase())
              )
                return (
                  <DropDownItem
                    key={idx}
                    onClick={() => {
                      setSelected(dropdownItem);
                      setDropdown();
                    }}
                  >
                    <span>
                      {props?.findText
                        ? props?.findText(dropdownItem?.name)
                        : dropdownItem?.name}
                    </span>
                    {(props?.valueSelect || selected) === dropdownItem && (
                      <Tick />
                    )}
                  </DropDownItem>
                );
            })}
          </DropDownContent>
        )}
        {!searchParam && dropdown && (
          <DropDownContent onScroll={handleScroll} ref={dropdownListRef}>
            {props?.dropdownData?.map((dropdownItem, idx) => {
              return (
                <DropDownItem
                  key={idx}
                  onClick={() => {
                    setSelected(dropdownItem);
                    setDropdown();
                  }}
                >
                  <span>
                    {props?.findText
                      ? props?.findText(dropdownItem?.name)
                      : dropdownItem?.name}
                  </span>
                  {(props?.valueSelect || selected) === dropdownItem && (
                    <Tick />
                  )}
                </DropDownItem>
              );
            })}
            <div className={showLoader ? 'loader' : ''}>
              {isLoading && showLoader && props?.dropdownData?.length > 0 && (
                <LoaderCustom />
              )}
            </div>
          </DropDownContent>
        )}
      </DropDownControls>
    </DropDownContainer>
  );
};
export default DropDownComponent;
export const DownIcon = ({ width, height, fill, onClick }) => {
  return (
    <svg
      width={width || '18'}
      height={height || '9'}
      viewBox="0 0 14 8"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      onClick={onClick}
    >
      <path
        d="M1 1L7 7L13 1"
        stroke={fill || '#7C8080'}
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
};
export const Tick = ({ size, stroke }) => {
  return (
    <svg
      width={size || '16'}
      height={size || '16'}
      viewBox="0 0 16 16"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M12.3828 4.23828L5.82031 11.7383L3.00781 8.92578"
        stroke={stroke || 'white'}
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
};
