import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch } from "react-redux";
import { provincePolicyWageSetupGetKillhouses } from "../../services/province-policy-wage-setup-get-killhouses";
import { IconButton, TextField } from "@mui/material";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { provincePolicyWagesEditKillhouse } from "../../services/province-policy-wages-edit-killhouse";
import SaveIcon from "@mui/icons-material/Save";
import { AppContext } from "../../../../contexts/AppContext";
// import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const ProvincePolicyWagesSetupKillhouses = () => {
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();
  const [data, setData] = useState();
  const [tableData, setTableData] = useState();

  const updateTable = () => {
    dispatch(provincePolicyWageSetupGetKillhouses()).then((r) => {
      setData(r.payload.data);
    });
  };

  useEffect(() => {
    updateTable();
  }, []);

  const handleFormCheck = (item) => {
    if (
      parseInt(item?.companyGatewayPercent) +
        parseInt(item.unionGatewayPercent) +
        parseInt(item.guildsGatewayPercent) +
        parseInt(item.otherGatewayPercent) >
      100
    ) {
      return true;
    } else {
      return false;
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        i + 1,
        item?.name,
        item?.killHouseOperator?.user?.mobile,
        <TextField
          key={i}
          style={{ width: "160px" }}
          label="سهم شرکت"
          value={item.companyGatewayPercent}
          onChange={(event) => handleCompanyChange(event, i)}
          size="small"
        />,
        <TextField
          key={i}
          style={{ width: "160px" }}
          label="سهم اتحادیه"
          value={item.unionGatewayPercent}
          onChange={(event) => handleUnionChange(event, i)}
          size="small"
        />,
        <TextField
          key={i}
          style={{ width: "160px" }}
          label="سهم صنف"
          value={item.guildsGatewayPercent}
          onChange={(event) => handleGuildChange(event, i)}
          size="small"
        />,
        <TextField
          key={i}
          style={{ width: "160px" }}
          label="سهم دیگر"
          value={item.otherGatewayPercent}
          onChange={(event) => handleOtherChange(event, i)}
          size="small"
        />,
        <IconButton
          disabled={handleFormCheck(item)}
          key={i}
          color="primary"
          onClick={() => {
            dispatch(
              provincePolicyWagesEditKillhouse({
                kill_house_key: item?.key,
                company_gateway_percent: parseInt(item?.companyGatewayPercent),
                union_gateway_percent: parseInt(item.unionGatewayPercent),
                guilds_gateway_percent: parseInt(item.guildsGatewayPercent),
                other_gateway_percent: parseInt(item.otherGatewayPercent),
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          <SaveIcon />
        </IconButton>,
      ];
    });

    setTableData(d);
  }, [data]);

  const handleCompanyChange = (event, rowIndex) => {
    const newData = [...data];
    newData[rowIndex].companyGatewayPercent = Number(event.target.value);
    setData(newData);
  };
  const handleUnionChange = (event, rowIndex) => {
    const newData = [...data];
    newData[rowIndex].unionGatewayPercent = Number(event.target.value);
    setData(newData);
  };
  const handleGuildChange = (event, rowIndex) => {
    const newData = [...data];
    newData[rowIndex].guildsGatewayPercent = Number(event.target.value);
    setData(newData);
  };
  const handleOtherChange = (event, rowIndex) => {
    const newData = [...data];
    newData[rowIndex].otherGatewayPercent = Number(event.target.value);
    setData(newData);
  };

  return (
    <Grid container alignItems="center" justifyContent="center">
      <ResponsiveTable
        paginated
        title="بر اساس کشتارگاه"
        columns={[
          "ردیف",
          "نام کشتارگاه",
          "موبایل",
          "سهم شرکت",
          "سهم اتحادیه",
          "سهم صنف",
          "سهم دیگر",
          "ذخیره تغییرات",
        ]}
        data={tableData}
      />
    </Grid>
  );
};
