import { Autocomplete, Button, TextField, Typography } from "@mui/material";
import { useFormik } from "formik";
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 { Yup } from "../../../../lib/yup/yup";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceAddCarToKillhouseService } from "../../services/province-add-car-to-killhouse";
import { provinceGetCars } from "../../services/province-get-cars";
import { provinceGetOnlyKillHousesService } from "../../services/province-get-only-kill-houses";
import { provinceRemoveCarFromKillhouseService } from "../../services/province-remove-car-from-killhouse";

const validationSchema = Yup.object().shape({
  // add any other validation rules that you need
  autocompleteField: Yup.string().required("This field is required"),
});

export const ProvinceAllocateCarsForm = ({ killHouseList, driverKey }) => {
  const [openNotif] = useContext(AppContext);

  const formik = useFormik({
    initialValues: {
      autocompleteField: "",
    },
    validationSchema,
    onSubmit: (values) => {
      if (!values?.autocompleteField || !driverKey) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "لطفا تمام فیلدها را پر کنید",
          severity: "error",
        });
        return;
      }
      dispatch(
        provinceAddCarToKillhouseService({
          kill_house_key: values.autocompleteField,
          driver_key: driverKey,
        })
      ).then((r) => {
        if (r?.payload?.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(provinceGetCars());
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });
  const dispatch = useDispatch();
  const [killhouses, setKillhouses] = useState([]);
  const { provinceGetOnlyKillHouses } = useSelector(
    (state) => state.provinceSlice
  );

  useEffect(() => {
    if (getRoleFromUrl() === "KillHouse") {
      dispatch(provinceGetOnlyKillHousesService("self_kill_houses"));
    } else {
      dispatch(provinceGetOnlyKillHousesService("role=ProvinceOperator"));
    }
  }, []);

  useEffect(() => {
    if (
      !provinceGetOnlyKillHouses ||
      !Array.isArray(provinceGetOnlyKillHouses)
    ) {
      setKillhouses([]);
      return;
    }
    const d = provinceGetOnlyKillHouses
      .map((item) => {
        if (!item) return null;
        let prefix;
        if (item.killer) {
          prefix = "کشتارکن";
        } else {
          prefix = "کشتارگاه";
        }
        const name = `${prefix} ${item?.name || ""}`;
        return { title: name, value: item?.key || "" };
      })
      .filter((item) => item !== null && item.value);
    setKillhouses(d || []);
  }, [provinceGetOnlyKillHouses]);

  return (
    <Grid>
      <form onSubmit={formik.handleSubmit}>
        <Grid
          container
          direction="column"
          gap={SPACING.TINY}
          mb={SPACING.SMALL}
        >
          <Autocomplete
            id="autocompleteField"
            options={killhouses || []}
            getOptionLabel={(option) => option?.title || ""}
            renderInput={(params) => (
              <TextField
                {...params}
                label="انتخاب کشتارگاه"
                variant="outlined"
                fullWidth
                error={
                  formik.touched.autocompleteField &&
                  Boolean(formik.errors.autocompleteField)
                }
                helperText={
                  formik.touched.autocompleteField &&
                  formik.errors.autocompleteField
                }
              />
            )}
            onChange={(e, value) =>
              formik.setFieldValue("autocompleteField", value?.value || "")
            }
            value={killhouses?.find(
              (o) => o.value === formik.values.autocompleteField
            )}
          />
          <Button fullWidth variant="contained" type="submit">
            ثبت
          </Button>
        </Grid>
      </form>
      <Typography variant="body1" fontWeight={"bold"}>
        کشتارگاه های خودرو
      </Typography>
      {killHouseList && Array.isArray(killHouseList) && killHouseList.length > 0
        ? killHouseList.map((item, i) => {
            if (!item) return null;
            return (
              <Grid
                container
                gap={SPACING.TINY}
                alignItems="center"
                justifyContent="space-between"
                style={{ borderBottom: "1px solid #DDD" }}
                key={item.killHouseKey || i}
              >
                <Typography>
                  {i + 1}. {item?.killHouseName || ""}
                </Typography>
                <Button
                  color="error"
                  onClick={() => {
                    if (!item?.killHouseKey || !driverKey) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "اطلاعات ناقص است",
                        severity: "error",
                      });
                      return;
                    }
                    dispatch(
                      provinceRemoveCarFromKillhouseService({
                        kill_house_key: item.killHouseKey,
                        driver_key: driverKey,
                      })
                    ).then((r) => {
                      if (r?.payload?.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: r.payload.error,
                          severity: "error",
                        });
                      } else {
                        dispatch(provinceGetCars());
                        dispatch(
                          DRAWER({ right: false, bottom: false, content: null })
                        );
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                    });
                  }}
                >
                  حذف
                </Button>
              </Grid>
            );
          })
        : null}
    </Grid>
  );
};
