import {
  TimelineConnector,
  TimelineContent,
  TimelineDot,
  TimelineItem,
  TimelineOppositeContent,
  TimelineSeparator,
} from "@mui/lab";
import { Button, TextField, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { BankAccountInformation } from "../bank-account-information/BankAccountInformation";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { useDispatch } from "react-redux";
import { PropTypes } from "prop-types";

import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getFileFromApi } from "../../hooks/useRequestFile";
import useUserProfile from "../../../authentication/hooks/useUserProfile";
import { useParams } from "react-router-dom";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterUpdatePayPoultryFactor } from "../../services/slaughterUpdatePayPoultryFactor";
import { slaughterPayPoultryFactor } from "../../services/slaughterPayPoultryFactor";

export const SlaughterPayPoultryFactorForm = ({
  factorKey,
  price,
  provinceFactorToPoultry,
  killHouseFactorToPoultry,
  isRejected,
}) => {
  const [openNotif] = useContext(AppContext);
  const [factorPaymentImages, setFactorPaymentImages] = useState([]);
  const [factorPaymentImg, setFactorPaymentImg] = useState();
  const dispatch = useDispatch();
  const [roles] = useUserProfile();
  const { id } = useParams();

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

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      setFactorPaymentImg(fixBase64(imageList[0]?.data_url));
      formik.setFieldValue(
        "factorPaymentImg",
        fixBase64(imageList[0]?.data_url)
      );
    } else {
      formik.setFieldValue("factorPaymentImg", "");
    }
    setFactorPaymentImages(imageList);
  };

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

  useEffect(() => {
    // fill the form if req is rejected
    if (isRejected) {
      formik.setFieldValue("paymentId", killHouseFactorToPoultry.paymentCode);
    }
  }, []);

  return (
    <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">
              <Grid container gap={SPACING.SMALL}>
                <Typography variant="body2" display="flex" gap={SPACING.SMALL}>
                  در این مرحله مبلغ را پرداخت کنید و شناسه پرداخت را وارد و سند
                  آن را بارگذاری کنید.
                </Typography>
              </Grid>
            </TimelineContent>
          </Grid>
        </Grid>
        <Grid container>
          <Grid xs={12} alignItems={"start"}>
            <Grid>
              <BankAccountInformation
                card={provinceFactorToPoultry?.card}
                shaba={provinceFactorToPoultry?.shaba}
                info={provinceFactorToPoultry?.nameOfBankUser}
                price={price}
                priceText={provinceFactorToPoultry?.totalAmountChar}
              />
            </Grid>
            <Grid
              container
              alignItems={"center"}
              gap={SPACING.SMALL}
              mt={SPACING.SMALL}
              pl={SPACING.SMALL}
            >
              <Grid>
                <TextField
                  id="paymentId"
                  label="شناسه پرداخت"
                  variant="outlined"
                  value={formik.values.paymentId}
                  error={
                    formik.touched.paymentId
                      ? Boolean(formik.errors.paymentId)
                      : null
                  }
                  onChange={formik.handleChange}
                  onBlur={formik.handleBlur}
                  helperText={
                    formik.touched.paymentId && Boolean(formik.errors.paymentId)
                      ? formik.errors.paymentId
                      : null
                  }
                />
              </Grid>
              <Grid>
                <ImageUpload
                  onChange={factorPaymentHandler}
                  images={factorPaymentImages}
                  maxNumber={1}
                  title={"بارگذاری سند"}
                />
              </Grid>
              <Grid>
                <Button
                  disabled={!formik.isValid}
                  variant={"contained"}
                  onClick={() => {
                    dispatch(LOADING_START());
                    const reqCallback = (r) => {
                      if (r.error) {
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "مشکلی پیش آمده است!",
                          severity: "error",
                        });
                      } else {
                        getFileFromApi(roles, id, dispatch);
                        setFactorPaymentImages([]);
                        formik.setFieldValue("paymentId", "");
                        openNotif({
                          vertical: "top",
                          horizontal: "center",
                          msg: "عملیات با موفقیت انجام شد.",
                          severity: "success",
                        });
                      }
                      dispatch(LOADING_END());
                    };

                    if (isRejected) {
                      const req = {
                        key: killHouseFactorToPoultry.factorKey,
                        factor_image: factorPaymentImg,
                        payment_code: formik.values.paymentId,
                        role: getRoleFromUrl(),
                      };
                      dispatch(slaughterUpdatePayPoultryFactor(req)).then(
                        reqCallback
                      );
                    } else {
                      const req = {
                        key: factorKey,
                        factor_image: factorPaymentImg,
                        payment_code: formik.values.paymentId,
                        role: getRoleFromUrl(),
                      };
                      dispatch(slaughterPayPoultryFactor(req)).then(
                        reqCallback
                      );
                    }
                  }}
                >
                  ثبت
                </Button>
              </Grid>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </TimelineItem>
  );
};
SlaughterPayPoultryFactorForm.propTypes = {
  factorKey: PropTypes.string,
  price: PropTypes.any,
  provinceFactorToPoultry: PropTypes.any,
  killHouseFactorToPoultry: PropTypes.any,
  isRejected: PropTypes.any,
};
