import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { Autocomplete, Button, TextField } from "@mui/material";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceChainsReplaceActiveChain } from "../../services/province-chains-replace-active-chain";
import { provinceChainsGetCompanies } from "../../services/province-chains-get-companies";

export const ChainsReplaceActiveChain = ({ item, updateTable }) => {
  const dispatch = useDispatch();
  const [dataCompany, setDataCompany] = useState([]);
  const [selectedCompany, setSelectedCompany] = useState("");
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    dispatch(provinceChainsGetCompanies()).then((r) => {
      setDataCompany(r.payload.data);
    });
  }, []);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <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={!selectedCompany}
          variant="contained"
          fullWidth
          onClick={() => {
            dispatch(
              provinceChainsReplaceActiveChain({
                type: "replace",
                hatching_key: item?.key,
                company_key: selectedCompany,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
    </Grid>
  );
};
