import { Box, Typography, Button, useTheme, FormControl, FormLabel, RadioGroup, FormControlLabel, Radio, InputLabel } from "@mui/material";
import MenuItem from "@mui/material/MenuItem";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import { useState } from "react";
import { SERVICE_LIST, ServiceType } from "@root/model/tariff";
import { CustomTextField } from "@root/kitUI/CustomTextField";
import { usePrivilegeStore } from "@root/stores/privileges";
import { AnyDiscount } from "@root/model/cart";
import { nanoid } from "nanoid";
import { addDiscounts } from "@root/stores/discounts";
import { enqueueSnackbar } from "notistack";


const discountTypes = {
    "Лояльность": "purchasesAmount",
    "Корзина": "cartPurchasesAmount",
    "Сервис": "service",
    "Товар": "privilege",
} as const;
type DiscountType = keyof typeof discountTypes;

export default function CreateDiscount() {
    const theme = useTheme();
    const privileges = usePrivilegeStore(state => state.privileges);
    const [serviceType, setServiceType] = useState<ServiceType>("templategen");
    const [discountType, setDiscountType] = useState<DiscountType>("Лояльность");
    const [discountNameField, setDiscountNameField] = useState<string>("");
    const [discountDescription, setDiscountDescription] = useState<string>("");
    const [privilegeIdField, setPrivilegeIdField] = useState<string | "">("");
    const [discountFactorField, setDiscountFactorField] = useState<string>("0");
    const [purchasesAmountField, setPurchasesAmountField] = useState<string>("0");
    const [cartPurchasesAmountField, setCartPurchasesAmountField] = useState<string>("0");
    const [discountMinValueField, setDiscountMinValueField] = useState<string>("0");

    const handleDiscountTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setDiscountType(event.target.value as DiscountType);
    };

    const handleServiceTypeChange = (event: SelectChangeEvent) => {
        setServiceType(event.target.value as ServiceType);
    };

    function handleCreateDiscount() {
        const purchasesAmount = parseFloat(purchasesAmountField.replace(",", "."));
        const discountFactor = 1 - parseFloat(discountFactorField.replace(",", ".")) / 100;
        const cartPurchasesAmount = parseFloat(cartPurchasesAmountField.replace(",", "."));
        const discountMinValue = parseFloat(discountMinValueField.replace(",", "."));

        if (!isFinite(purchasesAmount)) return enqueueSnackbar("Поле purchasesAmount не число");
        if (!isFinite(discountFactor)) return enqueueSnackbar("Поле discountFactor не число");
        if (!isFinite(cartPurchasesAmount)) return enqueueSnackbar("Поле cartPurchasesAmount не число");
        if (!isFinite(discountMinValue)) return enqueueSnackbar("Поле discountMinValue не число");

        let discount: AnyDiscount;
        switch (discountType) {
            case "Лояльность": {
                discount = {
                    _id: nanoid(6),
                    name: discountNameField,
                    description: discountDescription,
                    disabled: false,
                    conditionType: "purchasesAmount",
                    condition: {
                        purchasesAmount: purchasesAmount,
                    },
                    factor: discountFactor,
                };
                break;
            }
            case "Корзина": {
                discount = {
                    _id: nanoid(6),
                    name: discountNameField,
                    description: discountDescription,
                    disabled: false,
                    conditionType: "cartPurchasesAmount",
                    condition: {
                        cartPurchasesAmount: cartPurchasesAmount,
                    },
                    factor: discountFactor,
                };
                break;
            }
            case "Сервис": {
                discount = {
                    _id: nanoid(6),
                    name: discountNameField,
                    description: discountDescription,
                    disabled: false,
                    conditionType: "service",
                    condition: {
                        service: {
                            id: serviceType,
                            value: discountMinValue,
                        },
                    },
                    target: {
                        service: serviceType,
                        factor: discountFactor,
                    },
                };
                break;
            }
            case "Товар": {
                discount = {
                    _id: nanoid(6),
                    name: discountNameField,
                    description: discountDescription,
                    disabled: false,
                    conditionType: "privilege",
                    condition: {
                        privilege: {
                            id: privilegeIdField,
                            value: discountMinValue,
                        },
                    },
                    target: {
                        products: [{
                            privilegeId: privilegeIdField,
                            factor: discountFactor,
                        }],
                    },
                };
                break;
            }
        }

        addDiscounts([discount]);
    }

    return (
        <Box sx={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "left",
            alignItems: "left",
            marginTop: "15px",
            width: "100%",
            padding: "16px",
            maxWidth: "600px",
            gap: "1em",
        }}>
            <CustomTextField
                id="discount-name"
                label="Название"
                value={discountNameField}
                onChange={e => setDiscountNameField(e.target.value)}
            />
            <CustomTextField
                id="discount-desc"
                label="Описание"
                value={discountDescription}
                onChange={e => setDiscountDescription(e.target.value)}
            />
            <Typography
                variant="h4"
                sx={{
                    width: "90%",
                    fontWeight: "normal",
                    color: theme.palette.grayDisabled.main,
                    paddingLeft: "10px",
                }}>
                Условия:
            </Typography>
            <CustomTextField
                id="discount-factor"
                label="Процент скидки"
                value={discountFactorField}
                type="number"
                onChange={e => setDiscountFactorField(e.target.value)}
            />
            <FormControl>
                <FormLabel
                    id="discount-type"
                    sx={{
                        color: "white",
                        "&.Mui-focused": {
                            color: "white",
                        },
                    }}
                >Тип скидки</FormLabel>
                <RadioGroup
                    row
                    aria-labelledby="discount-type"
                    name="discount-type"
                    value={discountType}
                    onChange={handleDiscountTypeChange}
                >
                    {Object.keys(discountTypes).map(type =>
                        <FormControlLabel key={type} value={type} control={<Radio color="secondary" />} label={type} />
                    )}
                </RadioGroup>
            </FormControl>
            {discountType === "Лояльность" &&
                <CustomTextField
                    id="discount-purchases"
                    label="Внесено больше"
                    type="number"
                    sx={{
                        marginTop: "15px"
                    }}
                    value={purchasesAmountField}
                    onChange={e => setPurchasesAmountField(e.target.value)}
                />
            }
            {discountType === "Корзина" &&
                <CustomTextField
                    id="discount-cart-purchases"
                    label="Объем в корзине"
                    type="number"
                    sx={{
                        marginTop: "15px"
                    }}
                    value={cartPurchasesAmountField}
                    onChange={e => setCartPurchasesAmountField(e.target.value)}
                />
            }
            {discountType === "Сервис" &&
                <>
                    <Select
                        labelId="discount-service-label"
                        id="discount-service"
                        value={serviceType}
                        onChange={handleServiceTypeChange}
                        sx={{
                            color: theme.palette.secondary.main,
                            borderColor: theme.palette.secondary.main,
                            "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                                borderColor: theme.palette.secondary.main
                            },
                            ".MuiSvgIcon-root ": {
                                fill: theme.palette.secondary.main,
                            }
                        }}
                    >
                        {SERVICE_LIST.map(service =>
                            <MenuItem key={service.serviceKey} value={service.serviceKey}>{service.displayName}</MenuItem>
                        )}
                    </Select>
                    <CustomTextField
                        id="discount-min-value"
                        label="Минимальное значение"
                        type="number"
                        sx={{
                            marginTop: "15px"
                        }}
                        value={discountMinValueField}
                        onChange={e => setDiscountMinValueField(e.target.value)}
                    />
                </>
            }
            {discountType === "Товар" &&
                <>
                    <FormControl
                        fullWidth
                        sx={{
                            color: theme.palette.secondary.main,
                            "& .MuiInputLabel-outlined": {
                                color: theme.palette.secondary.main,
                            },
                            "& .MuiInputLabel-outlined.MuiInputLabel-shrink": {
                                color: theme.palette.secondary.main,
                            }
                        }}
                    >
                        <InputLabel
                            id="privilege-select-label"
                            sx={{
                                color: theme.palette.secondary.main,
                                fontSize: "16px",
                                lineHeight: "19px",
                            }}
                        >Привелегия</InputLabel>
                        <Select
                            labelId="privilege-select-label"
                            id="privilege-select"
                            value={privilegeIdField}
                            label="Привелегия"
                            onChange={e => setPrivilegeIdField(e.target.value)}
                            sx={{
                                color: theme.palette.secondary.main,
                                borderColor: theme.palette.secondary.main,
                                "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
                                    borderColor: theme.palette.secondary.main,
                                },
                                ".MuiSvgIcon-root ": {
                                    fill: theme.palette.secondary.main,
                                }
                            }}
                            inputProps={{ sx: { pt: "12px" } }}
                        >
                            {privileges.map((privilege, index) => (
                                <MenuItem key={index} value={privilege.privilegeId}>
                                    {privilege.description}
                                </MenuItem>
                            ))}
                        </Select>
                    </FormControl>
                    <CustomTextField
                        id="discount-min-value"
                        label="Минимальное значение"
                        type="number"
                        sx={{
                            marginTop: "15px"
                        }}
                        value={discountMinValueField}
                        onChange={e => setDiscountMinValueField(e.target.value)}
                    />
                </>
            }
            <Box sx={{
                width: "90%",
                marginTop: "55px",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center"
            }}>
                <Button
                    variant="contained"
                    sx={{
                        backgroundColor: theme.palette.menu.main,
                        height: "52px",
                        fontWeight: "normal",
                        fontSize: "17px",
                        "&:hover": {
                            backgroundColor: theme.palette.grayMedium.main
                        }
                    }}
                    onClick={handleCreateDiscount}
                >Cоздать</Button>
            </Box>
        </Box >
    );
}