import './style.css'

import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Modal from '@mui/material/Modal'
import { Field, Form, Formik } from 'formik'
import React from 'react'
import SVG from 'react-inlinesvg'
import * as yup from 'yup'

import EmailSvg from '../../assets/images/email.svg'
import UserSvg from '../../assets/images/user.svg'
import { CheckboxField } from '../common/CheckboxField'
import { CustomField } from '../common/CustomField'
import { RadioField } from '../common/RadioField'
import { ITicketTypes } from '../orderDetailsContainer/ticketsTable'

interface Props {
  ticket: ITicketTypes;
  onClose: () => void;
  onSubmit: (values: InitialValuesTypes) => void;
  loading?: boolean;
}

export interface InitialValuesTypes {
  to: string;
  first_name: string;
  last_name: string;
  email: string;
  confirm_email: string;
  confirm: boolean;
}

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'
}

const schema = yup.object().shape({
  to: yup.string().required(),
  first_name: yup.string().when('to', {
    is: (to: string) => to === 'friend',
    then: yup.string().required('First Name is required')
  }),
  last_name: yup.string().when('to', {
    is: (to: string) => to === 'friend',
    then: yup.string().required('Last Name is required')
  }),
  email: yup.string().when('to', {
    is: (to: string) => to === 'friend',
    then: yup.string().email('Invalid email').required('Email is required')
  }),
  confirm_email: yup.string().when('to', {
    is: (to: string) => to === 'friend',
    then: yup.string().email('Invalid email').oneOf([yup.ref('email'), null], 'Emails must match').required('Confirm Email is required')
  }),
  confirm: yup.boolean().oneOf([true])
})

const initialValues: InitialValuesTypes = {
  to: 'friend',
  first_name: '',
  last_name: '',
  email: '',
  confirm_email: '',
  confirm: false
}

export const TicketResaleModal = ({
  ticket = {} as ITicketTypes,
  onClose = () => { },
  onSubmit = () => { },
  loading = false
}: Props) => {
  const { hash, holder_name, event_name, currency, retain_amount_on_sale, ticket_type_is_active } = ticket

  return (
    <Modal
      open={true}
      onClose={onClose}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
      className='resale-modal'
    >
      <Box style={style}>
        <h3>Sell Ticket</h3>
        <div>
          <h3>Ticket Details</h3>
          <div>
            <h4>Event</h4>
            <p>{event_name}</p>
          </div>
          <div>
            <h4>Ticket Holder</h4>
            <p>{holder_name}</p>
          </div>
          <div>
            <h4>Ticket ID</h4>
            <p>{hash}</p>
          </div>
        </div>
        <div>
          <h3>Sell to Whom</h3>
          <Formik
            initialValues={initialValues}
            validationSchema={schema}
            onSubmit={onSubmit}
          >
            {({ values, isValid, dirty }) => (
              <Form>
                <div>
                  <Field
                    name='to'
                    label='I want to sell the ticket to someone I know'
                    type='radio'
                    value='friend'
                    component={RadioField}
                  />
                  {values.to === 'friend' && (
                    <div className='sell-to-friend'>
                      <div className='user-info-box'>
                        <div className='field-box'>
                          <div className='icon'>
                            <SVG
                              src={UserSvg}
                              width='24'
                              height='24'
                            />
                          </div>
                          <Field
                            name='first_name'
                            label='First Name'
                            type='text'
                            component={CustomField}
                          />
                        </div>
                        <div className='field-box'>
                          <div className='empty-box' />
                          <Field
                            name='last_name'
                            label='Last Name'
                            type='text'
                            component={CustomField}
                          />
                        </div>
                      </div>
                      <div className='email-info-box'>
                        <div className='field-box'>
                          <div className='icon'>
                            <SVG
                              src={EmailSvg}
                              width='24'
                              height='24'
                            />
                          </div>
                          <Field
                            name='email'
                            label='Email address'
                            type='text'
                            component={CustomField}
                          />
                        </div>
                        <div className='field-box'>
                          <div className='empty-box' />
                          <Field
                            name='confirm_email'
                            label='Confirm Email address'
                            type='text'
                            component={CustomField}
                          />
                        </div>
                      </div>
                    </div>
                  )}
                </div>
                {ticket_type_is_active && (
                  <div>
                    <Field
                      name="to"
                      label="I will sell my ticket to anyone who wants to buy it"
                      type="radio"
                      value="anyone"
                      component={RadioField}
                    />
                  </div>
                )}
                <div>
                  <h4>Terms of Resale</h4>
                  <p>I confirm that I want to sell this ticket and that, if someone chooses to buy it, I will no longer own it or have the right to ask for it back.</p>
                  <p>I also understand that, if no one chooses to buy it, it remains my property, is valid for entry to <strong>{event_name}</strong> and I will not receive any refund.</p>
                  <p>If my ticket is sold, the original card I used to buy my ticket will be refunded with the original amount paid, minus a small handling fee of <strong>{`${currency ?? ''} ${retain_amount_on_sale ?? '0'}`}</strong>, and that any existing refunds due to me for referring sales for this event are no longer valid.</p>
                  <Field
                    name='confirm'
                    label='I agree'
                    type='checkbox'
                    component={CheckboxField}
                  />
                </div>
                <div className="resale-action-button">
                  <Button
                    type="submit"
                    disabled={!(isValid && dirty)}
                  >
                    {loading ? <CircularProgress size="22px" /> : 'Sell Ticket'}
                  </Button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      </Box>
    </Modal>
  )
}
