import {
  TimelineConnector,
  TimelineContent,
  //   TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import {
  Button,
  // FormControl,
  // FormControlLabel,
  // FormLabel,
  // Radio,
  // RadioGroup,
  TextField,
  Typography,
} from "@mui/material";
import React, { 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 { checkRequestByCity } from "../../services/checkRequestByCity";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { getFileFromApi } from "../../hooks/useRequestFile";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { avicultureGetRequests } from "../../../aviculture/services/aviculture-requests";
import { getProvinceNewRequests } from "../../../province/services/get-province-new-requests";
import { avicultureRequestsStateProcessService } from "../../../aviculture/services/aviculture-requests-state-process";

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

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

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

  const showHatchingAllowed =
    file?.hatching?.allowHatching === "pending" &&
    file?.hatching?.leftOver !== 0;
  const buttonState = !formik.values.canHaching && showHatchingAllowed;

  // const animationControl = useAnimation();

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

  // const MotionInput = motion(TextField);
  const dispatch = useDispatch();
  const acceptButtonText =
    getRoleFromUrl() === "ProvinceOperator"
      ? "تایید اطلاعات بجای شهرستان"
      : "ثبت اطلاعات و ارسال به استان";
  return (
    <>
      {!isSubmited && (
        <TimelineItem sx={{ alignSelf: "flex-start", width: "100%" }}>
          <TimelineSeparator>
            <TimelineDot color="secondary" />
            <TimelineConnector />
          </TimelineSeparator>
          <Grid container direction="column" flexWrap="nowrap" flex="1" xs={12}>
            <Grid container>
              <Grid>
                <TimelineOppositeContent
                  variant="body1"
                  fontWeight="bold"
                  color="secondary"
                >
                  انجام عملیات
                </TimelineOppositeContent>
              </Grid>
              <Grid>
                <TimelineContent color="textSecondary">
                  <Typography variant="body2">
                    در این مرحله درخواست را تایید یا رد کنید.
                  </Typography>
                </TimelineContent>
              </Grid>
            </Grid>
            <Grid container xs={12}>
              <Grid xs={12}>
                <Grid
                  container
                  gap={SPACING.SMALL}
                  padding={SPACING.SMALL}
                  xs={12}
                >
                  <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}
                          xs={12}
                        >
                          <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} xs={12}>
                            <Grid>
                              <Button
                                fullWidth
                                variant="outlined"
                                color="secondary"
                                onClick={() => {
                                  setisDenyed(false);
                                }}
                              >
                                لغو
                              </Button>
                            </Grid>
                            <Grid container xs={12}>
                              <Button
                                fullWidth
                                disabled={!formik.values.rejectText}
                                variant="outlined"
                                onClick={() => {
                                  dispatch(LOADING_START());
                                  dispatch(
                                    checkRequestByCity({
                                      message: formik.values.rejectText,
                                      key: file?.key,
                                      allow_hatching: formik.values.canHaching,
                                      state: "reject",
                                      role: getRoleFromUrl(),
                                    })
                                  ).then((r) => {
                                    if (updateTable) {
                                      updateTable();
                                    }
                                    dispatch(
                                      getProvinceNewRequests({
                                        selectedDate1,
                                        selectedDate2,
                                      })
                                    );
                                    dispatch(
                                      avicultureGetRequests({
                                        selectedDate1,
                                        selectedDate2,
                                      })
                                    );
                                    getFileFromApi(roles, id, dispatch);
                                    dispatch(LOADING_END());

                                    // if (r.error) {

                                    // } else {

                                    // }
                                  });
                                }}
                              >
                                رد اطلاعات و پیام به مرغدار
                              </Button>
                            </Grid>
                          </Grid>
                        </Grid>
                      </motion.div>
                    ) : (
                      <Grid
                        container
                        direction="column"
                        alignItems="start"
                        gap={SPACING.SMALL}
                      >
                        <Grid
                          container
                          gap={SPACING.TINY}
                          direction="column"
                          alignItems="start"
                        >
                          <Grid container gap={SPACING.TINY}>
                            <Typography variant="body2" fontWeight="bold">
                              تعداد درخواست کشتار:
                            </Typography>
                            <Typography>
                              {file?.quantity?.toLocaleString()} قطعه
                            </Typography>
                          </Grid>
                          <Grid container gap={SPACING.TINY}>
                            <Typography variant="body2" fontWeight="bold">
                              تعداد باقی مانده از جوجه ریزی:
                            </Typography>
                            <Typography>
                              {file?.hatching?.leftOver?.toLocaleString()} قطعه
                            </Typography>
                          </Grid>
                          {!!showHatchingAllowed && (
                            <Grid
                              container
                              gap={SPACING.TINY}
                              alignItems="start"
                            >
                              {/* <Grid container textAlign="start">
                                <FormControl>
                                  <FormLabel id="demo-row-radio-buttons-group-label">
                                    مرغدار اجازه جوجه ریزی ......
                                  </FormLabel>
                                  <RadioGroup
                                    row
                                    aria-labelledby="demo-row-radio-buttons-group-label"
                                    name="row-radio-buttons-group"
                                    onChange={(event) => {
                                      formik.setFieldValue(
                                        "canHaching",
                                        event.currentTarget.value
                                      );
                                    }}
                                    value={formik.values.canHaching}
                                  >
                                    <FormControlLabel
                                      value="True"
                                      control={<Radio />}
                                      label="دارد"
                                    />
                                    <FormControlLabel
                                      value="False"
                                      control={<Radio />}
                                      label="ندارد"
                                    />
                                  </RadioGroup>
                                  <Grid>
                                    <Typography variant="button">
                                      مرغ دار اجازه جوجه ریزی دارد بدین معناست
                                      که باقی مانده مرغ صفر در نظر گرفته می شود
                                      و مرغ دار اجازه جوجه ریزی برای سالن خود را
                                      خواهد داشت.
                                    </Typography>
                                  </Grid>
                                </FormControl>
                              </Grid> */}
                            </Grid>
                          )}
                        </Grid>
                        <Grid container gap={SPACING.SMALL} xs={12}>
                          <Button
                            fullWidth
                            disabled={buttonState}
                            variant="outlined"
                            color="error"
                            onClick={() => {
                              setisDenyed(true);
                            }}
                          >
                            رد اطلاعات و پیام به مرغدار
                          </Button>
                          <Grid xs={12}>
                            <Button
                              fullWidth
                              disabled={buttonState}
                              variant="outlined"
                              onClick={() => {
                                dispatch(LOADING_START());
                                dispatch(
                                  checkRequestByCity({
                                    key: file?.key,
                                    allow_hatching: formik.values.canHaching,
                                    state: "accept",
                                    role: getRoleFromUrl(),
                                  })
                                ).then((r) => {
                                  getFileFromApi(roles, id, dispatch);
                                  dispatch(LOADING_END());
                                  if (r.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "مشکلی پیش آمده است!",
                                      severity: "error",
                                    });
                                  } else {
                                    if (updateTable) {
                                      updateTable();
                                    }
                                    dispatch(
                                      getProvinceNewRequests({
                                        selectedDate1,
                                        selectedDate2,
                                      })
                                    );
                                    dispatch(
                                      avicultureGetRequests({
                                        selectedDate1,
                                        selectedDate2,
                                      })
                                    );
                                    dispatch(
                                      avicultureRequestsStateProcessService({
                                        selectedDate1,
                                        selectedDate2,
                                      })
                                    );
                                    dispatch(
                                      DRAWER({
                                        right: false,
                                        bottom: false,
                                        content: null,
                                      })
                                    );
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                    if (
                                      getRoleFromUrl() === "ProvinceOperator"
                                    ) {
                                      dispatch(
                                        OPEN_MODAL({
                                          title: "عملیات با موفقیت انجام شد.",
                                          content: (
                                            <Grid
                                              xs={12}
                                              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>
                        </Grid>
                      </Grid>
                    )}
                  </AnimatePresence>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        </TimelineItem>
      )}
    </>
  );
};
CityFileOperations.propTypes = {
  file: PropTypes.object,
};

export default CityFileOperations;
