import React, { InputHTMLAttributes, useImperativeHandle, useRef, useState } from 'react';
import { faAngleDown } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { FormStyle } from '../styles';
import { ISelectProps } from './Select.interface';
import { SelectCore } from './SelectCore';
import * as S from './Select.style';

export const SelectPure = React.forwardRef<InputHTMLAttributes<any>, ISelectProps>(function SelectPure(
   { value, onChange, options, title, defaultValue, error, color, rightSelect, children, as, ...rest },
   inputRef: any,
) {
   const ref = useRef<any>();
   useImperativeHandle(inputRef, () => ref.current, []);

   const [focus, setFocus] = useState(false);

   return (
      <FormStyle>
         <S.Container color={color}>
            {title && <div className={`input-title ${focus && 'focus'}`}>{title}</div>}

            <label className="select-box">
               <select
                  {...rest}
                  defaultValue={defaultValue ? JSON.stringify(defaultValue) : undefined}
                  ref={ref}
                  value={value ? JSON.stringify(value) : undefined}
                  onChange={(event) => {
                     if (onChange) {
                        onChange(JSON.parse(event.target.value));
                     }
                  }}
                  className={error && 'has-error'}
                  onFocus={(ev) => {
                     if (rest.onFocus) rest.onFocus(ev);
                     setFocus(true);
                  }}
                  onBlur={(ev) => {
                     if (rest.onBlur) rest.onBlur(ev);
                     setFocus(false);
                  }}
               >
                  {!options && children}
                  {options &&
                     options.map((i) => (
                        <option value={JSON.stringify(i.value)} key={JSON.stringify(i.value)} disabled={i.disabled}>
                           {i.name}
                        </option>
                     ))}
               </select>

               <div className="select-icon">
                  <FontAwesomeIcon icon={faAngleDown} />
               </div>
            </label>

            {error && (
               <div data-cy={`input-error.${rest['data-cy'] ?? ''}`} className="error-input" data-testid="input-error">
                  {error}
               </div>
            )}
         </S.Container>
      </FormStyle>
   );
});

export const Select = React.forwardRef<InputHTMLAttributes<any>, ISelectProps>(function Checkbox(props, inputRef: any) {
   const ref = useRef();
   useImperativeHandle(inputRef, () => ref.current, []);

   return <SelectCore {...props} ref={ref} as={SelectPure} />;
});
