import { Box, Button, Dialog, FormControl, FormControlLabel, FormLabel, InputLabel, MenuItem, Radio, RadioGroup, Select, SelectChangeEvent, Typography, useTheme } from "@mui/material";
import { createDiscount, patchDiscount } from "@root/api/discounts";
import { CustomTextField } from "@root/kitUI/CustomTextField";
import { DiscountType, discountTypes } from "@root/model/discount";
import { ServiceType, SERVICE_LIST } from "@root/model/tariff";
import { closeEditDiscountDialog, updateDiscount, useDiscountStore } from "@root/stores/discounts";
import { setRealPrivileges, useRealPrivilegeStore } from "@root/stores/privileges";
import { getDiscountTypeFromLayer } from "@root/utils/discount";
import usePrivileges from "@root/utils/hooks/usePrivileges";
import { enqueueSnackbar } from "notistack";
import { useEffect, useState } from "react";


export default function EditDiscountDialog() {
    const theme = useTheme();
    const editDiscountId = useDiscountStore(state => state.editDiscountId);
    const discounts = useDiscountStore(state => state.discounts);
    const privileges = useRealPrivilegeStore(state => state.privileges);
    const [serviceType, setServiceType] = useState<ServiceType>("templategen");
    const [discountType, setDiscountType] = useState<DiscountType>("purchasesAmount");
    const [discountNameField, setDiscountNameField] = useState<string>("");
    const [discountDescriptionField, setDiscountDescriptionField] = 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 discount = discounts.find(discount => discount.ID === editDiscountId);

    usePrivileges({ onNewPrivileges: setRealPrivileges });

    useEffect(function setDiscountFields() {
        if (!discount) return;

        setServiceType(discount.Condition.Group);
        setDiscountType(getDiscountTypeFromLayer(discount.Layer));
        setDiscountNameField(discount.Name);
        setDiscountDescriptionField(discount.Description);
        setPrivilegeIdField(discount.Condition.Product);
        setDiscountFactorField(discount.Target.Factor.toString());
        setPurchasesAmountField(discount.Condition.PurchasesAmount.toString());
        setCartPurchasesAmountField(discount.Condition.CartPurchasesAmount.toString());
        setDiscountMinValueField(discount.Condition.PriceFrom.toString());
    }, [discount]);

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

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

    async function handleSaveDiscount() {
        if (!discount) return;

        const purchasesAmount = parseFloat(purchasesAmountField.replace(",", "."));
        const discountFactor = (100 - 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 не число");
        if (discountType === "privilege" && !privilegeIdField) return enqueueSnackbar("Привилегия не выбрана");
        if (!discountNameField) return enqueueSnackbar("Поле \"Имя\" пустое");
        if (!discountDescriptionField) return enqueueSnackbar("Поле \"Описание\" пустое");
        if (discountFactor < 0) return enqueueSnackbar("Процент скидки не может быть больше 100");

        try {
            const createdDiscount = await patchDiscount(discount.ID, {
                cartPurchasesAmount,
                discountFactor,
                discountMinValue,
                purchasesAmount,
                discountDescription: discountDescriptionField,
                discountName: discountNameField,
                startDate: new Date().toISOString(),
                endDate: new Date(Date.now() + 1000 * 3600 * 24 * 30).toISOString(),
                serviceType,
                discountType,
                privilegeId: privilegeIdField,
            });

            updateDiscount(createdDiscount);
            closeEditDiscountDialog();
        } catch (error) {
            console.log("Error patching discount", error);
            enqueueSnackbar("Ошибка при обновлении скидки");
        }
    }

    return (
        <Dialog
            open={editDiscountId !== null}
            onClose={closeEditDiscountDialog}
            PaperProps={{
                sx: {
                    width: "600px",
                    maxWidth: "600px",
                    backgroundColor: theme.palette.grayMedium.main,
                    position: "relative",
                    display: "flex",
                    flexDirection: "column",
                    p: "20px",
                    gap: "20px",
                    borderRadius: "12px",
                    boxShadow: "none",
                }
            }}
            slotProps={{ backdrop: { style: { backgroundColor: "rgb(0 0 0 / 0.7)" } } }}
        >
            <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={discountDescriptionField}
                    onChange={e => setDiscountDescriptionField(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={discountTypes[type as DiscountType]}
                                sx={{ color: "white" }}
                            />
                        )}
                    </RadioGroup>
                </FormControl>
                {discountType === "purchasesAmount" &&
                    <CustomTextField
                        id="discount-purchases"
                        label="Внесено больше"
                        type="number"
                        sx={{
                            marginTop: "15px"
                        }}
                        value={purchasesAmountField}
                        onChange={e => setPurchasesAmountField(e.target.value)}
                    />
                }
                {discountType === "cartPurchasesAmount" &&
                    <CustomTextField
                        id="discount-cart-purchases"
                        label="Объем в корзине"
                        type="number"
                        sx={{
                            marginTop: "15px"
                        }}
                        value={cartPurchasesAmountField}
                        onChange={e => setCartPurchasesAmountField(e.target.value)}
                    />
                }
                {discountType === "service" &&
                    <>
                        <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 === "privilege" &&
                    <>
                        <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={handleSaveDiscount}
                    >Сохранить</Button>
                </Box>
            </Box>
        </Dialog>
    );
}