/* eslint-disable @typescript-eslint/no-explicit-any */
import _identity from 'lodash/identity'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import React, { memo, useState } from 'react'

import { FEES_STYLES } from '../../constants'
import { createFixedFloatNormalizer, currencyNormalizerCreator } from '../../normalizers'
import { IOrderData } from '../../types'
import { CONFIGS } from '../../utils'
import Countdown from 'react-countdown'
import { showZero } from '../../utils/showZero'
import { IRenderer } from '../timerWidget'

interface OrderDetailsProps {
  orderData: any;
  paymentFieldsData: any[];
  customMobileText?: string;
  handleCountdownFinish?: () => void;
}

interface CountdownI {
  expiresAt: number;
  handleCountdownFinish: () => void;
}

const SimpleCountdown = memo(({ expiresAt, handleCountdownFinish }: CountdownI) => {
  const renderer = ({
                      minutes,
                      seconds,
                      completed,
                      handleCountdownFinish,
                    }: IRenderer) => {
    if (completed) {
      handleCountdownFinish()
      return null
    }
    return (
      <span>
        {showZero(minutes)}:{showZero(seconds)}
      </span>
    )
  }

  return (<div className="mobile-order-timer">
    {expiresAt && (
      <Countdown
        date={Date.now() + expiresAt * 1000}
        renderer={(props: any) =>
          renderer({
            ...props,
            handleCountdownFinish,
          })
        }
      />
    )}
  </div>)
})

export const OrderDetails = ({
  orderData = {},
  paymentFieldsData = [],
  customMobileText = 'Your order total',
  handleCountdownFinish = _identity
}: OrderDetailsProps) => {
  const { currency, guest_count } = orderData || {}
  const hasTableTypes = Boolean(Number(guest_count))
  const [isExpanded, setIsExpanded] = useState(false)

  // Find the total field to display in the mobile view
  const totalField = paymentFieldsData.find(field => field.id === 'total')
  const totalValue =
    totalField && orderData.total
      ? totalField.normalizer
        ? totalField.normalizer(orderData.total, currency, orderData)
        : orderData.total
      : ''

  const toggleExpand = () => {
    setIsExpanded(!isExpanded)
  }

  const defaultItemRenderer = (item: any) => {
    return (<div>
      <div key={item.id} className="add-on-container">
        <span>{item.quantity}</span>
        <span className="add-on-x">{' x '}</span>
        <span>{item.groupName ? item.groupName + ' - ' : ''}</span>
        <span>{item.name}</span>
        <span>{' - '}</span>
        <span>
          {CONFIGS.FEES_STYLE === FEES_STYLES.TRADITIONAL &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.price)),
              currency,
            ) + ' (incl. fees)'}
          {CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.cost)),
              currency,
            )}
          {CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.price)),
              currency,
            )}
                            </span>
        <span className="add-on-each">{' each'}</span>
      </div>
      {CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH && (
        <p className="fees">
          {`(${currencyNormalizerCreator(
            createFixedFloatNormalizer(2)(
              parseFloat(String(item.price)),
            ),
            currency,
          )} with fees)`}
        </p>
      )}
      {CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN && parseFloat(item.price) - parseFloat(item.cost) > 0 && (
        <p className="fees">
          {`(${currencyNormalizerCreator(createFixedFloatNormalizer(2)(parseFloat(item.cost)), currency)} + ${currencyNormalizerCreator(createFixedFloatNormalizer(2)(parseFloat(item.price) - parseFloat(item.cost)), currency)} fee)`}
        </p>
      )}
    </div>)
  }

  const defaultTableRenderer = (item: any) => {
    return (<div>
      <div key={item.id} className="table-type-container">
        <span>{item.groupName ? item.groupName + ' - ' : ''}</span>
        <span>{item.name}</span>
        <span>{' - '}</span>
        <span>Guest Count{': '}</span>
        <span>{item.guestCount}</span>
      </div>
      <div>
        <span>
          {CONFIGS.FEES_STYLE === FEES_STYLES.TRADITIONAL &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.price)),
              currency,
            ) + ' (incl. fees)'}
          {CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.cost)),
              currency,
            )}
          {CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN &&
            currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(parseFloat(item.price)),
              currency,
            )}
        </span>
        <br/>
        {CONFIGS.FEES_STYLE === FEES_STYLES.DISPLAY_BOTH && (
          <p className="fees">
            {`(${currencyNormalizerCreator(
              createFixedFloatNormalizer(2)(
                parseFloat(String(item.price)),
              ),
              currency,
            )} with fees)`}
          </p>
        )}
        {CONFIGS.FEES_STYLE === FEES_STYLES.FINAL_WITH_BREAKDOWN && parseFloat(item.price) - parseFloat(item.cost) > 0 && (
          <p className="fees">
            {`(${currencyNormalizerCreator(createFixedFloatNormalizer(2)(parseFloat(item.cost)), currency)} + ${currencyNormalizerCreator(createFixedFloatNormalizer(2)(parseFloat(item.price) - parseFloat(item.cost)), currency)} fee)`}
          </p>
        )}
      </div>
    </div>)
  }

  return (
    <div className="payment_page payment_page_single">
      {/* Mobile view summary */}
      <div className="mobile-order-summary">
        <div className="mobile-order-summary-content" onClick={toggleExpand}>
          <div className="mobile-order-info">
            <div
              className={`mobile-order-info-container order-info-container-left ${
                isExpanded ? 'open' : ''
              }`}
            >
              <div className="mobile-order-text">{customMobileText}</div>
            </div>
            <div className="mobile-order-info-container order-info-container-right">
              {!isExpanded && (
                <div className="mobile-order-total">{totalValue}</div>
              )}
              {orderData?.expires_at && (
                <SimpleCountdown expiresAt={orderData?.expires_at} handleCountdownFinish={handleCountdownFinish} />
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Original content - will be hidden on mobile when collapsed */}
      <div
        className={`order_info_section ${isExpanded ? 'expanded' : 'collapsed'}`}
        style={{ display: hasTableTypes ? 'block' : 'grid' }}
      >
        {_map(paymentFieldsData, field => {
          const { id, label, className = '', normalizer = _identity } = field
          const value = orderData[id as keyof IOrderData] || ''
          let component = null

          if (field.id === 'add_ons' && _isEmpty(value)) {
            return false
          }

          if (field.id === 'tableTypes') {
            const valueArray = value as Array<any>

            component = (
              <div
                key={id}
                className="order_info_block"
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                }}
              >
                {_map(valueArray, tableTypeItem => (
                  <div
                    key={tableTypeItem.id}
                    style={{
                      display: 'grid',
                      gridTemplateColumns: '33% 33% 33%',
                      gridColumnGap: '10%',
                    }}
                  >
                    <div className="order_info_block">
                      <div className="order_info_title">Table Type</div>
                      <div className={`${className} order_info_text`}>
                        {tableTypeItem.ticketType}
                      </div>
                    </div>
                    <div className="order_info_block">
                      <div className="order_info_title">Number of Tables</div>
                      <div className={`${className} order_info_text`}>
                        {tableTypeItem.count}
                      </div>
                    </div>
                    <div className="order_info_block">
                      <div className="order_info_title">Guest Count</div>
                      <div className={`${className} order_info_text`}>
                        {tableTypeItem.quantity}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )
          }

          return (
            component || (
              <div key={id} className={`order_info_block ${className}`}>
                <div className="order_info_title">{label}</div>
                <div className={`${className} order_info_text`}>
                  {typeof value === 'string' || typeof value === 'number'
                    ? normalizer(value, currency, orderData)
                    : _map(value, item => (
                      item.isTable ? defaultTableRenderer(item) : defaultItemRenderer(item)
                    ))}
                </div>
              </div>
            )
          )
        })}
      </div>
    </div>
  )
}
