import React, { useState, useEffect, useMemo, useCallback } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import FormElement from 'components/structure/FormElement';
import FormItemLabel from 'components/items/FormItemLabel';
import { getList } from 'store/utils/helper';
import cloneDeep from 'lodash/cloneDeep';
import styleIdentifiers from './Toggle.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface ToggleProps {}

const Toggle = (props: ToggleProps) => {
  const {
    disabled,
    items,
    input,
    onChange,
    label,
    united,
    meta: { touched },
    auto,
    className,
    error,
    // styling
    containerClassName,
    activeClassName,
    buttonClassName,
    imageClassName,
    labelClassName,
  } = props;

  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const content = useSelector((state: StoreState) => state.content.raw);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const [list, setList] = useState();

  useEffect(() => {
    let listItems;

    if (typeof items === 'string' && content) {
      listItems = getList(content, items);
    } else {
      listItems = cloneDeep(items);
    }
    if (!Array.isArray(listItems) && typeof listItems === 'object') {
      listItems = Object.values(listItems);
    }

    if (!listItems) return;

    listItems.map(item => {
      if (!item) return null;
      item.id = `${input.name}-${item.value || ''}`;
      return item;
    });

    setList(listItems);
  }, [items, content]);

  const handleChange = useCallback(
    item => {
      if (disabled) return;
      const value = (item && (item.value || item.label)) || item;

      if (input.onChange) input.onChange(value);

      if (onChange) onChange(value);
    },
    [onChange, disabled],
  );

  const fromContent = useMemo(() => typeof items === 'string', [items]);

  return (
    <div
      className={styles('toggle', united && 'united', error && 'error', touched && 'touched', auto && 'relative', className)}
      onFocus={input.onFocus}
      onBlur={input.onBlur}
      tabIndex="0"
    >
      {list && (
        <FormElement {...props}>
          {label && <FormItemLabel {...props} />}
          <div className={styles('value-container', containerClassName)} suppressHydrationWarning>
            {list.map((item, key) => {
              if (!item) return false;
              // toString allows to use boolean
              const isActive = input.value?.toString() === item.value?.toString();
              return (
                <div
                  key={key}
                  onClick={() => handleChange(item)}
                  className={styles('button', buttonClassName, disabled && 'disabled', isActive && 'active', isActive && activeClassName)}
                >
                  {isActive && item.imgActive && <img src={item.imgActive} className={styles(imageClassName)} alt="" />}
                  {!isActive && item.img && <img src={item.img} className={styles(imageClassName)} alt="" />}
                  {!item.img && (
                    <>
                      {fromContent && <TextItem item={item} className={styles('label', labelClassName)} />}
                      {!fromContent && <TextItem path={item.label || item.value} className={styles('label', labelClassName)} />}
                    </>
                  )}
                  {item.img && item.label && <TextItem path={item.label} className={styles('label', labelClassName)} />}
                </div>
              );
            })}
          </div>
        </FormElement>
      )}
    </div>
  );
};

export default Toggle;
