import theme from "@theme";
import { Button, Paper, Box, Typography, TableHead, TableRow, TableCell, TableBody, Table, Tooltip } from "@mui/material";
import Input from "@kitUI/input";
import { useCartStore } from "@root/stores/cart";
import { useState } from "react";
import { GridSelectionModel } from "@mui/x-data-grid";
import { testUser } from "@root/stores/mocks/user";
import { useDiscountStore } from "@root/stores/discounts";
import { calcCartData, createCartItem, findDiscountById, findDiscountFactorById, formatDiscountFactor } from "./calc";
import { useTariffStore } from "@root/stores/tariffs";
import { AnyDiscount, CartItemTotal } from "@root/model/cart";

interface Props {
    selectedTariffs: GridSelectionModel;
}

export default function Cart({ selectedTariffs }: Props) {
    const tariffs = useTariffStore(store => store.tariffs);
    const discounts = useDiscountStore(store => store.discounts);
    const cartTotal = useCartStore(state => state.cartTotal);
    const setCartTotal = useCartStore(store => store.setCartTotal);
    const [couponField, setCouponField] = useState<string>("");
    // const [coupon, setCoupon] = useState<string | undefined>();

    const cartRows = cartTotal?.items.map(cartItemTotal => {
        const envolvedDiscountsElement = (
            <Box>
                {cartItemTotal.envolvedDiscounts.map(discountId => (
                    <DiscountTooltip
                        key={discountId}
                        discounts={discounts}
                        discountId={discountId}
                        cartItemTotal={cartItemTotal}
                    />
                ))}
            </Box>
        );

        return {
            id: cartItemTotal.tariff.id,
            tariffName: cartItemTotal.tariff.name,
            privilegeDesc: cartItemTotal.tariff.privilege.description,
            envolvedDiscounts: envolvedDiscountsElement,
            price: cartItemTotal.totalPrice,
        };
    });

    const envolvedCartDiscountsElement = (
        <Box sx={{
            display: "inline-flex",
            flexWrap: "wrap",
        }}>
            {cartTotal?.envolvedCartDiscounts.map((discountId, index, arr) => (
                <span key={discountId}>
                    <DiscountTooltip
                        discounts={discounts}
                        discountId={discountId}
                    />
                    {index < arr.length - 1 &&
                        <span>,&nbsp;</span>
                    }
                </span>
            ))}
        </Box>
    );

    function handleCalcCartClick() {
        const cartTariffs = tariffs.filter(tariff => selectedTariffs.includes(tariff.id));
        const cartItems = cartTariffs.map(tariff => createCartItem(tariff));
        setCartTotal(calcCartData(testUser, cartItems, discounts, couponField));
    }

    return (
        <Box
            component="section"
            sx={{
                border: "1px solid white",
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
                width: "100%"
            }}
        >
            <Typography variant="caption">
                корзина
            </Typography>
            <Paper
                variant="bar"
                sx={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}
            >
                <Box
                    sx={{
                        border: "1px solid white",
                        padding: "3px",
                        display: "flex",
                        flexDirection: "column"
                    }}
                >
                    <Input
                        label="промокод"
                        size="small"
                        value={couponField}
                        onChange={e => setCouponField(e.target.value)}
                        InputProps={{
                            style: {
                                backgroundColor: theme.palette.content.main,
                                color: theme.palette.secondary.main,
                            }
                        }}
                        InputLabelProps={{
                            style: {
                                color: theme.palette.secondary.main
                            }
                        }}
                    />
                    {/* <Button
                        sx={{ maxWidth: "140px" }}
                        onClick={() => setCoupon(couponField)}
                    >применить промокод</Button> */}
                </Box>
                <Button onClick={handleCalcCartClick}>рассчитать</Button>
            </Paper>

            <Table sx={{
                width: "90%",
                margin: "5px",
                border: "2px solid",
                borderColor: theme.palette.secondary.main,
            }} aria-label="simple table">
                <TableHead>
                    <TableRow sx={{
                        borderBottom: "2px solid",
                        borderColor: theme.palette.grayLight.main,
                        height: "100px"
                    }}>
                        <TableCell>
                            <Typography
                                variant="h4"
                                sx={{ color: theme.palette.secondary.main }}
                            >Имя</Typography>
                        </TableCell>
                        <TableCell>
                            <Typography
                                variant="h4"
                                sx={{ color: theme.palette.secondary.main }}
                            >Описание</Typography>
                        </TableCell>
                        <TableCell>
                            <Typography
                                variant="h4"
                                sx={{ color: theme.palette.secondary.main }}
                            >Скидки</Typography>
                        </TableCell>
                        <TableCell>
                            <Typography
                                variant="h4"
                                sx={{ color: theme.palette.secondary.main }}
                            >стоимость</Typography>
                        </TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {cartRows?.map(row => (
                        <TableRow
                            key={row.id}
                            sx={{
                                borderBottom: "2px solid",
                                borderColor: theme.palette.grayLight.main,
                            }}
                        >
                            <TableCell sx={{
                                color: theme.palette.secondary.main,
                            }}>{row.tariffName}</TableCell>
                            <TableCell sx={{
                                color: theme.palette.secondary.main,
                            }}>{row.privilegeDesc}</TableCell>
                            <TableCell sx={{
                                color: theme.palette.secondary.main,
                            }}>{row.envolvedDiscounts}</TableCell>
                            <TableCell sx={{
                                color: theme.palette.secondary.main,
                            }}>{row.price.toFixed(2)} ₽</TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>

            <Typography id="transition-modal-title" variant="h6" sx={{
                fontWeight: "normal",
                textAlign: "center",
                marginTop: "15px",
                fontSize: "16px"
            }}>
                Скидки корзины: {envolvedCartDiscountsElement}
            </Typography>

            <Typography id="transition-modal-title" variant="h6" sx={{
                fontWeight: "normal",
                textAlign: "center",
                marginTop: "10px"
            }}>
                ИТОГО: <span>{cartTotal?.totalPrice.toFixed(2)} ₽</span>
            </Typography>

        </Box>
    );
}

function DiscountTooltip({ discounts, discountId, cartItemTotal }: {
    discounts: AnyDiscount[];
    discountId: string;
    cartItemTotal?: CartItemTotal;
}) {
    const discount = findDiscountById(discounts, discountId);
    const discountText = formatDiscountFactor(findDiscountFactorById(discounts, discountId, cartItemTotal?.tariff.privilege.privilegeId));

    return (
        <Tooltip title={
            <>
                <Typography>Скидка: {discount?.name}</Typography>
                <Typography>{discount?.description}</Typography>
                <Typography>-------</Typography>
                <Typography>layer: {discount?.layer}</Typography>
                <Typography>id: {discount?._id}</Typography>
            </>
        }>
            <span>{discountText}</span>
        </Tooltip>
    );
}