import { Button, TextField, Typography } from "@mui/material";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import React, { useContext, useEffect } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useState } from "react";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { vetFarmNewInspect } from "../../services/vet-farm-new-inspect";
import { vetFarmGetHatchingData } from "../../services/vet-farm-get-hatching-data";
import { PropTypes } from "prop-types";
import { AppContext } from "../../../../contexts/AppContext";

export const VetFarmSubmitInspectionForm = ({
  id,
  hall,
  poultrykey,
  updateTable,
}) => {
  const dispatch = useDispatch();
  const [hatchingData, setHatchingData] = useState("");
  const [inspectionImages, setInspectionImages] = React.useState([]);

  const inspectionImageHandler = (imageList, addUpdateIndex) => {
    setInspectionImages(imageList);
  };
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(vetFarmGetHatchingData(id + "&hall=" + hall)).then((r) => {
      if (r.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "اطلاعات جوجه ریزی یافت نشد!",
          severity: "error",
        });
        dispatch(DRAWER({ right: false, bottom: false, content: null }));
      } else {
        setHatchingData(r.payload.data);

        if (!r.payload.data.length) {
          setHatchingData(null);
        }

        dispatch(LOADING_END());
      }

      dispatch(LOADING_END());
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      topic: "",
      description: "",
      losses: "",
    },
    validationSchema: Yup.object({
      topic: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      description: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی وارد کنید!"),
      losses: Yup.number().typeError("لطفا فیلد را به درستی وارد کنید!"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
    // getUserGeolocationDetail();
  }, []);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      height="100%"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        {hatchingData && (
          <>
            <Grid sx={{ textAlign: "justify" }}>
              <Typography
                variant="body2"
                mr={SPACING.TINY}
                color={(prop) => prop.palette.grey["A700"]}
              >
                دوره جوجه ریزی
              </Typography>
              <Typography variant="body2" mr={SPACING.TINY} fontWeight="bold">
                {`دوره ${hatchingData[0]?.period} سالن ${hatchingData[0]?.hall} نژاد ${hatchingData[0]?.chickenBreed} باقیمانده ${hatchingData[0]?.leftOver} قطعه`}
              </Typography>{" "}
            </Grid>

            {/* <Grid minWidth={210}>
              <Autocomplete
                disablePortal
                id="hatching"
                options={
                  hatchingData
                    ? hatchingData.map((i) => ({
                        id: i.key,
                        race: i.chickenBreed,
                        selected: i,
                        label: `دوره ${i.period} سالن ${i.hall} نژاد ${i.chickenBreed} باقیمانده ${i.leftOver} قطعه`,
                      }))
                    : []
                }
                onChange={(event, value) => {
                  sethatchingKey(value.id);
                }}
                renderInput={(params) => (
                  <TextField {...params} label="دوره جوجه ریزی" />
                )}
              />
            </Grid> */}
            <Grid>
              <TextField
                id="losses"
                label="درصورت وجود تلفات، مقدار آن را وارد کنید"
                variant="outlined"
                sx={{ width: "100%" }}
                value={formik.values.losses}
                error={
                  formik.touched.losses ? Boolean(formik.errors.losses) : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.losses && Boolean(formik.errors.losses)
                    ? formik.errors.losses
                    : null
                }
              />
            </Grid>
          </>
        )}
        <Grid>
          <TextField
            id="topic"
            label="موضوع"
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.topic}
            error={formik.touched.topic ? Boolean(formik.errors.topic) : null}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.topic && Boolean(formik.errors.topic)
                ? formik.errors.topic
                : null
            }
          />
        </Grid>
        <Grid>
          <TextField
            multiline
            rows={4}
            id="description"
            label="توضیحات"
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.description}
            error={
              formik.touched.description
                ? Boolean(formik.errors.description)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.description && Boolean(formik.errors.description)
                ? formik.errors.description
                : null
            }
          />
        </Grid>
        <Typography>پیوست تصویر</Typography>
        <Grid mb={SPACING.SMALL}>
          <ImageUpload
            id="image"
            onChange={inspectionImageHandler}
            images={inspectionImages}
            maxNumber={4}
            title={"بارگذاری سند"}
            value={formik.values.image}
            error={formik.touched.image ? Boolean(formik.errors.image) : null}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.image && Boolean(formik.errors.image)
                ? formik.errors.image
                : null
            }
          />
        </Grid>
        <Grid mb={SPACING.SMALL}>
          <Button
            disabled={!formik.isValid}
            fullWidth
            variant="contained"
            onClick={() => {
              dispatch(LOADING_START());

              const imagesList = inspectionImages.map((item) =>
                fixBase64(item.data_url)
              );
              if (hatchingData) {
                dispatch(
                  vetFarmNewInspect({
                    key: poultrykey,
                    poultry_hatching_key: hatchingData[0]?.key,
                    topic: formik.values.topic,
                    description: formik.values.description,
                    Losses: formik.values.losses ? formik.values.losses : 0,
                    image: imagesList,
                    hall: hall,
                    longitude: "1",
                    latitude: "1",
                  })
                ).then((r) => {
                  updateTable();
                  if (r.error) {
                    if (r.error.message.includes("400")) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "امروز برای این سالن بازرسی ثبت شده است!",
                        severity: "error",
                      });
                    } else if (r.error.message.includes("403")) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "امروز برای مرغداری دیگری بازرسی ثبت شده است!",
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    }
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "با موفقیت ثبت شد!",
                      severity: "success",
                    });
                  }
                  dispatch(LOADING_END());
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                });
              } else {
                dispatch(
                  vetFarmNewInspect({
                    key: poultrykey,
                    topic: formik.values.topic,
                    description: formik.values.description,
                    image: imagesList,
                    hall: hall,
                    longitude: "1",
                    latitude: "1",
                  })
                ).then((r) => {
                  updateTable();
                  if (r.error) {
                    if (r.error.message.includes("400")) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "امروز برای این سالن بازرسی ثبت شده است!",
                        severity: "error",
                      });
                    } else if (r.error.message.includes("403")) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "امروز برای مرغداری دیگری بازرسی ثبت شده است!",
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    }
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "با موفقیت ثبت شد!",
                      severity: "success",
                    });
                  }

                  dispatch(LOADING_END());
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                });
              }
            }}
          >
            ثبت اطلاعات
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};

VetFarmSubmitInspectionForm.propTypes = {
  id: PropTypes.string,
  hall: PropTypes.string,
  poultrykey: PropTypes.string,
};
