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 PizzaAdditionalFeeModal from "./modals/PizzaAdditionalFeeModal";
import { PizzaDayState, PizzaOrder, PizzaVariant } from "../../../types";

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

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

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

    return <>
        <td>{order.customer}</td>
        <td>{order.pizzaList!.map<React.ReactNode>(pizzaOrder =>
            <span key={pizzaOrder.name}>
                {`${pizzaOrder.name}, ${pizzaOrder.size} (${pizzaOrder.price} Kč)`}
                {auth?.login === order.customer && state === PizzaDayState.CREATED &&
                    <span title='Odstranit'>
                        <FontAwesomeIcon onClick={() => {
                            onDelete(pizzaOrder);
                        }} className='action-icon' icon={faTrashCan} />
                    </span>
                }
            </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 && <span title='Nastavit příplatek'><FontAwesomeIcon onClick={() => { setIsFeeModalOpen(true) }} className='action-icon' icon={faMoneyBill1} /></span>}
        </td>
        <PizzaAdditionalFeeModal customerName={order.customer} isOpen={isFeeModalOpen} onClose={() => setIsFeeModalOpen(false)} onSave={saveFees} initialValues={{ text: order.fee?.text, price: order.fee?.price?.toString() }} />
    </>
}