import { Button, TextField, Typography } from "@mui/material";
import { useFormik } from "formik";
import React, { useContext, useEffect } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { SPACING } from "../../../../data/spacing";
import { Yup } from "../../../../lib/yup/yup";
import { fixBase64 } from "../../../../utils/toBase64";
import { PropTypes } from "prop-types";
import Num2persian from "num2persian";
import { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { ProvinceFinancialSubmitNewFinancialDocument } from "../../services/province-financial-submit-financial-document";
import { AppContext } from "../../../../contexts/AppContext";

export const ProvinceFinancialSubmitFinancialDocument = ({
  payable,
  transactionsList,
  userId,
  paymentType,
  userKey,
}) => {
  const [openNotif] = useContext(AppContext);

  const [documentImages, setDocumentImages] = React.useState([]);
  const [documentImagesBase64, setDocumentImagesBase64] = React.useState([]);
  const dispatch = useDispatch();

  const documentImageHandler = (imageList, addUpdateIndex) => {
    setDocumentImages(imageList);
    setDocumentImagesBase64(imageList.map((img) => fixBase64(img.data_url)));
  };

  const formik = useFormik({
    initialValues: {
      paymentId: "",
      description: "",
      // paymentType: "",
    },
    validationSchema: Yup.object({
      paymentId: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی پر کنید!"),
      description: Yup.string()
        .required("این فیلد اجباری است!")
        .typeError("لطفا فیلد را به درستی پر کنید!"),
      //   paymentType: Yup.string()
      //     .required("این فیلد اجباری است!")
      //     .typeError("لطفا فیلد را به درستی پر کنید!"),
    }),
  });

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

  return (
    <Grid
      container
      direction="column"
      display="flex"
      justifyContent="space-between"
    >
      <Grid
        className="slaughter-new-request-form"
        container
        gap={SPACING.SMALL}
        direction="column"
      >
        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            مبلغ:
          </Typography>
          <Typography mr={SPACING.TINY} variant="body2" fontWeight="bold">
            {Math.abs(payable).toLocaleString()}
          </Typography>
        </Grid>

        <Grid display="flex">
          <Typography
            variant="body2"
            mr={SPACING.TINY}
            color={(prop) => prop.palette.grey["A700"]}
          >
            به حروف:
          </Typography>
          <Typography mr={SPACING.TINY} variant="body2" fontWeight="bold">
            {Num2persian(Math.abs(payable))} ریال
          </Typography>
        </Grid>

        <Grid container gap={SPACING.SMALL} direction="column">
          {/* <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">روش پرداخت</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="paymentType"
            label="روش پرداخت"
            value={formik.values.paymentType}
            error={
              formik.touched.paymentType
                ? Boolean(formik.errors.paymentType)
                : null
            }
            onChange={(e) => {
              formik.setFieldValue("paymentType", e.target.value);
            }}
            onBlur={formik.handleBlur}
          >
            <MenuItem value={"shaba"}>شماره شبا: ۱۲۳۴۵۶۷۸۱۲۳۵۶۵۹۹۹۹۹۰</MenuItem>
            <MenuItem value={"account"}>شماره حساب: ۶۰۳۷۹۹۸۷۶۵۶۵۴۳۲۱</MenuItem>
            <MenuItem value={"cart"}>شماره کارت: ۹۶۵۵۴۴۳۳۵۵۴۳۱</MenuItem>
          </Select>
          <FormHelperText>
            {formik.touched.paymentType && Boolean(formik.errors.paymentType)
              ? formik.errors.paymentType
              : null}
          </FormHelperText>
        </FormControl> */}

          <TextField
            fullWidth
            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
            }
          />

          <TextField
            multiline
            rows={4}
            fullWidth
            id="description"
            label="توضیحات"
            variant="outlined"
            value={formik.values.description}
            error={
              formik.touched.description
                ? Boolean(formik.errors.description)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.description && Boolean(formik.errors.description)
                ? formik.errors.description
                : null
            }
          />

          <Typography>پیوست تصویر</Typography>
          <ImageUpload
            id="image"
            onChange={documentImageHandler}
            images={documentImages}
            maxNumber={4}
            title={"بارگذاری سند"}
          />
        </Grid>
      </Grid>
      <Grid>
        <Button
          disabled={!formik.isValid}
          fullWidth
          variant="contained"
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              ProvinceFinancialSubmitNewFinancialDocument({
                cost: Math.abs(payable),
                description: formik.values.description,
                payment_code: formik.values.paymentId,
                image: documentImagesBase64,
                type: paymentType,
                transaction_list: transactionsList,
                user_id: userId,
              })
            ).then((r) => {
              dispatch(LOADING_END());
              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                window.location.reload(false);
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );

                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
    </Grid>
  );
};

ProvinceFinancialSubmitFinancialDocument.propTypes = {
  payable: PropTypes.any,
  transactionsList: PropTypes.any,
  userId: PropTypes.any,
  paymentType: PropTypes.any,
  userKey: PropTypes.any,
};
