import * as React from 'react';
import classNames from 'classnames/bind';
// import TextItem from 'components/items/TextItem';
import { Field as FinalField } from 'react-final-form';
import { Field as ReduxField } from 'redux-form';

import Input from 'components/formItems/Input';
import Textarea from 'components/formItems/Textarea';
import Wysiwyg from 'components/formItems/Wysiwyg';
import CkEditorField from 'components/formItems/CkEditorField';
import CodeEditorInput from 'components/formItems/CodeEditorInput';

import { config } from 'config/general';
import { required } from 'store/utils/validation';
import FormItemLabel from 'components/items/FormItemLabel';
import _ from 'lodash';
import { FaLock, FaUnlock } from 'react-icons/fa';
import ModuleButton from 'components/items/ModuleButton';
import styleIdentifiers from './inputLanguage.scss';

const styles = classNames.bind(styleIdentifiers);

export interface InputLanguageProps {
  item?: Record<string, any>;
  name: string;
  type?: string;
  inputProps?: Record<string, any>;
  noMargin?: boolean;
}

interface InputLanguageState {}

export default class InputLanguage extends React.Component<InputLanguageProps, InputLanguageState> {
  constructor(props) {
    super(props);

    const { lg } = this.props;

    const firstDiff = _.find(config.languages, it => {
      const l = it.short || it.value;
      return l !== lg;
    });

    this.state = {
      displayAllLanguages: false,
      mainLanguage: lg,
      currentLg: firstDiff ? firstDiff.short || firstDiff.value : lg,
    };
  }

  getComponent = () => {
    const { type } = this.props;
    if (type === 'textarea') return Textarea;
    if (type === 'wysiwyg') return CkEditorField;
    if (type === 'code') return CodeEditorInput;

    return Input;
  };

  checkMatch = lgCode => {
    const { matches, matchClassName } = this.props;

    if (!matches) return '';

    if (matches.indexOf(lgCode) >= 0) {
      return matchClassName;
    }

    return '';
  };

  switchLanguage = target => {
    const { currentLg, mainLanguage } = this.state;

    // switch main language
    if (currentLg === target) {
      this.setState({
        mainLanguage: target,
        currentLg: mainLanguage,
      });
      return;
    }
    this.setState({
      currentLg: target,
    });
  };

  toggleDisplayLanguages = () => {
    const { displayAllLanguages } = this.state;
    this.setState({
      displayAllLanguages: !displayAllLanguages,
    });
  };

  render() {
    const {
      redux,
      item,
      label,
      name,
      type,
      inputProps,
      noMargin,
      lock,
      locked,
      activeLgs,
      ...rest
    } = this.props;

    const { currentLg, displayAllLanguages, mainLanguage } = this.state;

    const Field = redux ? ReduxField : FinalField;

    const numLg = config.languages.length;

    let languages =
      numLg <= config.maxNumLanguagesDisplayed
        ? config.languages
        : [_.find(config.languages, lg => lg.short === mainLanguage || lg.value === mainLanguage)];
    if (displayAllLanguages) languages = config.languages;

    if (activeLgs) languages = languages.filter(e => activeLgs?.includes(e.value || e.short));

    return (
      <div className={styles('InputLanguage', noMargin && 'no-margin')}>
        {label && <FormItemLabel {...inputProps} {...this.props} label={label} />}
        {languages.map((lang, index) => {
          const lgCode = lang.value || lang.short;
          return (
            <div
              key={lgCode || index}
              className={styles('language-wrapper', lgCode.length > 2 && 'large')}
            >
              <div className={styles('language-label', type)}>{lgCode}</div>
              <div className={styles('field-wrapper-container')}>
                <Field
                  {...rest}
                  {...inputProps}
                  // adding min rows
                  rows={2}
                  component={this.getComponent()}
                  fieldWrapperClassName={styles(
                    inputProps.fieldWrapperClassName,
                    this.checkMatch(lgCode),
                  )}
                  name={`${name}.${lgCode}`}
                  type="text"
                  noMargin
                  validate={item && item.required ? required : null}
                />
                {lock && (
                  <div
                    className={styles(
                      'icon-locker',
                      locked && 'active',
                      type === 'wysiwyg' && 'with-wysiwyg',
                    )}
                    onClick={lock}
                  >
                    {locked ? <FaLock /> : <FaUnlock />}
                  </div>
                )}
              </div>
            </div>
          );
        })}
        {numLg > config.maxNumLanguagesDisplayed && (
          <>
            {!displayAllLanguages && (
              <div className={styles('language-wrapper', currentLg.length > 2 && 'large')}>
                <div className={styles('language-label', type)}>{currentLg}</div>
                <div className={styles('field-wrapper-container')}>
                  <Field
                    {...rest}
                    {...inputProps}
                    rows={2}
                    component={this.getComponent()}
                    fieldWrapperClassName={styles(
                      inputProps.fieldWrapperClassName,
                      this.checkMatch(currentLg),
                    )}
                    name={`${name}.${currentLg}`}
                    type="text"
                    noMargin
                    validate={item && item.required ? required : null}
                  />
                  {lock && (
                    <div
                      className={styles(
                        'icon-locker',
                        locked && 'active',
                        type === 'wysiwyg' && 'with-wysiwyg',
                      )}
                      onClick={lock}
                    >
                      {locked ? <FaLock /> : <FaUnlock />}
                    </div>
                  )}
                </div>
              </div>
            )}
            <div className={styles('language-switch')}>
              {!displayAllLanguages &&
                config.languages.map((l, key) => {
                  const lgCode = l.short || l.value;
                  // if (label === currentLg) return false;
                  if (lgCode === mainLanguage) return false;
                  return (
                    <div
                      key={key}
                      onClick={() => this.switchLanguage(lgCode)}
                      className={styles('language-label', currentLg === lgCode && 'active')}
                    >
                      {lgCode}
                    </div>
                  );
                })}
              <ModuleButton
                className={styles('button')}
                noMargin
                color="grey"
                small
                relative
                label={displayAllLanguages ? 'admin.buttons.hideAll' : 'admin.buttons.showAll'}
                action={this.toggleDisplayLanguages}
              />
            </div>
          </>
        )}
      </div>
    );
  }
}
