import { Switch } from "@mui/material";
import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceGetCars } from "../../services/province-get-cars";
import { updateCarStateService } from "../../services/update-car-state";

export const ManageCarState = ({ item }) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [checked, setChecked] = useState(
    getRoleFromUrl() === "KillHouse"
      ? item.addCarActiveState
      : item.driverActiveState
  );

  const handleChange = (event) => {
    let reqObj;
    if (getRoleFromUrl() === "KillHouse") {
      reqObj = {
        add_car_key: item.addCarKey,
        add_car_change_activation: event.target.checked,
      };
    } else {
      reqObj = {
        driver_key: item.key,
        change_activation: event.target.checked,
      };
    }
    dispatch(updateCarStateService(reqObj)).then((r) => {
      if (r?.payload?.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r?.payload?.error,
          severity: "error",
        });
      } else {
        dispatch(provinceGetCars());
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
    setChecked(event.target.checked);
  };

  let disabled = false;
  if (item.driverType === "rental") {
    disabled = true;
  }

  return (
    <>
      <Switch
        checked={checked}
        onChange={handleChange}
        name="mySwitch"
        color="primary"
        disabled={disabled}
      />
      {checked ? (
        <label htmlFor="mySwitch">فعال</label>
      ) : (
        <label htmlFor="mySwitch">غیرفعال</label>
      )}
    </>
  );
};
