import React, { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import { Button, Switch, TextField, Typography } from "@mui/material";
import { provincePolicyWagesEditKillhouse } from "../../services/province-policy-wages-edit-killhouse";
import { useDispatch } from "react-redux";

export const ProvinceManagementSellingSlaughterLimitation = ({
  item,
  fetchdata,
}) => {
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();
  const [limitEnabled, setLimitEnabled] = useState(item?.maxKillLimit);
  const [killCapacity, setKillCapacity] = useState(item?.totalKillCapacity);
  const [killPercent, setKillPercent] = useState(item?.extraBarKillPercent);

  const handleToggle = () => {
    const newLimit = !limitEnabled;
    setLimitEnabled(newLimit);

    dispatch(
      provincePolicyWagesEditKillhouse({
        kill_house_key: item?.key,
        total_kill_capacity: killCapacity,
        extra_bar_kill_percent: killPercent,
        max_kill_limit: newLimit,
      })
    ).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",
        });
      }
    });
  };

  const handleSubmit = () => {
    dispatch(
      provincePolicyWagesEditKillhouse({
        kill_house_key: item?.key,
        total_kill_capacity: killCapacity,
        extra_bar_kill_percent: killPercent,
        max_kill_limit: limitEnabled,
      })
    ).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" alignItems="center" spacing={2}>
      <Grid item container alignItems="center" spacing={1}>
        <Grid item>
          <Switch
            checked={limitEnabled}
            onChange={handleToggle}
            inputProps={{ "aria-label": "محدودیت کشتار" }}
          />
        </Grid>
        <Grid>
          <Typography>محدودیت سقف کشتار</Typography>
        </Grid>
      </Grid>

      {limitEnabled && (
        <Grid item container spacing={2} justifyContent="center" width="100%">
          <Grid item>
            <TextField
              fullWidth
              label="ظرفیت کشتار"
              type="number"
              value={killCapacity}
              onChange={(e) => setKillCapacity(e.target.value)}
              size="small"
            />
          </Grid>
          <Grid item>
            <TextField
              fullWidth
              label="درصد اضافه بار"
              type="number"
              value={killPercent}
              onChange={(e) => setKillPercent(e.target.value)}
              size="small"
            />
          </Grid>
          <Grid item>
            <Button
              variant="outlined"
              disabled={
                !killPercent ||
                !killCapacity ||
                killPercent > 100 ||
                killPercent < 0
              }
              onClick={handleSubmit}
            >
              ثبت
            </Button>
          </Grid>
        </Grid>
      )}
    </Grid>
  );
};
