/* eslint-disable @typescript-eslint/no-explicit-any */
import './style.css'

import Box from '@mui/material/Box'
import FormControl from '@mui/material/FormControl'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import moment from 'moment-timezone'
import React, { useState } from 'react'
import { Tooltip } from 'react-tooltip'

import { FEES_STYLES } from '../../constants'
import { CONFIGS } from '../../utils'
import InfoIcon from './InfoIcon'
import { getTicketSelectOptions } from './utils'

function decodeHTML(html: string): string {
  const textArea = document.createElement('textarea')
  textArea.innerHTML = html
  return textArea.value
}

interface TimeSlotOption {
  timeKey: string;
  ticketInstance: any;
}

interface ITimeSlotTicketRowProps {
  ticketKey: string;
  ticket: any;
  availableTimeSlots: TimeSlotOption[];
  selectedTickets: any;
  selectedTimeSlots: any;
  handleTicketSelect: (ticketKey: string, quantity: number, ticketInstance: any) => void;
  handleTimeSlotSelect: (ticketKey: string, timeKey: string, ticketInstance: any) => void;
  priceSymbol: string;
  isSoldOut: boolean;
}

export const TimeSlotTicketRow = ({
  ticketKey,
  ticket,
  availableTimeSlots,
  selectedTickets,
  selectedTimeSlots,
  handleTicketSelect,
  handleTimeSlotSelect,
  priceSymbol,
  isSoldOut,
}: ITimeSlotTicketRowProps) => {
  const [visibleDescription, setVisibleDescription] = useState<boolean>(false)

  const currentSelectedTimeKey = selectedTimeSlots[ticketKey] || ''
  const currentTicketInstance = availableTimeSlots.find(slot => slot.timeKey === currentSelectedTimeKey)?.ticketInstance
  const currentSelectedQuantity = currentTicketInstance ? (selectedTickets[currentTicketInstance.id] || 0) : 0

  const maxCount = ticket.maxQuantity
  const minCount = ticket.minQuantity
  const { multiplier } = ticket
  const options = getTicketSelectOptions(maxCount, minCount, multiplier)

  const ticketPriceWithoutFees = `${priceSymbol} ${(+ticket.cost).toFixed(2)}`
  const ticketPriceWithFees = `${priceSymbol} ${(+ticket.basePrice).toFixed(2)}`
  const ticketOldPriceWithFees = `${priceSymbol} ${(+ticket.oldBasePrice).toFixed(2)}`
  const ticketOldPriceWithoutFees = `${priceSymbol} ${(+ticket.oldCost).toFixed(2)}`
  const ticketFinalPrice = ticket.feeIncluded && !ticket.isForward
    ? +(ticket.x_face_value || ticket.basePrice)
    : ticket.feeIncluded ? +ticket.basePrice : +ticket.cost
  const ticketFinalPriceFormatted = `${priceSymbol} ${parseFloat(ticketFinalPrice.toFixed(2))}`
  const ticketOldFinalPrice = ticket.feeIncluded && !ticket.isForward
    ? +(ticket.x_face_value || ticket.basePrice)
    : ticket.feeIncluded ? +ticket.oldBasePrice : +ticket.oldCost
  const ticketOldFinalPriceFormatted = `${priceSymbol} ${parseFloat(ticketOldFinalPrice.toFixed(2))}`
  const ticketFeeAmount = (+ticket.basePrice - +ticket.cost).toFixed(2)
  const ticketBreakdown = !ticket.feeIncluded
    ? '(+ fees at checkout)'
    : !ticket.isForward
      ? null
      : (parseFloat(ticketFeeAmount) > 0 ? `(${priceSymbol} ${(+ticket.cost).toFixed(2)} + ${priceSymbol} ${ticketFeeAmount} fee)` : null)

  let ticketIsDiscounted = false
  if (ticket.oldPrice && !isSoldOut && ticket.oldPrice !== ticket.price) {
    ticketIsDiscounted = true
  }

  const ticketIsFree = +ticket.price === 0
  const discountTicketPriceElem = CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN
    ? ticketOldFinalPriceFormatted
    : CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH || !ticket.feeIncluded
      ? ticketOldPriceWithoutFees
      : ticketOldPriceWithFees
  const ticketPriceElem = isSoldOut
    ? 'SOLD OUT'
    : ticketIsFree
      ? 'FREE'
      : CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN
        ? ticketFinalPriceFormatted
        : CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH || !ticket.feeIncluded
          ? ticketPriceWithoutFees
          : ticketPriceWithFees

  const handleTimeChange = (event: any) => {
    const selectedTimeKey = event.target.value
    const selectedOption = availableTimeSlots.find(slot => slot.timeKey === selectedTimeKey)
    if (selectedOption) {
      handleTimeSlotSelect(ticketKey, selectedOption.timeKey, selectedOption.ticketInstance)
    }
  }

  const handleQuantityChange = (event: any) => {
    const { value } = event.target
    // Only allow quantity selection if a time slot is selected
    if (!currentSelectedTimeKey && value > 0) {
      return
    }
    if (currentTicketInstance) {
      handleTicketSelect(ticketKey, value, currentTicketInstance)
    }
  }

  const handleDescriptionToggle = () => {
    setVisibleDescription(current => !current)
  }

  return (
    <>
      <div className={`event-detail__tier ${isSoldOut ? 'disabled' : ''}`} id={ticketKey}>
        <div className="event-detail__tier-name">
          {ticket.displayName || ticket.name}
          {ticket.descriptionRich && (
            <>
              <span
                aria-hidden
                className="info-icon"
                onClick={handleDescriptionToggle}
                data-tooltip-id={`tooltip-${ticketKey}`}
                data-tooltip-content="View ticket info"
                style={{
                  marginLeft: 8,
                  cursor: 'pointer',
                  display: 'flex',
                }}
              >
                <InfoIcon />
              </span>

              <Tooltip id={`tooltip-${ticketKey}`} place="top">
                {ticket.description || 'No description available'}
              </Tooltip>
            </>
          )}
        </div>
        <div className="event-tickets-container">
          <div className="event-detail__tier-price">
            {ticketIsDiscounted && <p className="old-price">{discountTicketPriceElem}</p>}
            <p className={isSoldOut ? 'sold-out' : ''}>{ticketPriceElem}</p>
            {!isSoldOut && !ticketIsFree && (
              <p className="fees">
                {CONFIGS.FEES_STYLE === FEES_STYLES.TRADITIONAL &&
                  (ticket.feeIncluded ? '(incl. Fees)' : '(excl. Fees)')}
                {CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH &&
                  `(${ticketPriceWithFees} with fees)`}
                {CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN &&
                  ticketBreakdown}
              </p>
            )}
          </div>
          {!isSoldOut && (
            <div className="event-detail__tier-state time-slot-selectors-container">
              {/* Time Slot Selector */}
              <Box
                sx={{
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: 2,
                  marginTop: 2,
                }}
              >
                <FormControl>
                  <Select
                    sx={{ borderRadius: 0, minWidth: 120 }}
                    value={currentSelectedTimeKey}
                    onChange={handleTimeChange}
                    displayEmpty
                    inputProps={{ 'aria-label': 'Select time slot' }}
                    MenuProps={{
                      PaperProps: {
                        className: 'get-tickets-paper',
                      },
                    }}
                  >
                    <MenuItem value="" disabled>
                      Time
                    </MenuItem>
                    {availableTimeSlots.map((slot, index) => (
                      <MenuItem key={index} value={slot.timeKey}>
                        {moment(slot.ticketInstance.slotStartDate).format('hh:mm A')}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
                {/* Quantity Selector */}
              <FormControl>
                <Select
                  sx={{ borderRadius: 0, minWidth: 60 }}
                  value={currentSelectedQuantity}
                  onChange={handleQuantityChange}
                  displayEmpty
                  disabled={!currentSelectedTimeKey}
                  inputProps={{ 'aria-label': 'Select quantity' }}
                  MenuProps={{
                    PaperProps: {
                      sx: { maxHeight: 150 },
                      className: 'get-tickets-paper',
                    },
                  }}
                >
                  {options.map((option, index) => (
                    <MenuItem key={index} value={option.value}>
                      {option.value}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
              </Box>
            </div>
          )}
        </div>
        {visibleDescription && ticket.descriptionRich && (
          <div className="ticket-description">
            <div
              dangerouslySetInnerHTML={{
                __html: decodeHTML(ticket.descriptionRich),
              }}
            />
          </div>
        )}
      </div>
    </>
  )
}
