import { useEffect, useState } from "react";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Modal from "@mui/material/Modal";
import TextField from "@mui/material/TextField";
import { enqueueSnackbar } from "notistack";
import { devlog, getMessageFromFetchError } from "@frontend/kitui";
import { closeEditTariffDialog, useTariffStore } from "@root/stores/tariffs";
import { putTariff } from "@root/api/tariffs";
import { requestTariffs } from "@root/services/tariffs.service";


export default function EditModal() {
    const [nameField, setNameField] = useState("");
    const [priceField, setPriceField] = useState("");
    const tariffs = useTariffStore((state) => state.tariffs);
    const editTariffId = useTariffStore(state => state.editTariffId);

    const tariff = tariffs.find(tariff => tariff._id === editTariffId);

    useEffect(function setCurrentTariffFields() {
        if (!tariff) return;

        setNameField(tariff.name);
        setPriceField((tariff.price || 0).toString());
    }, [tariff]);

    async function handleEditClick() {
        if (!tariff) return enqueueSnackbar(`Тариф ${editTariffId} не найден`);

        const price = parseFloat(priceField);

        if (!isFinite(price)) return enqueueSnackbar("Поле \"Цена за единицу\" не число");
        if (!nameField) return enqueueSnackbar("Поле \"Имя\" пустое");

        const updatedTariff = structuredClone(tariff);
        updatedTariff.name = nameField;
        updatedTariff.price = price;
        try {
            await putTariff(updatedTariff);
            closeEditTariffDialog();
            
            requestTariffs();
        } catch (error) {
            devlog("Error updating tariff", error);
            const message = getMessageFromFetchError(error);
            if (message) enqueueSnackbar(message);
        }
    }

    return (
        <Modal
            open={editTariffId !== null}
            onClose={closeEditTariffDialog}
            aria-labelledby="modal-modal-title"
            aria-describedby="modal-modal-description"
        >
            <Box
                sx={{
                    position: "absolute",
                    top: "50%",
                    left: "50%",
                    transform: "translate(-50%, -50%)",
                    width: 400,
                    bgcolor: "background.paper",
                    border: "2px solid gray",
                    borderRadius: "6px",
                    boxShadow: 24,
                    p: 4,
                }}
            >
                <Typography
                    id="modal-modal-title"
                    variant="h6"
                    component="h2"
                    sx={{ whiteSpace: "nowrap" }}
                >
                    Редактирование тариффа
                </Typography>

                {tariff && (
                    <Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
                        <Typography>Название Тарифа: {tariff.name}</Typography>
                        <TextField
                            onChange={(event) => setNameField(event.target.value)}
                            label="Имя"
                            name="name"
                            value={nameField}
                            sx={{ marginBottom: "10px" }}
                        />
                        <Typography>
                            Цена за единицу: {tariff.privilegies[0].price}
                        </Typography>
                        <TextField
                            type="number"
                            onChange={(event) => setPriceField(event.target.value)}
                            label="Цена за единицу"
                            name="price"
                            value={priceField}
                            sx={{ marginBottom: "10px" }}
                        />
                        <Button
                            onClick={handleEditClick}
                        >
                            Редактировать
                        </Button>
                    </Box>
                )}
            </Box>
        </Modal>
    );
}
