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 { policyChangePoultryFreeSalesService } from "../../services/policy-change-poultry-free-sales";
import { provinceGetPoultriesService } from "../../services/province-get-poultries";
import { BackButton } from "../../../../components/back-button/BackButton";

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

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

  useEffect(() => {
    const d = provinceGetPoultries?.map((item) => {
      return [
        item.name,
        <Switch
          key="kkk"
          checked={item.allowSellState}
          onChange={(event) => {
            dispatch(
              policyChangePoultryFreeSalesService({
                poultry_key: item.key,
                allow: event.target.checked,
              })
            ).then((r) => {
              dispatch(provinceGetPoultriesService());
            });
            // setChecked(event.target.checked);
          }}
          name="checked"
          color="primary"
        />,
      ];
    });
    setData(d);
  }, [provinceGetPoultries]);

  return (
    <Grid container>
      <BackButton />
      <AdvancedTable
        name="دسترسی مرغداران جهت فروش آزاد"
        columns={["مرغدار", "دسترسی"]}
        data={data}
      />
    </Grid>
  );
};
