import { Switch } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { BackButton } from "../../../../components/back-button/BackButton";
import { Grid } from "../../../../components/grid/Grid";
import { policyChangeKillhouseGuildsService } from "../../services/policy-change-killhouse-guilds";
import { provinceGetKillhousesGuildsService } from "../../services/province-get-killhouses-guilds";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const PolicyKillhouseGuilds = () => {
  const dispatch = useDispatch();
  const { provinceGetKillhousesGuilds } = useSelector(
    (state) => state.provinceSlice
  );
  const [data, setData] = useState();

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

  useEffect(() => {
    const d = provinceGetKillhousesGuilds?.map((item, i) => {
      return [
        item.killHouse?.name,
        item.killHouse?.killer ? "کشتارکن" : "کشتارگاه",
        <Switch
          key={i}
          checked={item.allow}
          onChange={(event) => {
            dispatch(
              policyChangeKillhouseGuildsService({
                register_guilds_key: item.key,
                allow: event.target.checked,
              })
            ).then((r) => {
              dispatch(provinceGetKillhousesGuildsService());
            });
            // setChecked(event.target.checked);
          }}
          name="checked"
          color="primary"
        />,
      ];
    });
    setData(d);
  }, [provinceGetKillhousesGuilds]);

  return (
    <Grid container>
      <BackButton />
      <ResponsiveTable
        paginated
        title="دسترسی به اصناف"
        columns={["کشتارگاه/کشتارکن", "ماهیت", "دسترسی"]}
        data={data}
        customColors={[{ name: "ماهیت", color: "green" }]}
      />
    </Grid>
  );
};
