import * as React from 'react';
import classNames from 'classnames/bind';
import GenericValue from 'components/items/GenericValue';

import { get } from 'lodash';
import { viewConfig, config } from 'config/general';
import styleIdentifiers from './genericDisplayFields.scss';
import GenericDropDown from '../GenericDropDown';
import LanguageSelector from '../LanguageSelector';

const styles = classNames.bind(styleIdentifiers);

export interface GenericDisplayFieldsProps {
  fields: Record<string, any>;
  loadData?: Function;
  loadOne?: Function;
  data?: Record<string, any>;
}

interface GenericDisplayFieldsState {}

export default class GenericDisplayFields extends React.Component<
  GenericDisplayFieldsProps,
  GenericDisplayFieldsState
> {
  constructor(props) {
    super(props);

    this.state = {
      activeLgs: [config.defaultLanguage],
    };
  }

  renderItem = (genericItem: any, key: string) => {
    const { item, oneSection, ...rest } = this.props;
    const { activeLgs } = this.state;

    this.setState({
      activeLgs: [config.defaultLanguage],
    });
  };

  checkIfLanguageSelector = array => {
    for (let index = 0; index < array.length; index++) {
      const element = array[index];
      if (element.type?.includes('multi')) return true;
      if (element.fields) {
        const sublevel = Object.values(element.fields);
        if (this.checkIfLanguageSelector(sublevel)) {
          return true;
        }
      }
    }
    return false;
  };

  renderItem = (genericItem: any, key: string) => {
    const { item, oneSection, allOpened, ...rest } = this.props;
    const { activeLgs } = this.state;

    if (!genericItem) return false;

    if (genericItem.hideDetail || genericItem.noDetail) return false;

    if (genericItem.type === 'col' || genericItem.type === 'column') {
      return (
        <div key={key} className={styles('column')}>
          <GenericDisplayFields {...rest} fields={genericItem.fields} />
        </div>
      );
    }

    if (genericItem.type === 'section') {
      let arrayFields = genericItem.fields;
      if (arrayFields && !Array.isArray(arrayFields)) arrayFields = Object.values(arrayFields);

      return (
        <div key={key} className={styles('section-wrapper')}>
          <GenericDropDown
            title={genericItem.label || 'Default'}
            titleClassName={styles('section-title')}
            defaultOpen={genericItem.opened || oneSection || allOpened}
            key={key}
            className={styles('section')}
          >
            {this.checkIfLanguageSelector(arrayFields) && (
              <LanguageSelector
                active={activeLgs}
                onSelect={e => this.setState({ activeLgs: e })}
              />
            )}
            <GenericDisplayFields displayLgs={activeLgs} {...rest} fields={genericItem.fields} />
          </GenericDropDown>
        </div>
      );
    }

    return (
      <div key={key} className={styles('field')}>
        {this.renderField(genericItem, key)}
      </div>
    );
  };

  renderTitle = (values, name, index) => {
    const value = get(values, name, index);

    if (!value) return false;

    return value;
  };

  renderField = (genericItem: any, key: string) => {
    const {
      data,
      loadOne,
      resourceData,
      item,
      noUpdate,
      transformedData,
      displayLgs,
      ...rest
    } = this.props;

    const name =
      genericItem.name || genericItem.displayDetailValue || genericItem.displayValue || key;

    const itemsDataKey = genericItem.itemsDataKey;

    const value = get(data, name);
    const itemsValue = get(resourceData, itemsDataKey);

    const type = genericItem.type;

    const displayIf = genericItem.displayIf;
    const hideIf = genericItem.hideIf;

    if (displayIf && !value) {
      return false;
    }

    if (hideIf && !value) {
      return false;
    }

    if (type === 'separator') {
      return (
        <div className={styles('separator', genericItem.small && 'intermediary')}>
          <h3>{genericItem.label}</h3>
        </div>
      );
    }

    if (type === 'geoloc' && genericItem.multiple) {
      return value?.map((it, itKey) => (
        <GenericValue
          key={itKey}
          {...viewConfig.inputProps}
          apiPayload={genericItem.api}
          transformedData={transformedData}
          loadApi={loadOne}
          apiDataKey={genericItem.dataKey}
          item={{ ...genericItem, noMargin: true }}
          noLabel
          value={it}
          dataKey={key}
          data={data}
          noUpdate={noUpdate}
        />
      ));
    }

    if (type === 'list') {
      const listValues = Array.isArray(value) && value;

      console.log('listValues', listValues);
      return (
        <div>
          {!genericItem.noLabel && genericItem.label && (
            <div
              className={styles(
                'separator',
                (genericItem.first || genericItem.noMargin) && 'no-margin',
              )}
            >
              <h3>{genericItem.label || key}</h3>
            </div>
          )}
          {listValues &&
            listValues.length > 0 &&
            value.map((it, index) => (
              <GenericDropDown
                title={
                  this.renderTitle(
                    it,
                    genericItem.itemLabel || genericItem.dropdownLabel || 'title',
                  ) || `item ${index + 1}`
                }
                key={index}
                className={styles('list-value')}
                titleClassName={styles('title-dropdown')}
              >
                <GenericDisplayFields
                  {...rest}
                  displayLgs={displayLgs}
                  noUpdate
                  transformedData={transformedData}
                  data={it}
                  fields={genericItem.fields}
                />
              </GenericDropDown>
              // <div className={styles('list-value')} key={index}>
              //   <GenericDisplayFields
              //     {...rest}
              //     displayLgs={displayLgs}
              //     noUpdate
              //     transformedData={transformedData}
              //     data={it}
              //     fields={genericItem.fields}
              //   />
              // </div>
            ))}
          {(!listValues || (listValues && listValues.length === 0)) && <span>-</span>}
        </div>
      );
    }

    return (
      <GenericValue
        {...viewConfig.inputProps}
        apiPayload={genericItem.api}
        transformedData={transformedData}
        loadApi={loadOne}
        apiDataKey={genericItem.dataKey}
        item={genericItem}
        itemsValue={itemsValue}
        value={value}
        dataKey={key}
        data={data}
        noUpdate={noUpdate}
        activeLgs={displayLgs}
      />
    );
  };

  render() {
    const { item, fields } = this.props;

    const data = fields || item;
    const keys = data && Object.keys(data);

    if (!keys) return false;

    return (
      <div className={styles('GenericDisplayFields')}>
        {keys.map(key => this.renderItem(data[key], key))}
      </div>
    );
  }
}
