import { Button, TextField } from "@mui/material";
import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { PropTypes } from "prop-types";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useParams } from "react-router-dom";
import { AppContext } from "../../../../contexts/AppContext";
import { AnimatePresence, motion } from "framer-motion";

import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getFileFromApi } from "../../hooks/useRequestFile";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceCheckComplaint } from "../../services/province-check-complaint";

export const FileOperatorCheckComplaint = ({ item }) => {
  const [isDenyedComplaint, setisDenyedComplaint] = useState(false);
  const [roles] = useUserProfile();
  const { id } = useParams();
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      rejectText: "",
    },
    validationSchema: Yup.object({
      rejectText: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا دلیل خود را بیان کنید."),
    }),
  });

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

  return (
    <>
      <Grid container>
        <Grid xs={12}>
          <Grid xs={12}>
            {item.complaint.state === "pending" && (
              <Grid container gap={SPACING.SMALL} padding={SPACING.SMALL}>
                <AnimatePresence>
                  {isDenyedComplaint ? (
                    <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={() => {
                                setisDenyedComplaint(false);
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                          <Grid>
                            <Button
                              disabled={!formik.isValid}
                              variant="outlined"
                              onClick={() => {
                                dispatch(LOADING_START());
                                dispatch(
                                  provinceCheckComplaint({
                                    key: item.complaint.complaintKey,
                                    state: "rejected",
                                    role: getRoleFromUrl(),
                                    message: formik.values.rejectText,
                                  })
                                ).then((r) => {
                                  if (r.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "مشکلی پیش آمده است!",
                                      severity: "error",
                                    });
                                  } else {
                                    getFileFromApi(roles, id, dispatch);
                                    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={() => {
                          setisDenyedComplaint(true);
                        }}
                      >
                        رد شکایت
                      </Button>
                      <Button
                        variant="outlined"
                        onClick={() => {
                          dispatch(LOADING_START());
                          dispatch(
                            provinceCheckComplaint({
                              key: item.complaint.complaintKey,
                              state: "accepted",
                              role: getRoleFromUrl(),
                            })
                          ).then((r) => {
                            if (r.error) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "مشکلی پیش آمده است!",
                                severity: "error",
                              });
                            } else {
                              getFileFromApi(roles, id, dispatch);
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                            }
                            dispatch(LOADING_END());
                          });
                        }}
                      >
                        تایید شکایت
                      </Button>
                    </Grid>
                  )}
                </AnimatePresence>
              </Grid>
            )}
          </Grid>
        </Grid>
      </Grid>
    </>
  );
};

FileOperatorCheckComplaint.propTypes = {
  item: PropTypes.object,
};
