import { Button, Switch, TextField, FormControlLabel } from "@mui/material";
import { useState, useEffect, useContext } from "react";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceUpdateKillhouseArchivePercentService } from "../../services/province-update-killhouse-archive-percent";

export const ProvinceManageCarcassStandardLossPercent = ({
  item,
  fetchdata,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

  const [isChecked, setIsChecked] = useState(
    item?.wareHouseRemainingWeightArchivePercent !== undefined &&
      item?.wareHouseRemainingWeightArchivePercent !== null &&
      item?.wareHouseRemainingWeightArchivePercent > 0
  );
  const [percentValue, setPercentValue] = useState(
    item?.wareHouseRemainingWeightArchivePercent || 0
  );

  useEffect(() => {
    const hasValue =
      item?.wareHouseRemainingWeightArchivePercent !== undefined &&
      item?.wareHouseRemainingWeightArchivePercent !== null &&
      item?.wareHouseRemainingWeightArchivePercent > 0;
    setIsChecked(hasValue);
    setPercentValue(item?.wareHouseRemainingWeightArchivePercent || 0);
  }, [item]);

  const isValidValue = Number(percentValue) >= 0 && Number(percentValue) <= 100;

  const handleTextChange = (event) => {
    setPercentValue(event.target.value);
  };

  const handleSwitchChange = () => {
    const newChecked = !isChecked;
    setIsChecked(newChecked);
    if (!newChecked) {
      setPercentValue(0);
    }
  };

  const handleSubmit = () => {
    dispatch(
      provinceUpdateKillhouseArchivePercentService({
        kill_house_key: item.key,
        ware_house_remaining_weight_archive_percent: isChecked
          ? Number(percentValue)
          : 0,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        fetchdata();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "عملیات با موفقیت انجام شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid container direction="column" gap={SPACING.SMALL} pt={SPACING.TINY}>
      <Grid container alignItems="center" spacing={1}>
        <Grid item>
          <FormControlLabel
            control={
              <Switch
                checked={isChecked}
                onChange={handleSwitchChange}
                color="primary"
              />
            }
            label="حداکثر افت استاندارد لاشه"
          />
        </Grid>
      </Grid>

      {isChecked && (
        <Grid container alignItems="center" spacing={1}>
          <Grid item xs>
            <TextField
              fullWidth
              size="small"
              label="درصد"
              type="number"
              value={percentValue}
              onChange={handleTextChange}
              variant="outlined"
              inputProps={{ min: 0, max: 100 }}
              error={!isValidValue}
              helperText={!isValidValue ? "عدد باید بین 0 تا 100 باشد" : ""}
            />
          </Grid>
        </Grid>
      )}

      <Grid item width="100%" mt={2}>
        <Button
          variant="contained"
          onClick={handleSubmit}
          fullWidth
          disabled={isChecked && !isValidValue}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
    </Grid>
  );
};
