import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { provinceGetPoultry } from "../../../aviculture/services/province-get-poultry";
import { Autocomplete, Button, TextField } from "@mui/material";
import { provinceChainsGetCompanies } from "../../services/province-chains-get-companies";
import { provinceChainsSubmitActiveChain } from "../../services/province-chains-submit-active-chain";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";

export const ChainsSubmitActiveChain = ({ updateTable }) => {
  const dispatch = useDispatch();
  const [poultries, setPoultries] = useState([]);
  const [data, setData] = useState([]);
  const [dataCompany, setDataCompany] = useState([]);
  const [selectedPoultries, setSelectedPoultries] = useState([]);
  const [selectedCompany, setSelectedCompany] = useState("");
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    dispatch(
      provinceGetPoultry({
        chain: true,
      })
    ).then((r) => {
      setData(r.payload.data);
    });
    dispatch(provinceChainsGetCompanies()).then((r) => {
      setDataCompany(r.payload.data);
    });
  }, []);

  useEffect(() => {
    setPoultries(
      data?.map((item) => {
        return {
          label: `${item.unitName} (${item?.user.mobile})`,
          value: `${item.chainCompany?.hatchingKey}`,
        };
      })
    );
  }, [data]);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <Grid>
          <Autocomplete
            disablePortal
            id="province"
            multiple
            options={poultries}
            getOptionLabel={(option) => option.label}
            onChange={(e, value) => {
              setSelectedPoultries(value);
            }}
            renderInput={(params) => (
              <TextField {...params} label="انتخاب مرغداران" />
            )}
          />
        </Grid>

        <Grid>
          <Autocomplete
            disablePortal
            id="province"
            options={
              dataCompany
                ? dataCompany?.map((i) => ({
                    id: i.key,
                    label: `${i.name} (${i.user.mobile})`,
                  }))
                : []
            }
            onChange={(e, value) => {
              setSelectedCompany(value.id);
            }}
            renderInput={(params) => (
              <TextField {...params} label="شرکت زنجیره" />
            )}
          />
        </Grid>
      </Grid>

      <Grid>
        <Button
          disabled={!selectedPoultries.length || !selectedCompany}
          variant="contained"
          fullWidth
          onClick={() => {
            dispatch(
              provinceChainsSubmitActiveChain({
                poultry_hitchings: selectedPoultries?.map((item) => {
                  return item?.value;
                }),
                chain_company: selectedCompany,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد!",
                  severity: "success",
                });
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
