import React, { useState, FC, useEffect } from 'react';
import { validationWithMessages } from '@/utils/validate';
import DatePicker from 'react-datepicker';
import { enUS, es } from 'date-fns/locale';
import axios from 'axios';
import * as Yup from 'yup';
import { apiContactMessages, apiEmailontact, apiToken } from '@/data/constants';
import { useRouter } from 'next/router';
import moment from 'moment';
interface ContactFormProps {
  trans: any;
  cities: any[];
  background?: string;
}
const INITIAL_VALUES = {
  email: '',
  name: '',
  phone: '',
  schedule: '',
  city: '',
  date: null,
  message: ''
};
const INITIAL_ERRORS = {
  email: '',
  name: '',
  phone: '',
  schedule: '',
  city: '',
  message: '',
  date: '',
  general: ''
};
const ContactForm: FC<ContactFormProps> = ({ trans, cities, background }) => {
  const schedules = trans('contact:form.schedules', { returnObjects: true });
  const [errors, setErrors] = useState(INITIAL_ERRORS);
  const [formData, setFormData] = useState(INITIAL_VALUES);
  const [status, setStatus] = useState('loaded');
  const [citiesOptions, setCitiesOptions] = useState<any[]>([]);
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  const { locale } = useRouter();
  const dateFnsLocale = locale === 'es' ? es : enUS;
  useEffect(() => {
    if (cities && Array?.isArray(cities) && cities?.length) {
      const citiesArray = cities?.map((city) => {
        return { value: city?.id, label: city?.name + ', ' + city?.state?.name };
      });
      setCitiesOptions(citiesArray);
    } else {
      setCitiesOptions([]);
    }
  }, [cities]);

  const handleErrors = (name: string, value: any) => {
    setErrors((prevState) => ({
      ...prevState,
      [name]: value
    }));
  };

  const yupObjectShape = {
    name: Yup.string().required(trans('common:formMessages.errorRequired')),
    //schedule: Yup.string().required(trans('common:formMessages.errorRequired')),
    //  city: Yup.string().required(trans('common:formMessages.errorRequired')),
    phone: Yup.string()
      .matches(/^\d{10}$/, trans('common:formMessages.errorPhone'))
      .required(trans('common:formMessages.errorRequired')),

    email: Yup.string()
      .email(trans('common:formMessages.errrorEmail'))
      .required(trans('common:formMessages.errorRequired'))
  };
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
    handleErrors(e.target.name, '');
  };

  const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.preventDefault();
    setStatus('sending');
    const validateForm = await validationWithMessages(yupObjectShape, formData);

    if (validateForm?.isValid) {
      setErrors(INITIAL_ERRORS);
      const options = {
        method: "POST",
        url: apiContactMessages,
        headers: {
          Authorization: "Bearer " + apiToken,
          "Content-Type": "application/json"
        },
        data: {
          data: {
            ...formData,
            city: formData?.city || null,
            phoneNumber: formData?.phone,
            type: "contact",
            date: formData?.date
              ? formData.date
              : null,
          }
        }
      };
      /* const options = {
         method: 'POST',
         url: apiEmailontact,
         params: { ...formData, date: formData?.date ? moment(formData?.date).format('DD-MM-YYYY') : '' },
         headers: {
           Authorization: 'Bearer ' + apiToken,
           'Content-Type': 'multipart/form-data'
         }
       }; */
      try {
        await axios
          .request(options)
          .then(function (response) {
            if (response?.status == 200) {
              setStatus('sended');
            } else {
              setStatus('loaded');
              setErrors({ ...INITIAL_ERRORS, general: trans('common:formMessages.generalError') });
            }
          })
          .catch(function (error) {
            console.error(error);
            setStatus('loaded');
            setErrors({ ...INITIAL_ERRORS, general: trans('common:formMessages.generalError') });
          });
      } catch (error) {
        console.log(error);
        setStatus('loaded');
        setErrors({ ...INITIAL_ERRORS, general: trans('common:formMessages.generalError') });
      }
    } else {
      setStatus('loaded');
      setErrors({ ...INITIAL_ERRORS, ...validateForm?.errors });
    }
  };

  return (
    <div id="contact-form" className=" contact-form" style={{ background: background || '#FFFFFF' }}>
      <div className="container py-12">
        <div className="row g-7">
          <div className="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2  text-center">
            <span className="base-pretitle"> {trans('contact:form.preTitle')}</span>
            <h2 className="base-title !tw-text-main-color   tw-my-4">{trans('contact:form.title')}</h2>
          </div>
          <div className="col-12 col-md-10 offset-md-1 col-lg-8 offset-lg-2 ">
            {(status !== 'sended' && (
              <form className="form needs-validation">
                <div className="messages">
                  {' '}
                  {errors?.general ? (
                    <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light tw-text-center mb-4">
                      {errors?.general}
                    </p>
                  ) : (
                    ''
                  )}
                </div>
                <div className="row gx-4">
                  <div className="col-md-6">
                    <div className="form-floating mb-4 t">
                      <input
                        required
                        type="text"
                        name="name"
                        id="form_name"
                        placeholder={trans('contact:form.name')}
                        className="form-control  "
                        value={formData.name}
                        onChange={handleChange}
                      />
                      <label htmlFor="form_name" className="">
                        {trans('contact:form.name')} *
                      </label>
                      {errors?.name ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.name}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>{' '}
                  <div className="col-md-6">
                    <div className="form-floating mb-4">
                      <input
                        required
                        type="text"
                        name="phone"
                        placeholder={trans('contact:form.phone')}
                        id="cel"
                        className="form-control "
                        value={formData.phone}
                        onChange={handleChange}
                      />
                      <label htmlFor="cel">{trans('contact:form.phone')} *</label>
                      {errors?.phone ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.phone}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>{' '}
                  <div className="col-md-6">
                    <div className="form-floating mb-4">
                      <input
                        required
                        type="email"
                        name="email"
                        id="form_email"
                        className="form-control "
                        placeholder="jane.doe@example.com"
                        value={formData.email}
                        onChange={handleChange}
                      />
                      <label htmlFor="form_email">{trans('contact:form.email')} *</label>
                      {errors?.email ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.email}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>
                  <div className="col-md-6">
                    <div className="form-select-wrapper mb-4">
                      <select
                        className="form-select"
                        id="form-select"
                        name="city"
                        required
                        value={formData.city}
                        onChange={handleChange}
                      >
                        <option disabled value="">
                          {trans('contact:form.selectCity')}
                        </option>
                        {citiesOptions && Array?.isArray(citiesOptions)
                          ? citiesOptions?.map((item: any, key: number) => {
                            return (
                              <option value={item?.value} key={key}>
                                {item?.label}
                              </option>
                            );
                          })
                          : ''}
                      </select>
                      {errors?.city ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.city}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>
                  <div className="col-md-6">
                    <div className="form-floating mb-4">
                      <DatePicker
                        dateFormat={'dd-MM-YYYY'}
                        locale={dateFnsLocale}
                        selected={formData?.date}
                        onChange={(date) => {
                          setFormData((prev: any) => ({
                            ...prev,
                            ['date']: date
                          }));
                          handleErrors('date', '');
                        }}
                        placeholderText={trans('contact:form.date')}
                        className="form-control tw-w-full"
                        wrapperClassName="tw-w-full"
                        onKeyDown={(e) => e.preventDefault()}
                        minDate={tomorrow}
                      />

                      {errors?.message ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.message}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>
                  <div className="col-md-6">
                    <div className="form-select-wrapper mb-4">
                      <select
                        className="form-select"
                        id="form-select"
                        name="schedule"
                        required
                        value={formData.schedule}
                        onChange={handleChange}
                      >
                        <option disabled value="">
                          {trans('contact:form.schedule')}
                        </option>
                        {schedules && Array?.isArray(schedules)
                          ? schedules?.map((item: any, key: number) => {
                            return (
                              <option value={item} key={key}>
                                {item}
                              </option>
                            );
                          })
                          : ''}
                      </select>
                      {errors?.schedule ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.schedule}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>
                  <div className="col-md-12">
                    <div className="form-floating mb-4">
                      <textarea
                        required
                        name="message"
                        placeholder={trans('contact:form.message')}
                        id="message"
                        className="form-control !tw-min-h-[99px] "
                        value={formData.message}
                        onChange={handleChange}
                      />
                      <label htmlFor="message">{trans('contact:form.message')} </label>
                      {errors?.message ? (
                        <p className="tw-text-xs tw-text-red-500 tw-font-inter tw-font-light">{errors?.message}</p>
                      ) : (
                        ''
                      )}
                    </div>
                  </div>
                  <div className="col-12 text-center tw-justify-items-center">
                    {status === 'sending' ? (
                      <div className="mx-auto mx-md-0 tw-animate-bounce tw-bg-main-color tw-text-white tw-rounded tw-py-3 tw-w-[300px] tw-max-w-full tw-font-inter tw-font-semibold tw-uppercase tw-mx-auto  tw-block hover:tw-opacity-75 ">
                        {trans('common:formMessages.sending')} ...
                      </div>
                    ) : (
                      <button
                        onClick={handleSubmit}
                        className="tw-bg-main-color tw-text-white tw-rounded tw-py-3 tw-w-[300px] tw-max-w-full tw-font-inter tw-font-semibold tw-uppercase tw-mx-auto  tw-block hover:tw-opacity-75"
                      >
                        {trans('contact:form.cta')}
                      </button>
                    )}
                  </div>
                </div>
              </form>
            )) ||
              ''}
            {status === 'sended' ? (
              <div className="text-center py-2 py-md-12">
                <i className="tw-block mb-6 uil uil-check-circle tw-text-6xl tw-font-inter tw-text-main-color"></i>
                <p className="tw-font-inter tw-text-4xl tw-text-secondary-dark tw-text-center">
                  {trans('common:formMessages.sended')}
                </p>
              </div>
            ) : (
              ''
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default ContactForm;
