import { useState } from "react";
import { Typography, Container, Button, Select, MenuItem, FormControl, InputLabel, useTheme, Box } from "@mui/material";
import { nanoid } from "nanoid";
import { enqueueSnackbar } from "notistack";
import axios from "axios";

import { CustomTextField } from "@root/kitUI/CustomTextField";

import { useCombinedPrivileges } from "@root/hooks/useCombinedPrivileges.hook";

import { Tariff } from "@root/model/tariff";

import { addTariffs } from "@root/stores/tariffs";
import { authStore } from "@root/stores/auth";

export default function CreateTariff() {
  const theme = useTheme();
  const [nameField, setNameField] = useState<string>("");
  const [amountField, setAmountField] = useState<string>("");
  const [customPriceField, setCustomPriceField] = useState<string>("");
  const [privilegeIdField, setPrivilegeIdField] = useState<string>("");
  const { mergedPrivileges, isError, errorMessage } = useCombinedPrivileges();
  const { token } = authStore();

  const findPrivilegeById = (privilegeId: string) => {
    return mergedPrivileges.find((privilege) => privilege.privilegeId === privilegeId) ?? null;
  };

  const privilege = findPrivilegeById(privilegeIdField);

  console.log(privilege);

  function handleCreateTariffClick() {
    if (nameField === "") {
      enqueueSnackbar("Пустое название тарифа");
    }
    if (amountField === "") {
      enqueueSnackbar("Пустое кол-во едениц привилегия");
    }
    if (privilegeIdField === "") {
      enqueueSnackbar("Невыбрана привилегия");
    }

    const amount = Number(amountField);
    const customPrice = Number(customPriceField);

    if (isNaN(amount) || !privilege) return;

    const newTariff: Tariff = {
      id: nanoid(5),
      name: nameField,
      amount,

      privilegeId: privilege.privilegeId,
      customPricePerUnit: customPrice ? customPrice / amount : undefined,
    };

    addTariffs([newTariff]);

    axios({})
      .then((response) => {
        console.log(response.data);
      })
      .catch((error) => {
        console.error(error);
      });
  }

  const createTariff = async () => {
    try {
      if (!privilege) {
        throw new Error("Привилегия не выбрана");
      }

      const { data } = await axios({
        url: "https://admin.pena.digital/strator/tariff/",
        method: "post",
        headers: {
          Authorization: `Bearer ${token}`,
        },
        data: {
          name: nameField,
          price: Number(customPriceField) * 100,
          isCustom: false,
          privilegies: [
            {
              name: privilege.name,
              privilegeId: privilege.privilegeId,
              serviceKey: privilege.serviceKey,
              description: privilege.description,
              type: privilege.type,
              value: privilege.value,
              price: privilege.price,
              amount: amountField,
            },
          ],
        },
      });
    } catch (error) {
      enqueueSnackbar((error as Error).message);
    }
  };

  return (
    <Container
      sx={{
        p: "20px",
        border: "1px solid rgba(224, 224, 224, 1)",
        borderRadius: "4px",
        display: "flex",
        flexDirection: "column",
        gap: "12px",
      }}
    >
      <Typography variant="h6" sx={{ textAlign: "center", mb: "16px" }}>
        Создание тарифа
      </Typography>
      <FormControl
        fullWidth
        sx={{
          height: "52px",
          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>
        {isError ? (
          <Typography>{errorMessage}</Typography>
        ) : (
          <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,
                border: "1px solid",
              },
              ".MuiSvgIcon-root ": {
                fill: theme.palette.secondary.main,
              },
            }}
            inputProps={{ sx: { pt: "12px" } }}
          >
            {mergedPrivileges.map((privilege) => (
              <MenuItem key={privilege.description} value={privilege.privilegeId}>
                {privilege.description}
              </MenuItem>
            ))}
          </Select>
        )}
      </FormControl>
      {privilege && (
        <Box
          sx={{
            display: "flex",
            flexDirection: "column",
          }}
        >
          <Typography>
            Имя: <span>{privilege.name}</span>
          </Typography>
          <Typography>
            Сервис: <span>{privilege.serviceKey}</span>
          </Typography>
          <Typography>
            Единица: <span>{privilege.type}</span>
          </Typography>
          <Typography>
            Стандартная цена за единицу: <span>{privilege.price}</span>
          </Typography>
        </Box>
      )}
      <CustomTextField
        id="tariff-name"
        label="Название тарифа"
        value={nameField}
        onChange={(e) => setNameField(e.target.value)}
      />
      <CustomTextField
        id="tariff-amount"
        label="Кол-во единиц привилегии"
        value={amountField}
        onChange={(e) => setAmountField(e.target.value)}
        type="number"
      />
      <CustomTextField
        id="tariff-custom-price"
        label="Кастомная цена (не обязательно)"
        value={customPriceField}
        onChange={(e) => setCustomPriceField(e.target.value)}
        type="number"
      />
      <Button
        onClick={() => {
          handleCreateTariffClick();
          createTariff();
        }}
        // disabled={privilegeIdField === "" || amountField === "" || nameField === ""}
      >
        Создать
      </Button>
    </Container>
  );
}
