import { Autocomplete, Button, TextField, Typography } from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { inspectorDeleteKillhouseVetService } from "../../services/inspector-delete-killhouse-vet";
import { inspectorGetKillHousesService } from "../../services/inspector-get-kill-houses";
import { inspectorSetKillhouseVetService } from "../../services/inspector-set-killhouse-vet";
import { manageFarmGetFarmsService } from "../../services/manage-farm-get-farms";

export const InspectorAddVetToKillHouse = ({ userKey, item }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { inspectorGetKillHouses } = useSelector(
    (state) => state.inspectorSlice
  );

  const [value, setValue] = useState(null);
  const [killhouses, setKillhouses] = useState([]);

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

  useEffect(() => {
    const d =
      inspectorGetKillHouses
        ?.filter((item) => item.killer === false)
        .map((item) => {
          return { title: item.name, value: item.key };
        }) || [];
    setKillhouses(d);
  }, [inspectorGetKillHouses]);

  return (
    <Grid contianer gap={SPACING.SMALL}>
      <Grid>
        <Autocomplete
          options={killhouses}
          getOptionLabel={(option) => option.title}
          renderInput={(params) => (
            <TextField {...params} label="انتخاب کشتارگاه" variant="outlined" />
          )}
          value={value}
          onChange={(event, newValue) => {
            setValue(newValue);
          }}
        />
      </Grid>
      <Grid mt={SPACING.TINY}>
        <Button
          variant="contained"
          fullWidth
          onClick={() => {
            dispatch(
              inspectorSetKillhouseVetService({
                role: getRoleFromUrl(),
                user_key: userKey,
                key: value.value,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                dispatch(manageFarmGetFarmsService());
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
              }
            });
          }}
        >
          ثبت
        </Button>
      </Grid>
      <Grid container direction="column" gap={SPACING.SMALL} mt={SPACING.SMALL}>
        <Grid>
          <Typography>کشتارگاه های ثبت شده</Typography>
        </Grid>
        <Grid>
          {item.killHouses?.map((it, i) => {
            return (
              <Grid container key={i} alignItems={"center"} gap={SPACING.SMALL}>
                <Typography>
                  {i + 1}. {it.KillHouseName}
                </Typography>
                <Button
                  color="error"
                  variant="outlined"
                  onClick={() => {
                    dispatch(
                      inspectorDeleteKillhouseVetService({
                        user_key: userKey,
                        key: it.KillHouseKey,
                      })
                    ).then((r) => {
                      if (r.payload.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        dispatch(manageFarmGetFarmsService());
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );
                      }
                    });
                  }}
                >
                  حذف
                </Button>
              </Grid>
            );
          })}
        </Grid>
      </Grid>
    </Grid>
  );
};
