import * as React from 'react';
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 './customRadio.scss';

const styles = classNames.bind(styleIdentifiers);

export interface CustomRadioProps {
  label: string;
  nameItem: string;
  valueItem: string;
  onChange: Function;
  input: {};
  meta: {};
  items: object[];
  classNameRadioContainer?: string;
  classNameSingleRadio?: string;
  customClassName?: string;
}

interface CustomRadioState {}

export default class CustomRadio extends React.Component<CustomRadioProps, CustomRadioState> {
  state = {
    list: null,
  };

  componentDidMount() {
    this.treatItems();
  }

  componentDidUpdate(prevProps) {
    const { items } = this.props;

    if (items && prevProps.items !== items) {
      this.treatItems();
    }
  }

  handleChange = (event: SyntheticInputEvent<HTMLInputElement>) => {
    const { input, onChange } = this.props;

    // when puttin type="radio" to the Field => value is not updated
    const value = event.target.value;

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

    if (onChange) onChange(value);
  };

  treatItems = () => {
    const { items, content, input } = this.props;

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

    this.setState({
      list: listItems,
    });
  };

  // to update background color when checked just overwrite css variable $color_radio_checked
  render() {
    const {
      disabled,
      label,
      items,
      input,
      united,
      classNameRadioContainer,
      radioContainerClassName,
      classNameSingleRadio,
      singleRadioClassName,
      singleRadioActiveClassName,
      imageClassName,
      radioLabelClassName,
      customClassName,
      auto,
      meta: { touched, error },
    } = this.props;

    const { list } = this.state;

    const fromContent = typeof items === 'string';

    return (
      <div
        className={styles('CustomRadio', united && 'united', error && 'error', touched && 'touched', auto && 'relative', customClassName)}
        onFocus={input.onFocus}
        onBlur={input.onBlur}
        tabIndex="0"
      >
        {list && (
          <FormElement {...this.props}>
            {label && <FormItemLabel {...this.props} />}
            <div className={styles('value-container', classNameRadioContainer, radioContainerClassName)} suppressHydrationWarning>
              {list.map((item, key) => {
                if (!item) return false;
                // toString allows to use boolean
                const isActive = input.value?.toString() === item.value?.toString();
                return (
                  <label htmlFor={item.id} key={key} className={styles(isActive && 'active')}>
                    <input
                      disabled={disabled}
                      aria-label={input && input.name}
                      type="radio"
                      name={input.name}
                      value={item.value}
                      id={item.id}
                      onChange={this.handleChange}
                      checked={isActive}
                      suppressHydrationWarning
                    />
                    <div
                      className={styles(
                        'single',
                        classNameSingleRadio,
                        singleRadioClassName,
                        isActive && 'active',
                        isActive && singleRadioActiveClassName,
                      )}
                    >
                      {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', radioLabelClassName)} />}
                          {!fromContent && <TextItem path={item.label || item.value} className={styles('label', radioLabelClassName)} />}
                        </>
                      )}
                      {item.img && item.label && <TextItem path={item.label} className={styles('label', radioLabelClassName)} />}
                    </div>
                  </label>
                );
              })}
            </div>
          </FormElement>
        )}
      </div>
    );
  }
}
