import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Button, TextField, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { PropTypes } from "prop-types";
import { AnimatePresence, motion } from "framer-motion";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";

import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { inspectorCheckRequest } from "../../services/inspector-check-request";
import { getFileFromApi } from "../../hooks/useRequestFile";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useParams } from "react-router-dom";
import { inspectorGetNewRequests } from "../../../inspector/services/inspector-new-requests";

export const InspectorRequestOperations = ({ process }) => {
  const [openNotif] = useContext(AppContext);
  const [isSubmited, setIsSubmited] = useState(false);

  useEffect(() => {
    if (process === null) {
      setIsSubmited(true);
    }
  }, []);

  const formik = useFormik({
    initialValues: {
      rejectText: "",
    },
    validationSchema: Yup.object({
      rejectText: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا دلیل خود را بیان کنید."),
    }),
  });
  const [isDenyed, setisDenyed] = useState(false);
  const dispatch = useDispatch();
  const [roles] = useUserProfile();
  const { id } = useParams();

  return (
    <>
      {!isSubmited && (
        <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
          <TimelineSeparator>
            <TimelineDot color="secondary" />
            <TimelineConnector />
          </TimelineSeparator>
          <Grid container direction="column" flexWrap="nowrap" flex="1">
            <Grid container>
              <Grid>
                <TimelineOppositeContent
                  variant="body1"
                  fontWeight="bold"
                  color="secondary"
                >
                  انجام عملیات بازرسی
                </TimelineOppositeContent>
              </Grid>
              <Grid>
                <TimelineContent color="textSecondary">
                  <Typography variant="body2">
                    در این مرحله درخواست را تایید یا رد کنید.
                  </Typography>
                </TimelineContent>
              </Grid>
            </Grid>
            <Grid>
              <Grid xs={12}>
                <Grid container gap={SPACING.SMALL} padding={SPACING.SMALL}>
                  <AnimatePresence>
                    {isDenyed ? (
                      <motion.div
                        animate={{ x: -10, opacity: 1 }}
                        transition={{ duration: 0.3 }}
                        initial={{ opacity: 0 }}
                        exit={{ opacity: 0 }}
                      >
                        <Grid
                          flexDirection={"column"}
                          container
                          gap={SPACING.SMALL}
                        >
                          <Grid>
                            <TextField
                              multiline
                              rows={4}
                              fullWidth
                              id="rejectText"
                              label="پیام خود را وارد کنید"
                              variant="outlined"
                              value={formik.values.rejectText}
                              error={
                                formik.touched.rejectText
                                  ? Boolean(formik.errors.rejectText)
                                  : null
                              }
                              onChange={formik.handleChange}
                              onBlur={formik.handleBlur}
                              helperText={
                                formik.touched.rejectText &&
                                Boolean(formik.errors.rejectText)
                                  ? formik.errors.rejectText
                                  : null
                              }
                            />
                          </Grid>

                          <Grid container gap={SPACING.SMALL}>
                            <Grid>
                              <Button
                                variant="outlined"
                                color="secondary"
                                onClick={() => {
                                  setisDenyed(false);
                                }}
                              >
                                لغو
                              </Button>
                            </Grid>
                            <Grid>
                              <Button
                                color="secondary"
                                variant="outlined"
                                disabled={!formik.isValid}
                                onClick={() => {
                                  dispatch(LOADING_START());
                                  dispatch(
                                    inspectorCheckRequest({
                                      message: formik.values.rejectText,
                                      key: process?.poultry?.poultryRequestKey,
                                      state: "rejected",
                                    })
                                  ).then((r) => {
                                    if (r.error) {
                                      dispatch(LOADING_END());
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "مشکلی پیش آمده است!",
                                        severity: "error",
                                      });
                                    } else {
                                      dispatch(
                                        DRAWER({
                                          right: false,
                                          bottom: false,
                                          top: false,
                                          content: null,
                                        })
                                      );
                                      dispatch(inspectorGetNewRequests());
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "عملیات با موفقیت انجام شد.",
                                        severity: "success",
                                      });
                                    }
                                  });
                                  dispatch(LOADING_END());
                                }}
                              >
                                رد درخواست
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      </motion.div>
                    ) : (
                      <Grid container gap={SPACING.SMALL}>
                        <Button
                          variant="outlined"
                          color="secondary"
                          onClick={() => {
                            setisDenyed(true);
                          }}
                        >
                          رد اطلاعات و پیام به استان
                        </Button>
                        <Button
                          variant="outlined"
                          onClick={() => {
                            dispatch(LOADING_START());
                            dispatch(
                              inspectorCheckRequest({
                                key: process?.poultry?.poultryRequestKey,
                                state: "accepted",
                              })
                            ).then((r) => {
                              if (r.error) {
                                dispatch(LOADING_END());
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "مشکلی پیش آمده است!",
                                  severity: "error",
                                });
                              } else {
                                dispatch(
                                  DRAWER({
                                    right: false,
                                    bottom: false,
                                    top: false,
                                    content: null,
                                  })
                                );
                                dispatch(inspectorGetNewRequests());
                                getFileFromApi(roles, id, dispatch);
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                            });
                            dispatch(LOADING_END());
                          }}
                        >
                          تایید نهایی درخواست
                        </Button>
                      </Grid>
                    )}
                  </AnimatePresence>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </TimelineItem>
      )}
    </>
  );
};
InspectorRequestOperations.propTypes = {
  process: PropTypes.any,
};
