import 'tf-seat-map-view/dist/index.css'

import React, { useEffect } from 'react'
import ReactDom from 'react-dom'
import SeatMapView from 'tf-seat-map-view'

import { Loader } from '../common'
import { getTierRelationsArray } from './utils'

const CONTAINER_DEFAULT_ID = 'seat_map_default_container'

// Temp solution
declare global {
  interface Window {
    tierPrices: any;
  }
}

export const SeatMapComponent = (props: ISeatMapContainerProps) => {
  const { seatMapProps, mapContainerId } = props
  const {
    seatData,
    statuses,
    seatMapType = null,
    seatMapEvents = {},
    ticketTypeTierRelations = {},
    tierPrices,
    isReserving,
    predefinedSeats,
    isLoadingSeatMapData,
  } = seatMapProps

  useEffect(() => {
    const parentElement = document.getElementById(mapContainerId || CONTAINER_DEFAULT_ID)

    // Temp solution
    window.tierPrices = tierPrices

    if (parentElement) {
      let mapComponent = null

      if (!(seatData && statuses) || isLoadingSeatMapData) {
        mapComponent = <Loader />
      } else {
        mapComponent = (
          <SeatMapView
            disabled={isReserving}
            loading={isReserving}
            events={seatMapEvents}
            isSelectionOn={false}
            seatData={seatData}
            statuses={statuses}
            ticketTypeTireRelationsArray={getTierRelationsArray(ticketTypeTierRelations)}
            width={Math.min(parentElement?.clientWidth || 800, 800)}
            height={Math.min(parentElement?.clientWidth || 800, 800)}
            isBlockMap={seatMapType === 'block'}
            isTableMap={seatMapType === 'table'}
            predefinedSeats={predefinedSeats}
          />
        )
      }

      ReactDom.render(mapComponent, parentElement)
    }
  }, [
    isReserving,
    mapContainerId,
    seatData,
    seatMapEvents,
    seatMapType,
    tierPrices,
    statuses,
    ticketTypeTierRelations,
  ])

  return <div id={CONTAINER_DEFAULT_ID} />
}
