// @ts-nocheck
import React, { 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 axios from "axios";
import { authStore } from "@root/stores/auth";
import { Privilege, Tariff } from "@root/model/tariff";
import { findPrivilegeById } from "@root/stores/privilegesStore";
import { useTariffStore, updateTariff } from "@root/stores/tariffsStore";
import { arrayBuffer } from "stream/consumers";


interface EditProps {
  tarifIid: string,
  tariffName: string,
  tariffPrice: number,
  privilege: Privilege,
  token: string
}


const editTariff = ({
  tarifIid,
  tariffName,
  tariffPrice,
  privilege,
  token
}:EditProps): Promise<unknown> => {
  return axios({
    method: "put",
    url: `https://admin.pena.digital/strator/tariff/${tarifIid}`,
    headers: {
      Authorization: `Bearer ${token}`,
    },
    data: {
      name: tariffName,
      price: tariffPrice,
      isCustom: true,
      privilegies: [privilege]
    },
  });
}
interface Props {
  tariff: Tariff,
  getTariffs: () => void
}

/** @deprecated */
export default function EditModal({tariff, getTariffs}:Props) {
  
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [price, setPrice] = useState("");
  const { token } = authStore();
  const tariffs = useTariffStore((state) => state.tariffs);
  
  useEffect(() => {
    setOpen(tariff !== undefined)
  }, [tariff])
  console.log(tariff)
   if (tariff?.privilege[0].privilegeId !== undefined) console.log(findPrivilegeById(tariff?.privilege[0].privilegeId))

  return <Modal
        open={open}
        onClose={() => setOpen(false)}
        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 !== undefined && (
            <Box sx={{ mt: "20px", display: "flex", flexDirection: "column" }}>
              <Typography>Название Тарифа: {tariff.name}</Typography>
              <TextField
                onChange={(event) => setName(event.target.value)}
                label="Имя"
                name="name"
                value={name}
                sx={{ marginBottom: "10px" }}
              />
              <Typography>Цена за единицу: {tariff.pricePerUnit}</Typography>
              <TextField
                onChange={(event) => setPrice(event.target.value)}
                label="Цена за единицу"
                name="price"
                value={price}
                sx={{ marginBottom: "10px" }}
              />
              <Button onClick={() => {
                if (tariff.privilege.length) {
                  let privelege = tariff.privilege[0]
                  
                  mergedPrivileges.forEach((p:any) => {
                    if (privelege.privilegeId == p.privilegeId) tariff.privilege[0].privilegeId = p._id
                  })

              //back
                  editTariff({
                    tarifIid: tariff.id,
                    tariffName: name ? name : tariff.name,
                    tariffPrice: price ? Number(price) : tariff.privilege[0].price,
                    privilege: privelege,
                    token: token
                  })
                  .then(() => {
                    setOpen(false)
                    getTariffs()
                  })
                } else {//front/store

                  let array = tariffs
                  let index
                  tariffs.forEach((p:any, i:number) => {
                    if (tariff.id == p.id) index = i
                  })
                  if (index !== undefined) {
                    array[index].name = name
                    array[index].amount = Number(price)
                    updateTariffs(array)
                    setOpen(false)
                  } else {
                    console.log("не нашел такой тариф в сторе")
                  }
                  
                }
              }}>Редактировать</Button>
            </Box>
          )}
        </Box>
      </Modal>      

}
