import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import {
  Button,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Select,
  Typography,
} from "@mui/material";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { SPACING } from "../../../../data/spacing";
import { getFaUserRole } from "../../../../utils/getFaUserRole";

export const AddAccessLevelModal = ({ device, onSuccess }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [selectedAccessLevel, setSelectedAccessLevel] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const accessLevelOptions = ["Steward", "KillHouse", "Guilds"];

  const handleCloseModal = () => {
    dispatch(CLOSE_MODAL());
  };

  const handleSubmit = async () => {
    if (!selectedAccessLevel) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "لطفاً یک سطح دسترسی را انتخاب کنید.",
      });
      return;
    }

    if (!device?.key && !device?.id) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "شناسه دستگاه یافت نشد. لطفاً دوباره تلاش کنید.",
      });
      return;
    }

    setSubmitting(true);
    try {
      const payload = {
        pos_key: device?.key || device?.id,
        name: selectedAccessLevel,
      };

      await axios.post("/pos-access-level/", payload);

      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "success",
        msg: "سطح دسترسی با موفقیت افزوده شد.",
      });

      if (onSuccess) {
        onSuccess();
      }
      handleCloseModal();
    } catch (error) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg:
          error?.response?.data?.result ||
          error?.response?.data?.detail ||
          "افزودن سطح دسترسی با خطا مواجه شد.",
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Grid
      container
      direction="column"
      gap={SPACING.SMALL}
      width="100%"
      alignItems="stretch"
      sx={{ minWidth: 300 }}
    >
      <Typography variant="body2">
        دستگاه انتخاب شده:{" "}
        {device?.serial ||
          device?.pos_unique_id ||
          device?.pos_id ||
          device?.posId ||
          "-"}
      </Typography>
      <FormControl fullWidth size="small">
        <InputLabel id="access-level-label">سطح دسترسی</InputLabel>
        <Select
          labelId="access-level-label"
          id="access-level-select"
          value={selectedAccessLevel}
          label="سطح دسترسی"
          onChange={(e) => setSelectedAccessLevel(e.target.value)}
        >
          <MenuItem value="">
            <em>انتخاب سطح دسترسی</em>
          </MenuItem>
          {accessLevelOptions.map((option) => (
            <MenuItem key={option} value={option}>
              {getFaUserRole(option)}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      <Grid container justifyContent="flex-end" gap={SPACING.SMALL} mt={2}>
        <Button
          variant="outlined"
          color="primary"
          onClick={handleCloseModal}
          disabled={submitting}
        >
          انصراف
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={!selectedAccessLevel || submitting}
        >
          {submitting ? "در حال ثبت..." : "ثبت"}
        </Button>
      </Grid>
    </Grid>
  );
};
