import { Button, TextField, Typography } from "@mui/material";
import React, { useState } from "react";
import { SPACING } from "../../../../data/spacing";
import { AnimatePresence, motion } from "framer-motion";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { checkRequestBySlaughter } from "../../services/checkRequestBySlaughter";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch, useSelector } from "react-redux";
import { PropTypes } from "prop-types";
import { getAllocationInformation } from "../../services/get-allocation-information";
import { Grid } from "../../../../components/grid/Grid";
import { useParams } from "react-router-dom";
import { getAcceptedSlaughterRequest } from "../../services/getAcceptedSlaughterRequest";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterGetActiveRequests } from "../../../slaughter-house/services/slaughter-get-active-requests";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export default function CheckRequestItem({ reqKey, poultryRequestKey }) {
  const [openNotif] = useContext(AppContext);
  const [isDenyed, setisDenyed] = useState(false);
  const dispatch = useDispatch();
  const { id } = useParams();
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);

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

  const acceptButtonText =
    getRoleFromUrl() === "ProvinceOperator"
      ? "ثبت اطلاعات بجای کشتارگاه"
      : "ثبت اطلاعات و ارسال به استان";

  const rejectButtonText =
    getRoleFromUrl() === "ProvinceOperator"
      ? "رد اطلاعات بجای کشتارگاه"
      : "رد اطلاعات و پیام به استان";

  return (
    <Grid>
      <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
                      variant="outlined"
                      onClick={() => {
                        dispatch(LOADING_START());
                        dispatch(
                          checkRequestBySlaughter({
                            message: formik.values.rejectText,
                            province_kill_request_key: reqKey,
                            state: "rejected",
                          })
                        ).then((r) => {
                          dispatch(LOADING_END());
                          if (r.error) {
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "مشکلی پیش آمده است!",
                              severity: "error",
                            });
                          } else {
                            dispatch(
                              DRAWER({
                                right: false,
                                bottom: false,
                                top: false,
                                content: null,
                              })
                            );
                            // getFileFromApi(roles, id, dispatch);
                            dispatch(
                              getAcceptedSlaughterRequest({
                                id,
                                role_key: checkPathStartsWith("slaughter")
                                  ? selectedSubUser?.key || ""
                                  : "",
                              })
                            );
                            setisDenyed(false);
                            dispatch(
                              getAllocationInformation({
                                key: poultryRequestKey,
                                role_key: checkPathStartsWith("slaughter")
                                  ? selectedSubUser?.key || ""
                                  : "",
                              })
                            );
                            dispatch(
                              slaughterGetActiveRequests({
                                selectedDate1,
                                selectedDate2,
                                role_key: checkPathStartsWith("slaughter")
                                  ? selectedSubUser?.key || ""
                                  : "",
                              })
                            );
                            openNotif({
                              vertical: "top",
                              horizontal: "center",
                              msg: "عملیات با موفقیت انجام شد.",
                              severity: "success",
                            });
                          }
                        });
                      }}
                    >
                      رد اطلاعات و پیام به استان
                    </Button>
                  </Grid>
                </Grid>
              </Grid>
            </motion.div>
          ) : (
            <Grid container gap={SPACING.SMALL}>
              <Button
                variant="outlined"
                color="secondary"
                onClick={() => {
                  setisDenyed(true);
                }}
              >
                {rejectButtonText}
              </Button>
              <Button
                variant="outlined"
                onClick={() => {
                  dispatch(LOADING_START());
                  dispatch(
                    checkRequestBySlaughter({
                      province_kill_request_key: reqKey,
                      state: "accepted",
                      role: getRoleFromUrl(),
                    })
                  ).then((r) => {
                    dispatch(LOADING_END());
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      dispatch(
                        DRAWER({
                          right: false,
                          bottom: false,
                          top: false,
                          content: null,
                        })
                      );
                      dispatch(
                        getAcceptedSlaughterRequest({
                          id,
                          role_key: checkPathStartsWith("slaughter")
                            ? selectedSubUser?.key || ""
                            : "",
                        })
                      );
                      dispatch(
                        getAllocationInformation({
                          key: poultryRequestKey,
                          role_key: checkPathStartsWith("slaughter")
                            ? selectedSubUser?.key || ""
                            : "",
                        })
                      );
                      dispatch(
                        slaughterGetActiveRequests({
                          selectedDate1,
                          selectedDate2,
                          role_key: checkPathStartsWith("slaughter")
                            ? selectedSubUser?.key || ""
                            : "",
                        })
                      );
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                      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>
                          ),
                        })
                      );
                    }
                  });
                }}
              >
                {acceptButtonText}
              </Button>
            </Grid>
          )}
        </AnimatePresence>
      </Grid>
    </Grid>
  );
}
CheckRequestItem.propTypes = {
  reqKey: PropTypes.string,
  poultryRequestKey: PropTypes.string,
};
