import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Modal from '@mui/material/Modal'
import { Field, Form, Formik } from 'formik'
import React, { useState } from 'react'

import { sendRSVPInfo } from '../../api'
import { isBrowser } from '../../utils'
import { combineValidators, emailValidator, requiredValidator } from '../../validators'
import { CustomField, Loader } from '../common/index'

interface IRsvpContainerPage {
  showSection?: boolean;
  eventId: number;
}

interface IRSVPValuesTypes {
  email: string;
}

const style: React.CSSProperties = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  minWidth: 480,
  backgroundColor: '#e3e3e3',
  border: '1px solid white',
  outline: 'none',
  padding: '14px',
  maxHeight: '85vh',
  overflow: 'auto',
}

export const RsvpContainer = ({ showSection = false, eventId }: IRsvpContainerPage) => {
  const userDataEncoded = isBrowser ? window.localStorage.getItem('user_data') : ''
  const parsedData = JSON.parse(userDataEncoded || '{}')

  const [loading, setLoading] = useState(false)
  const [modal, setModal] = useState({ isOpen: false, text: '' })

  const handleModalClose = () => {
    setModal({ isOpen: false, text: '' })
  }

  const handleSubmit = async (values: IRSVPValuesTypes) => {
    try {
      setLoading(true)

      const requestData = { data: { email: values.email } }
      const response = await sendRSVPInfo(eventId, requestData)

      setModal({ isOpen: true, text: response.message })
    } catch (error) {
      if (error.response.status === 403) {
        setModal({ isOpen: true, text: error.response.data?.message })
      }
    } finally {
      setLoading(false)
    }
  }

  if (!showSection) {
    return null
  }

  return (
    <>
      <Modal
        open={modal.isOpen}
        onClose={handleModalClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        className="rsvp-modal"
      >
        <Box style={style} className="rsvp-modal-box">
          <div className="rsvp-modal-container">
            <div className="rsvp-modal-header">{modal.text}</div>
            <div className="rsvp-modal-button">
              <button type="button" onClick={handleModalClose}>
                OK
              </button>
            </div>
          </div>
        </Box>
      </Modal>
      <div className="rsvp-container">
        {loading ? (
          <Loader />
        ) : (
          <>
            <div className="rsvp-header">RSVP</div>
            <div className="rsvp-email-container">
              <Formik
                initialValues={{
                  email: parsedData?.email || '',
                }}
                onSubmit={handleSubmit}
                enableReinitialize
              >
                <Form>
                  <div className="rsvp-email-input-container">
                    <Field
                      name="email"
                      label="EMAIL ADDRESS"
                      type="email"
                      validate={combineValidators(
                        (value: string) =>
                          requiredValidator(value, 'Please enter your Email'),
                        (value: string) => emailValidator(value)
                      )}
                      component={CustomField}
                    />
                  </div>
                  <div className="rsvp-button-container">
                    <Button type="submit">RSVP</Button>
                  </div>
                </Form>
              </Formik>
            </div>
          </>
        )}
      </div>
    </>
  )
}
