import { KeyboardEvent, useRef, useState } from "react";
import { enqueueSnackbar } from "notistack";
import {Box, IconButton, TextField, Tooltip, Typography, useMediaQuery, useTheme} from "@mui/material";
import ModeEditOutlineOutlinedIcon from "@mui/icons-material/ModeEditOutlineOutlined";
import { PrivilegeWithAmount } from "@frontend/kitui";
import { putPrivilege } from "@root/api/privilegies";
import SaveIcon from '@mui/icons-material/Save';
import { currencyFormatter } from "@root/utils/currencyFormatter";


interface CardPrivilege {
  privilege: PrivilegeWithAmount;
}

export const СardPrivilege = ({ privilege }: CardPrivilege) => {
  const [inputOpen, setInputOpen] = useState<boolean>(false);
  const [inputValue, setInputValue] = useState<string>("");
  const priceRef = useRef<HTMLDivElement>(null);
  const theme = useTheme();
  const mobile = useMediaQuery(theme.breakpoints.down(600));

  const translationType = {
    count: "за единицу",
    day: "за день",
    mb: "за  МБ",
  };

  const putPrivileges = async () => {

    const [_, putedPrivilegeError] = await putPrivilege({
      name: privilege.name,
      privilegeId: privilege.privilegeId,
      serviceKey: privilege.serviceKey,
      description: privilege.description,
      amount: 1,
      type: privilege.type,
      value: privilege.value,
      price: 100 * Number(inputValue),
    });

    if (putedPrivilegeError) {
      return enqueueSnackbar(putedPrivilegeError);
    }

    if (!priceRef.current) {
      return;
    }

    enqueueSnackbar("Изменения сохранены");

    priceRef.current.innerText = "price: " + inputValue;
    setInputValue("");
    setInputOpen(false);
  };

  const onTextfieldKeyDown = (event: KeyboardEvent) => {
    if (event.key === "Escape") {
      return setInputOpen(false);
    }
    if (event.key === "Enter" && inputValue !== "") {
      putPrivileges();
      setInputOpen(false);
    }
  };

  function handleSavePrice() {
    setInputOpen(false);
    if (!inputValue) return;

    putPrivileges();
}

  return (
    <Box
      key={privilege.type}
      sx={{
        px: "20px",

        display: "flex",
        alignItems: "center",
        border: "1px solid gray",
      }}
    >
      <Box sx={{ display: "flex", borderRight: "1px solid gray" }}>
        <Box sx={{ width: mobile ? "120px" : "200px", py: "25px" }}>
          <Typography
            variant="h6"
            sx={{
              color: "#fe9903",
              overflowWrap: "break-word",
              overflow: "hidden",
            }}
          >
            {privilege.name}
          </Typography>
          <Tooltip
            sx={{
              span: {
                fontSize: "1rem",
              },
            }}
            placement="top"
            title={<Typography sx={{ fontSize: "16px" }}>{privilege.description}</Typography>}
          >
            <IconButton disableRipple>
              <svg width="40" height="40" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M9.25 9.25H10V14.5H10.75"
                  stroke="#7E2AEA"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M9.8125 7C10.4338 7 10.9375 6.49632 10.9375 5.875C10.9375 5.25368 10.4338 4.75 9.8125 4.75C9.19118 4.75 8.6875 5.25368 8.6875 5.875C8.6875 6.49632 9.19118 7 9.8125 7Z"
                  fill="#7E2AEA"
                />
              </svg>
            </IconButton>
          </Tooltip>
          <IconButton onClick={() => setInputOpen(!inputOpen)}>
            <ModeEditOutlineOutlinedIcon sx={{ color: "gray" }} />
          </IconButton>
        </Box>
      </Box>
      <Box sx={{ maxWidth: "600px", width: "100%", display: "flex", alignItems: mobile ? "center" : undefined, justifyContent: "space-around", flexDirection: mobile ? "column" : "row", gap: "5px" }}>
        {inputOpen ? (
          <TextField
            type="number"
            onKeyDown={onTextfieldKeyDown}
            placeholder="введите число"
            fullWidth
            onChange={(event) => setInputValue(event.target.value)}
            sx={{
              alignItems: "center",
              maxWidth: "400px",
              width: "100%",
              marginLeft: "5px",
              "& .MuiInputBase-root": {
                backgroundColor: "#F2F3F7",
                height: "48px",
              },
            }}
            inputProps={{
              sx: {
                borderRadius: "10px",
                fontSize: "18px",
                lineHeight: "21px",
                py: 0,
              },
            }}
            InputProps={{
                endAdornment: (
                    <IconButton onClick={handleSavePrice}>
                        <SaveIcon />
                    </IconButton>
                )
            }}
          />
        ) : (
          <div ref={priceRef} style={{ color: "white", marginRight: "5px" }}>
            price: {currencyFormatter.format(privilege.price / 100)}
          </div>
        )}
        <Typography sx={{ color: "white" }}>{translationType[privilege.type]}</Typography>
      </Box>
    </Box>
  );
};
