import {
  TimelineConnector,
  TimelineContent,
  //   TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Button, TextField, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
// import { formatTime } from "../../../../utils/formatTime";
import { PropTypes } from "prop-types";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { AnimatePresence, motion } from "framer-motion";
import { useDispatch } from "react-redux";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { provinceAcceptRequest } from "../../services/provinceAcceptRequest";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { provinceRejectRequest } from "../../services/provinceRejectRequest";
import useRequestFile from "../../hooks/useRequestFile";
// import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getProvinceNewRequests } from "../../../province/services/get-province-new-requests";

const ProvinceCheckRequest = ({ id, file, item, updateTable }) => {
  const myFile = useRequestFile(id);
  file = file ? file : myFile?.file?.process;
  const [openNotif, , selectedDate1, , selectedDate2, ,] =
    useContext(AppContext);
  const [isSubmited, setIsSubmited] = useState(false);
  // const [roles] = useUserProfile();

  useEffect(() => {
    if (file?.province !== null) {
      setIsSubmited(true);
    }
  }, [file]);

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

  // useEffect(() => {
  //   if (isDenyed) {
  //     animationControl.start({
  //       x: -10,
  //       display: "block",
  //       transition: { duration: 0.3 },
  //     });
  //   }
  // }, [isDenyed]);

  // const MotionInput = motion(TextField);
  const dispatch = useDispatch();

  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
                                disabled={!formik.values.rejectText}
                                variant="outlined"
                                onClick={() => {
                                  dispatch(LOADING_START());
                                  dispatch(
                                    provinceRejectRequest({
                                      message: formik.values.rejectText,
                                      key: item?.cityCheckRequest,
                                      state: "reject",
                                    })
                                  ).then((r) => {
                                    if (r.error) {
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "مشکلی پیش آمده است!",
                                        severity: "error",
                                      });
                                    } else {
                                      updateTable();
                                      dispatch(
                                        DRAWER({
                                          right: false,
                                          bottom: false,
                                          content: null,
                                        })
                                      );
                                      dispatch(
                                        getProvinceNewRequests({
                                          selectedDate1,
                                          selectedDate2,
                                        })
                                      );
                                      // getFileFromApi(roles, id, dispatch);
                                      dispatch(LOADING_END());
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "عملیات با موفقیت انجام شد.",
                                        severity: "success",
                                      });
                                    }
                                  });
                                }}
                              >
                                رد اطلاعات و پیام به مرغدار
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      </motion.div>
                    ) : (
                      <Grid container gap={SPACING.SMALL} xs={12}>
                        <Button
                          fullWidth
                          variant="outlined"
                          color="secondary"
                          onClick={() => {
                            setisDenyed(true);
                          }}
                        >
                          رد اطلاعات و پیام به مرغدار
                        </Button>
                        <Button
                          fullWidth
                          variant="outlined"
                          onClick={() => {
                            dispatch(LOADING_START());
                            dispatch(
                              provinceAcceptRequest({
                                key: item?.cityCheckRequest,
                                state: "accept",
                              })
                            ).then((r) => {
                              if (r.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "مشکلی پیش آمده است!",
                                  severity: "error",
                                });
                              } else {
                                // getFileFromApi(roles, id, dispatch);
                                updateTable();
                                dispatch(
                                  getProvinceNewRequests({
                                    selectedDate1,
                                    selectedDate2,
                                  })
                                );
                                dispatch(
                                  DRAWER({
                                    right: false,
                                    bottom: false,
                                    content: null,
                                  })
                                );
                                dispatch(
                                  OPEN_MODAL({
                                    title: "عملیات با موفقیت انجام شد.",
                                    content: (
                                      <Grid
                                        container
                                        direction="column"
                                        gap={SPACING.MEDIUM}
                                        alignItems="center"
                                        justifyContent="center"
                                      >
                                        <Grid>
                                          <Typography color={"green"}>
                                            پرونده به کارتابل (در انتظار تخصیص)
                                            انتقال پیدا کرد.
                                          </Typography>
                                        </Grid>
                                        <Grid>
                                          <Button
                                            variant="contained"
                                            color="success"
                                            onClick={() => {
                                              dispatch(CLOSE_MODAL());
                                            }}
                                          >
                                            تایید
                                          </Button>
                                        </Grid>
                                      </Grid>
                                    ),
                                  })
                                );
                                dispatch(
                                  getProvinceNewRequests({
                                    selectedDate1,
                                    selectedDate2,
                                  })
                                );
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                                dispatch(LOADING_END());
                                updateTable();
                              }
                            });
                          }}
                        >
                          تایید و اختصاص به کشتارگاه
                        </Button>
                      </Grid>
                    )}
                  </AnimatePresence>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </TimelineItem>
      )}
    </>
  );
};
ProvinceCheckRequest.propTypes = {
  file: PropTypes.object,
};

export default ProvinceCheckRequest;
