import React, { useState, CSSProperties, useEffect, useRef } from 'react';
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}
 * toggleOnHover: boolean
 * valueSelect: {name:  string | number, [key: string]: string | number}
 * }} props - properties of the dropdown component
 */
// dropdownData - Array of objects with property values of name and value
// header - this specifies the label of the dropdown
// searchable - property that includes search functionality or not
// className - if this one isn't self-explanatory, leave React.
// onSelect - this is a function that runs onselect and returns a selected object value.
// inputPlaceHolder - this is a placeholder for the dropdown

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();

  // dropdown menu ref
  const dropdownRef = 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);
  };
  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={
              (searchParam && searchParam) ||
              (props?.valueSelect?.name && props?.valueSelect?.name) ||
              (selected?.name && selected?.name)
            }
            onChange={(e) => {
              setSearchParam(e.target.value);
            }}
            // onClick={() => setDropdown(true)}
            onFocus={handleDropdownToggle}
          />
        ) : (
          // <p onClick={() => setDropdown(!dropdown)}>
          <p onClick={handleDropdownToggle}>
            {props?.valueSelect?.name ||
              selected?.name ||
              props?.inputPlaceHolder}
          </p>
        )}
        {/* <DownIcon onClick={() => setDropdown(!dropdown)} /> */}
        <DownIcon onClick={handleDropdownToggle} />
        {searchParam && dropdown && (
          <DropDownContent>
            {props?.dropdownData?.map((dropdownItem, idx) => {
              if (
                props?.dropdownData[idx]?.name
                  ?.toLowerCase()
                  .includes(searchParam?.toLowerCase())
              )
                return (
                  <DropDownItem
                    key={idx}
                    onClick={() => {
                      setSelected(dropdownItem);
                      setDropdown();
                      setSearchParam();
                    }}
                  >
                    <span>{dropdownItem?.name}</span>
                    {(props?.valueSelect || selected) === dropdownItem && (
                      <Tick />
                    )}
                  </DropDownItem>
                );
            })}
          </DropDownContent>
        )}
        {!searchParam && dropdown && (
          <DropDownContent>
            {props?.dropdownData?.map((dropdownItem, idx) => {
              return (
                <DropDownItem
                  key={idx}
                  onClick={() => {
                    setSelected(dropdownItem);
                    setDropdown();
                  }}
                >
                  <span>{dropdownItem?.name}</span>
                  {(props?.valueSelect || selected) === dropdownItem && (
                    <Tick />
                  )}
                </DropDownItem>
              );
            })}
          </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>
  );
};
