import {
  TimelineConnector,
  TimelineContent,
  //   TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Button, TextField, Typography } from "@mui/material";
import React, { useState } from "react";
// import { formatTime } from "../../../../utils/formatTime";
import { PropTypes } from "prop-types";
import { Grid } from "../../../../components/grid/Grid";

import { SPACING } from "../../../../data/spacing";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch } from "react-redux";
import { AnimatePresence, motion } from "framer-motion";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { provinceFinancialSlaughterCheckRequest } from "../../services/provinceFinancialSlaughterCheckRequest";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceFinancialGetPayedFactorsService } from "../../../province-finacial/services/province-financial-get-payed-factors-service";

const ProvinceFinancialSlaughterCheckRequest = ({ factorKey, factorType }) => {
  const [openNotif] = useContext(AppContext);
  const [isSubmited] = useState(false);
  const [isDenyed, setisDenyed] = useState(false);
  const dispatch = useDispatch();

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

  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>
                <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(
                                    provinceFinancialSlaughterCheckRequest({
                                      key: factorKey,
                                      type: factorType,
                                      message: formik.values.rejectText,
                                      state: "rejected",
                                    })
                                  ).then((r) => {
                                    dispatch(LOADING_END());
                                    if (r.error) {
                                      openNotif({
                                        vertical: "top",
                                        horizontal: "center",
                                        msg: "مشکلی پیش آمده است!",
                                        severity: "error",
                                      });
                                    } else {
                                      setisDenyed(false);
                                      // getFileFromApi(roles, id, dispatch);
                                      dispatch(
                                        provinceFinancialGetPayedFactorsService()
                                      );
                                      dispatch(
                                        DRAWER({
                                          right: false,
                                          bottom: false,
                                          top: false,
                                          content: null,
                                          size: null,
                                        })
                                      );
                                      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);
                          }}
                        >
                          رد پرداخت
                        </Button>
                        <Button
                          variant="outlined"
                          onClick={() => {
                            dispatch(LOADING_START());
                            dispatch(
                              provinceFinancialSlaughterCheckRequest({
                                key: factorKey,
                                type: factorType,
                                state: "accepted",
                              })
                            ).then((r) => {
                              dispatch(LOADING_END());
                              if (r.error) {
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "مشکلی پیش آمده است!",
                                  severity: "error",
                                });
                              } else {
                                // getFileFromApi(roles, id, dispatch);
                                dispatch(
                                  provinceFinancialGetPayedFactorsService()
                                );
                                dispatch(
                                  DRAWER({
                                    right: false,
                                    bottom: false,
                                    top: false,
                                    content: null,
                                    size: null,
                                  })
                                );
                                setisDenyed(false);
                                openNotif({
                                  vertical: "top",
                                  horizontal: "center",
                                  msg: "عملیات با موفقیت انجام شد.",
                                  severity: "success",
                                });
                              }
                            });
                          }}
                        >
                          تایید پرداخت
                        </Button>
                      </Grid>
                    )}
                  </AnimatePresence>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </TimelineItem>
      )}
    </>
  );
};
ProvinceFinancialSlaughterCheckRequest.propTypes = {
  factorKey: PropTypes.any,
  factorType: PropTypes.any,
};

export default ProvinceFinancialSlaughterCheckRequest;
