import React, { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { useDispatch, useSelector } from "react-redux";
import { getGuildsSettingsService } from "../../services/get-guilds-settings";
import { ManageGuildsState } from "../manage-guilds-state/ManageGuildsState";
import { ManageStewardsState } from "../manage-stewards-state/ManageStewardsState";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const GuildsSettings = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState([]);
  const { getGuildsSettings } = useSelector((state) => state.provinceSlice);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(getGuildsSettingsService({ kill_house_key: null })).then(() => {
      dispatch(LOADING_END());
    });
  }, []);

  useEffect(() => {
    if (Array.isArray(getGuildsSettings)) {
      const d = getGuildsSettings?.map((item, i) => {
        return [
          i + 1,
          item.killHouse.name,
          <ManageGuildsState
            key={i}
            guildState={item.guilds}
            choose_steward_guilds_key={item.key}
          />,
          <ManageStewardsState
            key={i}
            stewardState={item.steward}
            choose_steward_guilds_key={item.key}
          />,
        ];
      });
      setDataTable(d);
    }
  }, [getGuildsSettings]);

  return (
    <Grid>
      <ResponsiveTable
        paginated
        title="مجوزهای توزیع"
        columns={[
          "ردیف",
          "نام کشتارگاه",
          "اجازه فروش آزاد به صنف",
          "اجازه فروش آزاد به مباشرین",
        ]}
        data={dataTable}
      />
    </Grid>
  );
};
