import './style.css'

import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import { Field, Form, Formik } from 'formik'
import _find from 'lodash/find'
import React, { useState } from 'react'

import { addToWaitingList } from '../../api'
import { isBrowser } from '../../utils'
import { ErrorFocus } from '../../utils/formikErrorFocus'
import {
  combineValidators,
  emailValidator,
  requiredValidator,
} from '../../validators'
import { CustomField } from '../common/index'

interface WaitingListProps {
  tickets: any;
  eventId: number;
  defaultMaxQuantity: number;
}

interface WaitingListFields {
  ticketTypeId: string;
  quantity: string;
  firstName: string;
  lastName: string;
  email: string;
}

const generateQuantity = (n: number) => {
  const quantityList = []
  for (let i = 1; i <= n; i++) {
    quantityList.push({ label: i, value: i })
  }
  return quantityList
}

const WaitingList = ({
  tickets = {},
  eventId,
  defaultMaxQuantity = 10,
}: WaitingListProps) => {
  const userData =
    isBrowser && window.localStorage.getItem('user_data')
      ? JSON.parse(window.localStorage.getItem('user_data') || '')
      : {}

  const [showSuccessMessage, setShowSuccessMessage] = useState(false)
  const [loading, setLoading] = useState(false)
  const ticketTypesList = Object.values(tickets).map((d: any) => ({
    label: d.displayName,
    value: d.id,
  }))

  const showTicketsField = Boolean(ticketTypesList.length)

  const handleSubmit = async (values: WaitingListFields) => {
    try {
      setLoading(true)
      const response = await addToWaitingList(eventId, { attributes: values })

      if (response.success) {
        setShowSuccessMessage(true)
      }
    } catch (error) {
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="waiting-list">
      {showSuccessMessage ? (
        <div className="success-message">
          <p className="added-success-message">You&apos;ve been added to the waiting list!</p>
          <p>You&apos;ll be notified if tickets become available.</p>
        </div>
      ) : (
        <>
          <h2>WAITING LIST</h2>
          <Formik
            initialValues={{
              ticketTypeId: '',
              quantity: '',
              firstName: userData.first_name || '',
              lastName: userData.last_name || '',
              email: userData.email || '',
            }}
            onSubmit={handleSubmit}
          >
            {({ values, setFieldValue }) => {
              const selectedTicket = _find(tickets, n => n.id === values.ticketTypeId)
              return (
                <Form>
                  <ErrorFocus />
                  {showTicketsField && (
                    <>
                      <div className="field-item">
                        <Field
                          name="ticketTypeId"
                          label="Type of Ticket"
                          type="select"
                          component={CustomField}
                          onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
                            setFieldValue('ticketTypeId', e.target.value)
                            setFieldValue('quantity', '')
                          }}
                          selectOptions={[
                            { label: 'Type of Ticket', value: '', disabled: true },
                            ...ticketTypesList,
                          ]}
                        />
                      </div>
                      <div className="field-item">
                        <Field
                          name="quantity"
                          label="Quantity Requested"
                          type="select"
                          component={CustomField}
                          selectOptions={[
                            {
                              label: 'Quantity Requested',
                              value: '',
                              disabled: true,
                            },
                            ...generateQuantity(selectedTicket?.waitingListMaxQuantity || (defaultMaxQuantity ?? 10)
                            ),
                          ]}
                        />
                      </div>
                    </>
                  )}
                  <div className="field-item">
                    <Field
                      name="firstName"
                      label="First name"
                      validate={(value: string) =>
                        requiredValidator(value, 'Please enter your First name')
                      }
                      component={CustomField}
                    />
                  </div>
                  <div className="field-item">
                    <Field
                      name="lastName"
                      label="Last name"
                      validate={(value: string) =>
                        requiredValidator(value, 'Please enter your Last name')
                      }
                      component={CustomField}
                    />
                  </div>
                  <div className="field-item">
                    <Field
                      name="email"
                      label="Email"
                      validate={combineValidators(
                        (value: string) =>
                          requiredValidator(value, 'Please enter your Email'),
                        (value: string) => emailValidator(value)
                      )}
                      component={CustomField}
                    />
                  </div>

                  <Button
                    type="submit"
                    variant="contained"
                    className="waiting-list-button"
                  >
                    {loading ? (
                      <CircularProgress size="22px" />
                    ) : (
                      'ADD TO WAITING LIST'
                    )}
                  </Button>
                </Form>
              )
            }}
          </Formik>
        </>
      )}
    </div>
  )
}

export default WaitingList
