import {
  Button,
  FormControl,
  FormHelperText,
  InputAdornment,
  InputLabel,
  MenuItem,
  Select,
  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 { useDispatch } from "react-redux";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { ProvinceFinancialSubmitFinancialTransaction } from "../../services/province-financial-submit-financial-transaction";
import { AppContext } from "../../../../contexts/AppContext";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

const ProvinceFinancialSubmitDebtDocument = ({ profileid, walletkey }) => {
  const [documentImages, setDocumentImages] = React.useState([]);
  const [documentImagesBase64, setDocumentImagesBase64] = React.useState([]);

  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

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

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

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

  return (
    <Grid
      className="slaughter-new-request-form"
      container
      gap={SPACING.SMALL}
      direction="column"
      flex="1"
      justifyContent="space-between"
    >
      <Grid container gap={SPACING.SMALL} direction="column">
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">نوع تراکنش</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="transactionType"
            label="نوع تراکنش"
            value={formik.values.transactionType}
            error={
              formik.touched.transactionType
                ? Boolean(formik.errors.transactionType)
                : null
            }
            onChange={(e) => {
              formik.setFieldValue("transactionType", e.target.value);
            }}
            onBlur={formik.handleBlur}
          >
            <MenuItem value={"debtor"}>بدهی</MenuItem>
            <MenuItem value={"penalty"}>جریمه</MenuItem>
            <MenuItem value={"deposit"}>واریز</MenuItem>
          </Select>
          <FormHelperText>
            {formik.touched.transactionType &&
            Boolean(formik.errors.transactionType)
              ? formik.errors.transactionType
              : null}
          </FormHelperText>
        </FormControl>

        <NumberInput
          allowLeadingZeros
          thousandSeparator=","
          fullWidth
          id="debt"
          label="مبلغ بدهی را وارد کنید"
          variant="outlined"
          InputLabelProps={{
            shrink: true,
          }}
          InputProps={{
            endAdornment: (
              <InputAdornment position="start">ریال</InputAdornment>
            ),
          }}
          value={formik.values.debt}
          error={formik.touched.debt ? Boolean(formik.errors.debt) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.debt && Boolean(formik.errors.debt)
              ? formik.errors.debt
              : null
          }
        />

        {/* <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={"بارگذاری سند"}
        />

        <Button
          disabled={!formik.isValid}
          fullWidth
          variant="contained"
          onClick={() => {
            dispatch(LOADING_START());
            dispatch(
              ProvinceFinancialSubmitFinancialTransaction({
                wallet_receive: walletkey,
                type: formik.values.transactionType,
                cost: formik.values.debt,
                user_id: profileid,
                image: documentImagesBase64,
              })
            ).then((r) => {
              dispatch(LOADING_END());
              if (r.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "مشکلی پیش آمده است!",
                  severity: "error",
                });
              } else {
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );

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

export default ProvinceFinancialSubmitDebtDocument;

ProvinceFinancialSubmitDebtDocument.propTypes = {
  profileid: PropTypes.any,
  walletkey: PropTypes.any,
};
