import axios, { AxiosError } from 'axios'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import _map from 'lodash/map'
import React, { useEffect, useState } from 'react'

import { IDelegationsData, IDelegationsTicketType } from '../../api/guestTicketDelegation'
import { getDelegationTickets, issueTicket } from '../../api/index'
import { CONFIGS, getQueryVariable } from '../../utils'
import { Loader } from '../common'
import ConfirmModal from '../confirmModal'
import { DELEGATION_ACCESS_ERROR } from '../idVerificationContainer/constants'
import IssueTicketForm from './IssueTicketForm'
import TicketsAssignedTable from './TicketsAssignedTable'
import TicketsAvailableTable from './TicketsAvailableTable'

export interface IssueTicketData {
  headTitle?: string;
  classNamePrefix?: string;
  onGetIssuePageDataSuccess?: () => void;
  onGetIssuePageDataError?: (e: AxiosError) => void;
}

const IssueComponent = ({
  classNamePrefix = 'delegations',
  headTitle = 'Manage Your Guest Tickets',
  onGetIssuePageDataSuccess = _identity,
  onGetIssuePageDataError = _identity,
}: IssueTicketData) => {
  const [loading, setLoading] = useState(true)
  const [showMaxQtyModal, setShowMaxQtyModal] = useState(false)
  const [showSuccessModal, setShowSuccessModal] = useState(false)
  const [error, setError] = useState('')
  const accessHash = getQueryVariable('hash') || ''
  const [issuePageData, setIssuePageData] = useState<IDelegationsData>(
    {} as IDelegationsData
  )

  useEffect(() => {
    const fetchDelegationTickets = async () => {
      try {
        const res = await getDelegationTickets(accessHash)
        setLoading(false)
        setIssuePageData(res?.data?.data?.attributes || {})
        onGetIssuePageDataSuccess()
      } catch (e) {
        setLoading(false)
        if (axios.isAxiosError(e)) {
          onGetIssuePageDataError(e)
        }
      }
    }
    fetchDelegationTickets()
  }, [showSuccessModal])
  const selectTicketTypeOptions = _map(
    issuePageData.ticketTypes || ({} as IDelegationsTicketType),
    (val, key) => ({
      value: key,
      label: val.optionValue,
    })
  )
  return (
    <div className={`${classNamePrefix}-container`}>
      {loading ? (
        <Loader />
      ) : (
        <>
          {showMaxQtyModal && (
            <ConfirmModal
              hideCancelBtn={true}
              message={error}
              onClose={() =>
                error === DELEGATION_ACCESS_ERROR
                  ? (window.location.href = '/')
                  : setShowMaxQtyModal(false)
              }
              onConfirm={() =>
                error === DELEGATION_ACCESS_ERROR
                  ? (window.location.href = '/')
                  : setShowMaxQtyModal(false)
              }
            />
          )}
          {showSuccessModal && (
            <ConfirmModal
              hideCancelBtn={true}
              message="Your ticket successfully issued."
              onClose={() => setShowSuccessModal(false)}
              onConfirm={() => setShowSuccessModal(false)}
            />
          )}
          <div className={`${classNamePrefix}-head-title`}>{headTitle}</div>
          <div className={`${classNamePrefix}-inner-blocks`}>
            <div className={`${classNamePrefix}-image-block`}>
              <img
                src={`${CONFIGS.BASE_URL}${issuePageData?.eventImage}`}
                alt="main_event_img"
                title=""
              />
            </div>
            <div className={`${classNamePrefix}-tables`}>
              <TicketsAvailableTable
                tableTitle="Tickets available"
                issuePageData={issuePageData}
                classNamePrefix="delegations"
              />
              <TicketsAssignedTable
                tableTitle="Tickets assigned"
                issuePageData={issuePageData}
                classNamePrefix="delegations"
              />
              <div className={`${classNamePrefix}-issue-block`}>
                <div className={`${classNamePrefix}-issue-title`}>Issue New Tickets</div>
                <div className={`${classNamePrefix}-issue-subtitle`}>
                  Please select the type of tickets and enter recipient details:
                </div>
              </div>
              <IssueTicketForm
                classNamePrefix={'delegations'}
                handleSubmit={async (values: any, { resetForm, setSubmitting }) => {
                  try {
                    await issueTicket(accessHash, values)
                    setShowSuccessModal(true)
                    resetForm()
                  } catch (e) {
                    if (axios.isAxiosError(e)) {
                      const error = _get(e, 'response.data.message') || 'Error'
                      setError(error)
                    } else if (e instanceof Error) {
                      setError(e?.message || 'Error')
                    }
                    setShowMaxQtyModal(true)
                  } finally {
                    setLoading(false)
                    setSubmitting(false)
                  }
                }}
                selectTicketTypeOptions={selectTicketTypeOptions}
                initialValues={{
                  ticketTypeId: '',
                  firstName: '',
                  lastName: '',
                  email: '',
                  confirmEmail: '',
                  confirm: false,
                }}
              />
            </div>
          </div>
        </>
      )}
    </div>
  )
}

export default IssueComponent
