import { Switch } from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
import { Grid } from "../../../../components/grid/Grid";
import { policyChangeKillhouseDirectBuyService } from "../../services/policy-change-killhouse-direct-buy";
import { provinceGetKillhousesService } from "../../services/province-get-killhouses";
import { BackButton } from "../../../../components/back-button/BackButton";

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

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

  useEffect(() => {
    const d = provinceGetKillhouses?.map((item) => {
      return [
        item.killHouse.name,
        <Switch
          key="kkk"
          checked={item.allow}
          onChange={(event) => {
            dispatch(
              policyChangeKillhouseDirectBuyService({
                direct_buying_key: item.key,
                allow: event.target.checked,
              })
            ).then((r) => {
              dispatch(provinceGetKillhousesService());
            });
            // setChecked(event.target.checked);
          }}
          name="checked"
          color="primary"
        />,
        <Switch
          key="kkk"
          checked={item.exportStatus}
          onChange={(event) => {
            dispatch(
              policyChangeKillhouseDirectBuyService({
                direct_buying_key: item.key,
                export_status: event.target.checked,
              })
            ).then((r) => {
              dispatch(provinceGetKillhousesService());
            });
            // setChecked(event.target.checked);
          }}
          name="checked"
          color="primary"
        />,
      ];
    });
    setData(d);
  }, [provinceGetKillhouses]);

  return (
    <Grid container>
      <BackButton />
      <AdvancedTable
        name="اجازه خرید مستقیم"
        columns={["کشتارگاه/کشتارکن", "خرید مستقیم", "صادرات"]}
        data={data}
      />
    </Grid>
  );
};
