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

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

// Import actions here
import accountActions from 'store/account/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import notificationsForm from 'components/forms/NotificationsForm';
import AccountStructure from 'components/structure/AccountStructure';
import { settings } from 'cluster';
import styleIdentifiers from './notifications.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type NotificationsProps = StateProps & DispatchProps & OwnProps;

const Notifications = (props: NotificationsProps) => {
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);

  const profile = useSelector(
    (state: StoreState) => state.account.profile && state.account.profile.data,
  );

  // Allow to dispatch actions
  const dispatch = useDispatch();

  const [initialValues, setInitialValues] = useState();

  const handleSubmit = values => {
    console.log(values);
    values.notifications = { ...values.notifications, type: 'notifications' };
    values.promotions = { ...values.promotions, type: 'promotions' };
    values.reminders = { ...values.reminders, type: 'reminders' };

    const array = [];

    const keys = Object.keys(values);
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      const elem = values[key];
      array.push(elem);
    }

    dispatch(
      accountActions.updateProfile.request.action({
        data: {
          settings: array,
        },
        callback: res => {
          console.log(res);
        },
        success: 'pages.account.notification.updateSuccess',
      }),
    );
  };

  useEffect(() => {
    const object = {};
    console.log(profile);
    if (profile.settings) {
      profile.settings.forEach(setting => {
        const { type, email, pushNotifications, sms } = setting;
        object[type] = {
          email,
          pushNotifications,
          sms,
        };
      });

      setInitialValues(object);
    }
  }, []);

  return (
    <AccountStructure
      title="pages.account.notification"
      rightBack
      className={styles('notifications')}
    >
      <Form
        component={notificationsForm}
        initialValues={initialValues}
        onSubmit={handleSubmit}
        customClassName={styles('notifications-form')}
      />
    </AccountStructure>
  );
};

export default Notifications;
