import React from "react";
import { Table } from "react-bootstrap";
import { Order, PizzaOrder, State } from "../Types";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrashCan } from "@fortawesome/free-regular-svg-icons";
import { useAuth } from "../context/auth";

export default function PizzaOrderList({ state, orders, onDelete }: { state: State, orders: Order[], onDelete: (pizzaOrder: PizzaOrder) => void }) {
    const auth = useAuth();

    if (!orders?.length) {
        return <p className="mt-3"><i>Zatím žádné objednávky...</i></p>
    }

    const total = orders.map(order => order.pizzaList.map(o => o.price).reduce((total, i) => total + i)).reduce((total, i) => total + i);

    return <Table className="mt-3" striped bordered hover>
        <thead>
            <tr>
                <th>Jméno</th>
                <th>Objednávka</th>
                <th>Poznámka</th>
                <th>Cena</th>
            </tr>
        </thead>
        <tbody>
            {orders.map(order => <tr key={order.customer}>
                <td>{order.customer}</td>
                <td>{order.pizzaList.map<React.ReactNode>((pizzaOrder, index) =>
                    <span key={index}>
                        {`${pizzaOrder.name}, ${pizzaOrder.size} (${pizzaOrder.price} Kč)`}
                        {auth?.login === order.customer && state === State.CREATED &&
                            <FontAwesomeIcon onClick={() => {
                                onDelete(pizzaOrder);
                            }} title='Odstranit' className='trash-icon' icon={faTrashCan} />
                        }
                    </span>)
                    .reduce((prev, curr, index) => [prev, <br key={`br-${index}`} />, curr])}
                </td>
                <td>{order.note || '-'}</td>
                <td>{order.totalPrice} Kč</td>
            </tr>)}
            <tr style={{ fontWeight: 'bold' }}>
                <td colSpan={3}>Celkem</td>
                <td>{`${total} Kč`}</td>
            </tr>
        </tbody>
    </Table>
}