import React, { useEffect, useState } from 'react';
import { Field } from 'react-final-form';

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

// Import actions here

import classNames from 'classnames/bind';
import Input from 'components/formItems/Input';
import ModuleButton from 'components/items/ModuleButton';
import CustomSelect from 'components/formItems/CustomSelect';
import { required, email, composeValidators } from 'store/utils/validation';
import genericApollo from 'store/genericApollo';
import shop from 'store/shop';
import countries from 'data/countries';
import { constants, viewConfig } from 'config/general';
import { isOdd } from 'store/utils/helper';
import currency from 'config/data/currency';
import styleIdentifiers from './priceForm.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  onSubmit: Function;
}

export type PriceFormProps = StateProps & DispatchProps & OwnProps;

const PriceForm = (props: PriceFormProps) => {
  const { handleSubmit, submitting, valid, initialValues } = props;

  const [price, setPrice] = useState(null);
  const [curr, setCurrency] = useState(null);

  // mapStateToProps
  const vat = useSelector((state: StoreState) => state.shop.vatValues);
  const lg = useSelector((state: StoreState) => state.content.lg);

  const dispatch = useDispatch();

  const loadApolloData = e => dispatch(genericApollo.actions.search.request.action(e));

  function handleLoadVat(id) {
    dispatch(shop.actions.vat.loadValues.request.action({ id }));
  }

  function handleOrderData(e) {
    const res = [...e];
    const countryPrio = ['BE', 'US'];

    for (let index = 0; index < countryPrio.length; index++) {
      const element = countryPrio[index];
      const ind = res.findIndex(y => y.value === element);
      if (ind !== -1) res.splice(ind, 1);
    }

    return res;
  }

  function getPrioData(list) {
    const res = [];
    const countryPrio = ['BE', 'US'];

    for (let index = 0; index < countryPrio.length; index++) {
      const element = countryPrio[index];
      const item = list.find(y => y.value === element);
      res.push({ ...item, prio: true });
    }

    return res;
  }

  const tax = vat && vat.data;

  useEffect(() => {
    if (initialValues) {
      if (initialValues.price) setPrice(initialValues.price);
      if (initialValues.currency) setCurrency(initialValues.currency);
      if (initialValues.vatClassId) handleLoadVat(initialValues.vatClassId);
    }
    return () => dispatch(shop.actions.vat.resetValues.action());
  }, []);

  return (
    <form className={styles('price-form')} onSubmit={handleSubmit}>
      <div className={styles('top')}>
        <Field
          component={Input}
          onChange={e => setPrice(e)}
          name="price"
          label="Price"
          {...viewConfig.inputProps}
          validate={required}
          noError
        />
        <Field
          component={CustomSelect}
          loadApiData={loadApolloData}
          apiPayload={{
            resource: 'vatClassGetMany',
          }}
          modelValues={{
            value: '_id',
            text: 'title',
          }}
          noFilterApi
          apollo
          name="vatClassId"
          label="VAT"
          onChange={e => handleLoadVat(e)}
          validate={required}
          {...viewConfig.inputProps}
          noError
        />
        <Field
          component={CustomSelect}
          name="currency"
          label="currency"
          filter
          items={constants.currencyShop || currency}
          modelValues={{ value: 'value' }}
          {...viewConfig.inputProps}
          validate={required}
          onChange={e => setCurrency(e)}
          noError
        />
        <ModuleButton
          className={styles('button')}
          disabled={submitting || !valid}
          label="Submit"
          type="submit"
        />
      </div>
      <div className={styles('tax-container')}>
        {getPrioData(countries)
          .concat(handleOrderData(countries))
          .map((item, key) => (
            <div className={styles('tax-item', isOdd(key) && 'odd', item.prio && 'prio')} key={key}>
              <div className={styles('country')}>{item[lg]}</div>
              <div className={styles('tax')}>
                {`${tax && tax[item.value] ? tax[item.value] : 0}%`}
              </div>
              <div className={styles('price')}>
                {(price * (tax && tax[item.value] ? tax[item.value] / 100 + 1 : 1)).toLocaleString(
                  navigator.language,
                  {
                    style: 'currency',
                    currency: curr || 'EUR',
                  },
                )}
              </div>
            </div>
          ))}
      </div>
    </form>
  );
};

export default PriceForm;
