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 }: 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() }} />
    </>
}