import { Form, Formik } from 'formik';
import React from 'react';
import * as Yup from 'yup';
import { useStoreDispatch } from '../../App';
import { SetModal } from '../../store/actions/Settings';
import InputWrapper from '../InputWrapper/InputWrapper';
import s from './ShareByEmailForm.module.scss';

export type initialValuesT = {
  email: string;
};

const axios = require('axios');

const getValidationSchema = () => {
  return Yup.object({
    email: Yup.string().email().required('The field is required'),
  });
};

export const ShareByEmailForm = ({ link }: any) => {
  const dispatch = useStoreDispatch();

  const initialValues: initialValuesT = {
    email: '',
  };

  const onSubmitForm = (values: initialValuesT) => {
    let formData = {
      ...values,
      link: link,
    };

    axios
      .post(
        'https://quadratecbeta-z9cen.ondigitalocean.app/api/contact',
        formData,
        {
          headers: {
            // 'Content-Type': 'multipart/form-data',
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          },
          withCredentials: false,
        }
      )
      .then((props: any) => {
        console.log('props: ', props.data.status);
        if (props.data.status == 'OK') {
          dispatch(
            SetModal({
              list: {
                MailComponent: false,
              },
            })
          );
          dispatch(SetModal({ list: { MailSent: true } }));

          setTimeout(() => {
            dispatch(SetModal({ list: { MailSent: false } }));
          }, 2000);
        }
      });

    // const actualData: any = values;
    // let formData = new FormData();

    // Object.keys(actualData).forEach((key: string) => {
    //   formData.append(key, actualData[key]);
    // });
    // axios({
    //   method: 'POST',
    //   url: 'http://localhost:3001/api/contact',
    //   body: formData,
    //   headers: {
    //     'Content-Type': 'multipart/form-data',
    //   },
    // })
    //   .then((response: any) => {
    //     console.log('response: ', response);
    //   })
    //   .catch(() => {
    //     // popUp({ type: 'error', message: 'Oh, something went wrong!' });
    //   });
  };

  return (
    <Formik
      initialValues={initialValues}
      enableReinitialize
      validationSchema={getValidationSchema()}
      onSubmit={onSubmitForm}
    >
      <Form className={s.contact_form}>
        <InputWrapper
          type="text"
          name="email"
          labelFor="emailContact"
          placeholder="example@gmail.com"
          tag="input"
        />

        <button type="submit" className={s.submit}>
          Send
        </button>
      </Form>
    </Formik>
  );
};
