import { Button, Checkbox, FormControlLabel, TextField } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { getLossesPermissionService } from "../../services/get-losses-permission";
import { updateLossesPermissionService } from "../../services/update-losses-permission";

export const ProvinceApplyDefaultLosses = () => {
  const [isChecked, setIsChecked] = useState(true);
  const [numberValue, setNumberValue] = useState("");
  const [data, setData] = useState();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getLossesPermissionService()).then((r) => {
      setIsChecked(r.payload.data.allow);
      setNumberValue(r.payload.data.percent);
      setData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (!isChecked) {
      dispatch(
        updateLossesPermissionService({
          permission_key: data.key,
          allow: false,
          percent: parseInt(numberValue),
        })
      );
    }
  }, [isChecked]);

  const handleChange = (event) => {
    setIsChecked(event.target.checked);
  };

  // Define a handleChange function to update the state when the text field value changes
  const handleChangeNumber = (event) => {
    // Ensure that the entered value is a number (or an empty string)
    const newValue = event.target.value;
    if (/^\d*$/.test(newValue) || newValue === "") {
      setNumberValue(newValue);
    }
  };

  return (
    <Grid container alignItems="center" gap={SPACING.TINY}>
      <FormControlLabel
        control={
          <Checkbox checked={isChecked} onChange={handleChange} name="item4" />
        }
        label="اعمال درصد تلفات پیش فرض:"
      />
      <Grid>
        <TextField
          disabled={!isChecked}
          type="number"
          label="درصد تلفات"
          size="small"
          value={numberValue}
          onChange={handleChangeNumber}
          inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
        />
      </Grid>
      <Grid>
        <Button
          variant="contained"
          disabled={!isChecked || !numberValue}
          onClick={() => {
            dispatch(
              updateLossesPermissionService({
                permission_key: data.key,
                percent: parseInt(numberValue),
                allow: isChecked,
              })
            );
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
