import React, { FC, Fragment, useState, useEffect, useRef } from 'react';
import { AreaMenu, Area, Menu, Button, Loading, IconButton, Label } from '../';
import { useLocale } from '../../hooks/useLocale';

//containers
import ExtraOptionsContainer from './Containers/ExtraOptionsContainer'
import ValuesContainer from './Containers/ValuesContainer'
import { SelectMenuProps } from './SelectMenu.types';
import "./index.scss"

export const SelectMenu: FC<SelectMenuProps> = ({
  options,
  value,
  valueField,
  label,
  isLoading,
  isMultiple,
  isDisabled,
  placeholder,
  textField,
  extraOptions,
  extraOptionstextField,
  extraOptionsvalueField,
  buttonLabel,
  helpText,
  id,
  onChange,
}) => {
  const [isValid, setIsValid] = useState(true)
  const [errorMessage, setErrorMessage] = useState(null)
  const [selectedOptions, setSelectedOptions] = useState({})
  const [filterText, setFilterText] = useState("")
  const [isCollapse, setIsCollapse] = useState(true)
  const [dataShown, setDataShown] = useState(10)

  const areaMenuRef = useRef<any>()
  const firstRender = useRef(true);
  const prevValue = useRef<any>();
  const prevCheckAll = useRef<any>(false)
  const labels = {
    placeholder: useLocale(placeholder),
    label: useLocale(label),
    helpText: useLocale(helpText),
    errorMessage: useLocale(errorMessage || ''),
    showAllText: useLocale("show_all"),
  }
  
  const [isCheckAll, setIsCheckAll] = useState(false)

  useEffect(() => {
      if (firstRender.current) {
        firstRender.current = false;
      } else {
        // do componentDidUpdate logic
        if( JSON.stringify(prevValue.current) != JSON.stringify(value) ){
          let newSelected = {}
          value.map( (elem:any) => {
            newSelected = { ...newSelected, [ elem[valueField] ]:elem.options } 
          })
    
          setSelectedOptions({ ...newSelected })
          prevValue.current = value;
        }
      }
  }, [value]);

  return (
    <div className="gtc-rc-select-menu-container">
      {label && 
          <Label>{labels['label']}</Label>    
      }
      {isLoading ? 
        <div className="gtc-rc-input-loading">
          <Loading />
        </div>
        : 
        <Fragment>
          <AreaMenu 
              id={id || "SelectMenu"} 
              menuPlacement={"bottom"}
              isDisabled={isDisabled}
              clickAway={false}
              ref={areaMenuRef}
          > 
            <Area>
              <div className="gtc-rc-select-menu-container-input">
                <input
                  className="gtc-rc-select-menu-input"                    
                  type="text"
                  multiple={isMultiple}
                  onChange={(e) => {
                      setFilterText(e.target.value)
                  }}
                  //required={this.props.required}
                  disabled={isDisabled}
                  placeholder={labels['placeholder']}
                />
                <div className="gtc-rc-select-menu-icon-button">
                  <IconButton className="gtc-rc-datepicker_icon" icon={"keyboard_arrow_down"} size="small" onClick={() => {}} />
                </div>
              </div>
            </Area>

            <Menu>
                <ExtraOptionsContainer
                  filterText={filterText}
                  options={options}
                  buttonLabel={buttonLabel}
                  textField="title"
                  valueField="contactId"
                  extraOptions={extraOptions}
                  selectedOptions={selectedOptions}
                  onChange={onChange}
                  setSelectedOptions={setSelectedOptions}
                  extraOptionstextField="name"
                  extraOptionsvalueField="id"
                  onCloseMenu={() => areaMenuRef.current?.close()}
                  setIsCheckAll={(value: boolean) => setIsCheckAll(value)}
                  isCheckAll={isCheckAll}
                  
                  //extraOptionsRequiredMessage={messages["scheduleVehicleService_alert_error_message"]}
                />
            </Menu>
          </AreaMenu>

          {/* DISPLAY SELECTED DATA */}      
          {value && value.length > 0 && 
            <ValuesContainer 
              value={value} 
              dataShow={dataShown}
              textField={textField} 
              extraOptionstextField={extraOptionstextField}
              onDelete={(val:any) => {
                  let currentValue = [...value];
                  currentValue = currentValue.filter(
                      (cval) => cval[valueField] != val[valueField],
                  );

                  if (onChange) {
                      onChange(currentValue);
                  }
              }}
            />
          }

          {value.length > 10 &&
            <Button
              className='gtc-rc-buttonCollapsed'
              variant="secondary"
              onClick={ () =>{
                if(isCollapse){
                  setDataShown(value.length)//dataShown + 10)
                  setIsCollapse(false)
                }else{
                  setDataShown(10)
                  setIsCollapse(true)
                }

              }}
            >
              { isCollapse ? `${labels['showAllText']} (${value.length || 0 })` : "collapse_to_ten"  }
            </Button>
          }

          {helpText && (
            <small id={`${id}-help`} className="text-muted">
              {labels['helpText']}
            </small>
          )}

          {!isValid && errorMessage && (
            <small className="text-danger" style={{ paddingTop: 5 }}>
              {labels['errorMessage']}
            </small>
          )}
        </Fragment>
      }
    </div>
  );
}