import React, { FC, useState } from 'react'
import { Order, OrderItem } from '../model/models'
import bringTruck from '../../../assets/img/bring-truck.png'

export declare interface AlreadyBookedListProps {
  orders: Array<Order>
  startIndex: number
  mapServiceId: (shippingOption: string | undefined) => string | undefined | React.ReactNode
}

const BookedOrders: FC<AlreadyBookedListProps> = ({
  orders,
  startIndex,
  mapServiceId,
}) => {
  const [visibleOrderIds, setVisibleOrderIds] = useState<string[]>([])

  const toggleOrderDetails = (orderId: string) => {
    setVisibleOrderIds(prevState =>
      prevState.includes(orderId)
        ? prevState.filter(id => id !== orderId)
        : [...prevState, orderId]
    )
  }

  return orders.map((order, index) => (
    <React.Fragment key={order.order_id}>
      <tr
        className={`order-row ${
          (startIndex + index) % 2 === 0 ? 'even' : 'odd'
        }`}
      >
        <td>
          {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
          <a
            href="#"
            onClick={e => {
              e.preventDefault()
              toggleOrderDetails(order.order_id)
            }}
          >
            #{order.order_id}
          </a>
        </td>
        <td className={'order-list-shipping-options'}>
          {mapServiceId(order.order_shipping_option)}
        </td>
        <td className={'order-list-weight'}></td>
        <td className="action-cell">
          <div className="flex align-ic gas flex-dir-row flex-nowrap">
            <div className="result-container">
              <span className="success">OK</span>
            </div>
            <div className="truck-container flex flex-dir-col justify-cc">
              <img className="bring-truck-icon" src={bringTruck} alt="" />
            </div>
          </div>
        </td>
      </tr>
      <tr
        className={`order-row ${index % 2 === 0 ? 'even' : 'odd'}`}
        style={{
          display: `${
            visibleOrderIds.includes(order.order_id) ? 'table-row' : 'none'
          }`,
        }}
      >
        <td colSpan={4}>
          {order.recipientName}
          <br />
          {order.recipientAddressLine}
          <br />
          {order.recipientPostalCode} {order.recipientCity}
          <br />
          <ul>
            {order.items &&
              order.items.map((item: OrderItem, orderIndex: number) => (
                <li key={orderIndex}>
                  <i>{item.name}</i> x {item.quantity}
                </li>
              ))}
          </ul>
        </td>
      </tr>
    </React.Fragment>
  ))
}

export default BookedOrders
