import { Button, Typography, Checkbox } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { slaughterGetKillerKillhousesService } from "../../../slaughter-house/services/slaughter-get-killers-killhouses";
import { provinceGetSlaughterhousesQuotaService } from "../../services/province-get-slaughterhouses-quota";
import { provinceSetSlaughterhousesQuotaService } from "../../services/province-set-slaughterhouses-quota";
import { ProvinceGuildsQuantity } from "../province-guilds-quantity/ProvinceGuildsQuantity";
import { ProvinceManageSlaughterhouseQuota } from "../province-manage-slaughterhouse-quota/ProvinceManageSlaughterhouseQuota";
import { ProvinceSelectSlaughterForSlaughter } from "../province-select-slaughter-for-slaughter/ProvinceSelectSlaughterForSlaughter";
// import { ProvinceSelectSlaughterForSlaughter } from "../province-select-slaughter-for-slaughter/ProvinceSelectSlaughterForSlaughter";
import { formatJustDate } from "../../../../utils/formatTime";

export const ProvinceSlaughterhouseQuota = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState();
  const [allPercent, setAllPercent] = useState([]);
  const [openNotif] = useContext(AppContext);
  const { provinceGetSlaughterhousesQuota } = useSelector(
    (state) => state.provinceSlice
  );

  const onPercentChange = (keyToFind, percent) => {
    // remove the slaughter that updated
    setAllPercent((prevState) => {
      const tempArr = prevState.filter((item) => item.key !== keyToFind);
      const itemToAdd = prevState.filter((item) => item.key === keyToFind)[0];
      const objectToAdd = {
        key: keyToFind,
        percent,
        killer_kill_house_key: itemToAdd?.killer_kill_house_key,
      };
      tempArr.push(objectToAdd);
      return tempArr;
    });
  };

  const onSlaughterChange = (keyToFind, slughterKey) => {
    // remove the slaughter that updated
    setAllPercent((prevState) => {
      const index = prevState.findIndex((obj) => obj.key === keyToFind);
      const removedItem = prevState[index];
      const tempArr = prevState.filter((item) => item.key !== keyToFind);
      const objectToAdd = {
        ...removedItem,
        killer_kill_house_key: slughterKey,
      };
      tempArr.push(objectToAdd);
      return tempArr;
    });
  };

  useEffect(() => {
    dispatch(provinceGetSlaughterhousesQuotaService());
    dispatch(slaughterGetKillerKillhousesService());
  }, []);

  useEffect(() => {
    const tempKeyAndPercent = [];
    const d = provinceGetSlaughterhousesQuota?.map((item, i) => {
      const killhouseType = item?.killHouse?.killer ? "کشتارکن" : "کشتارگاه";
      tempKeyAndPercent.push({
        key: item.key,
        percent: item.percent,
        killer_kill_house_key: item?.killHouseForKiller?.key,
      });
      return [
        <Checkbox key={i} defaultChecked />,
        i + 1,
        killhouseType,
        item.killHouse?.name,
        item.killHouse?.killHouseOperator?.user?.fullname,
        `${item.killHouse?.systemAddress?.province?.name} - ${item.killHouse?.systemAddress?.city?.name} - ${item.killHouse?.systemAddress?.address}`,
        item?.killHouse?.killer ? (
          <ProvinceSelectSlaughterForSlaughter
            key={item.killHouse?.name + i}
            onSlaughterChange={onSlaughterChange}
            slaughterKey={item.key}
            killHouseForKiller={item.killHouseForKiller}
            disabled={true}
          />
        ) : (
          item.killHouse?.name
        ),
        <ProvinceManageSlaughterhouseQuota
          key={i}
          slaughterKey={item.key}
          onPercentChange={onPercentChange}
          percent={item.percent}
        />,
        <ProvinceGuildsQuantity item={item} key={item.key} />,
        item.guildsWeight,
      ];
    });
    setAllPercent(tempKeyAndPercent);

    setDataTable(d);
  }, [provinceGetSlaughterhousesQuota]);

  const sum = allPercent?.reduce(
    (accumulator, currentValue) => accumulator + currentValue.percent,
    0
  );

  return (
    <Grid
      display="flex"
      width="100%"
      direction="column"
      alignItems="end"
      style={{ flexDirection: "column" }}
      mt={SPACING.SMALL}
      pb={SPACING.LARGE}
      px={2}
    >
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        mb={SPACING.TINY}
        width="100%"
      >
        <Grid>
          <Typography style={{ color: "green" }}>
            تاریخ آخرین بروزرسانی:{" "}
            {provinceGetSlaughterhousesQuota?.length &&
              formatJustDate(
                provinceGetSlaughterhousesQuota[0]?.lastGuildsUpdateDate
              )}
          </Typography>
        </Grid>
        <Grid container gap={SPACING.TINY}>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                provinceSetSlaughterhousesQuotaService({
                  percentage_list: allPercent,
                  type: "guild",
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  dispatch(provinceGetSlaughterhousesQuotaService());
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            بروزرسانی بر اساس واحد
          </Button>
          <Button
            variant="contained"
            onClick={() => {
              dispatch(
                provinceSetSlaughterhousesQuotaService({
                  percentage_list: allPercent,
                  type: "guilds_weight",
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  dispatch(provinceGetSlaughterhousesQuotaService());
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            بروزرسانی بر اساس وزن
          </Button>
        </Grid>
      </Grid>
      <SimpleTable
        columns={[
          "وضعیت",
          "ردیف",
          "ماهیت",
          "نام واحد",
          "نام و نام خانوادگی",
          "آدرس",
          "محل کشتار",
          "سهم روزانه (درصد)",
          "تعداد زیرمجموعه ها (واحد)",
          "زیرمجموعه (وزن)",
        ]}
        data={dataTable}
      />
      <Grid
        container
        gap={SPACING.SMALL}
        mx={SPACING.SMALL}
        mt={SPACING.TINY}
        style={{
          position: "fixed",
          bottom: "4px",
          padding: "10px",
          borderRadius: "10px",
          background: "#3c3c3c",
          color: "white",
          justifyContent: "center",
          alignItems: "center",
          zIndex: 99999999999,
        }}
      >
        <Typography>جمع کل درصد ها</Typography>
        <Typography>{sum.toFixed(2)}%</Typography>
        <Button
          variant="contained"
          disabled={sum.toFixed(2) !== Number(100).toFixed(2)}
          onClick={() => {
            dispatch(
              provinceSetSlaughterhousesQuotaService({
                percentage_list: allPercent,
                type: "manual",
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                dispatch(provinceGetSlaughterhousesQuotaService());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
