import React, { useState } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faMoneyBill1, faTrashCan } from "@fortawesome/free-regular-svg-icons";
import { useAuth } from "../context/auth";
import { Order, PizzaDayState, PizzaOrder } from "../types";
import PizzaAdditionalFeeModal from "./modals/PizzaAdditionalFeeModal";

type Props = {
    creator: string,
    order: Order,
    state: PizzaDayState,
    onDelete: (order: PizzaOrder) => void,
    onFeeModalSave: (customer: string, name?: string, price?: number) => void,
}

export default function PizzaOrderRow({ creator, order, state, onDelete, onFeeModalSave }: Props) {
    const auth = useAuth();
    const [isFeeModalOpen, setFeeModalOpen] = useState<boolean>(false);

    const saveFees = (customer: string, text?: string, price?: number) => {
        onFeeModalSave(customer, text, price);
        setFeeModalOpen(false);
    }

    return <>
        <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 === PizzaDayState.CREATED &&
                    <FontAwesomeIcon onClick={() => {
                        onDelete(pizzaOrder);
                    }} title='Odstranit' className='action-icon' icon={faTrashCan} />
                }
            </span>)
            .reduce((prev, curr, index) => [prev, <br key={`br-${index}`} />, curr])}
        </td>
        <td style={{ maxWidth: "200px" }}>{order.note || '-'}</td>
        <td style={{ maxWidth: "200px" }}>{order.fee?.price ? `${order.fee.price} Kč${order.fee.text ? ` (${order.fee.text})` : ''}` : '-'}</td>
        <td>
            {order.totalPrice} Kč{auth?.login === creator && state === PizzaDayState.CREATED && <FontAwesomeIcon onClick={() => { setFeeModalOpen(true) }} title='Nastavit příplatek' className='action-icon' icon={faMoneyBill1} />}
        </td>
        <PizzaAdditionalFeeModal customerName={order.customer} isOpen={isFeeModalOpen} onClose={() => setFeeModalOpen(false)} onSave={saveFees} initialValues={{ text: order.fee?.text, price: order.fee?.price?.toString() }} />
    </>
}