import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  FormControlLabel,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import {
  provinceSubSectorCitySharesGeyCitisService,
  provinceSubSectorCitySharesWageDetailsEditDepositService,
  provinceSubSectorCitySharesWageDetailsSubmitDepositService,
  provinceSubSectorStewardSharesGeyVetFarmsService,
  provinceSubSectorVetFarmSharesGeyVetFarmsService,
} from "../../services/province-sub-sectors-services";
import { useDispatch } from "react-redux";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { AppContext } from "../../../../contexts/AppContext";
import { resizeImage } from "../../../../utils/resizeImage";
import ShowImage from "../../../../components/show-image/ShowImage";

export const ProvinceSubSectorCitySharesDepositsSubmit = ({
  updateTable,
  isEdit,
  item,
  type,
}) => {
  const [openNotif] = useContext(AppContext);
  const [profileImages, setProfileImages] = useState([]);
  const [receiverOptions, setReceiverOptions] = useState([]);
  const dispatch = useDispatch();
  useEffect(() => {
    if (!isEdit) {
      if (type === "city") {
        dispatch(provinceSubSectorCitySharesGeyCitisService()).then((r) => {
          setReceiverOptions(r.payload.data);
        });
      } else if (type === "vet") {
        dispatch(provinceSubSectorVetFarmSharesGeyVetFarmsService()).then(
          (r) => {
            setReceiverOptions(r.payload.data);
          }
        );
      } else {
        dispatch(provinceSubSectorStewardSharesGeyVetFarmsService()).then(
          (r) => {
            setReceiverOptions(r.payload.data);
          }
        );
      }
    }
  }, []);

  const formik = useFormik({
    initialValues: {
      from_account: isEdit ? item?.fromAccount : "",
      to_account: isEdit ? item?.toAccount : "",
      receiver_key: isEdit ? "check" : "",
      type: isEdit ? item?.type : "online",
      amount: isEdit ? item?.amount : "",
      transaction_image: isEdit ? [item?.image] : "",
      selectedDate1: isEdit
        ? item?.createDate
        : moment(new Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      from_account: Yup.string().required("این فیلد اجباری است!"),
      // .matches(/^\d{16}$/, "شماره حساب باید 16 رقمی باشد!"),
      to_account: Yup.string().required("این فیلد اجباری است!"),
      amount: Yup.number()
        .required("این فیلد اجباری است!")
        .typeError("لطفا عدد وارد کنید!"),
      receiver_key: Yup.string().required("این فیلد اجباری است!"),
      transaction_image: Yup.array().required("این فیلد اجباری است!"),
    }),
  });

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList.length === 0) {
      formik.setFieldValue("transaction_image", []);
      setProfileImages([]);
    } else {
      const resizedImagesPromises = imageList.map(
        (image) =>
          new Promise((resolve) => {
            const file = image.file;
            resizeImage(file, (resizedDataUrl) => {
              resolve(fixBase64(resizedDataUrl));
            });
          })
      );

      Promise.all(resizedImagesPromises).then((resizedImages) => {
        formik.setFieldValue("transaction_image", resizedImages);
        setProfileImages(imageList);
      });
    }
  };
  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid container xs={12} direction="column" gap={1}>
      <Grid item xs={12}>
        {!isEdit && (
          <Autocomplete
            style={{ width: "100%" }}
            options={
              receiverOptions
                ? receiverOptions.map((i) => ({
                    id: i.key,
                    label:
                      type === "city"
                        ? `${i.unitName} / ${i.user?.fullname} `
                        : `${i.user?.fullname} / ${i.user?.mobile} `,
                    item: i,
                  }))
                : []
            }
            value={formik.values.guild}
            onChange={(e, item) => {
              formik.setFieldValue("receiver_key", item?.id);
              formik.validateForm();
            }}
            error={
              formik.touched.receiver_key && Boolean(formik.errors.receiver_key)
            }
            helperText={
              formik.touched.receiver_key && formik.errors.receiver_key
            }
            getOptionLabel={(option) => option.label}
            renderInput={(params) => (
              <TextField
                {...params}
                label={
                  type === "city"
                    ? "انتخاب تعاونی"
                    : type === "vet"
                    ? "انتخاب دامپزشک"
                    : "انتخاب صنف پروتئینی"
                }
                variant="outlined"
              />
            )}
          />
        )}
      </Grid>

      <Grid>
        <DatePicker
          label="تاریخ واریز"
          id="date"
          renderInput={(params) => <TextField {...params} fullWidth />}
          value={formik.values.selectedDate1}
          onChange={(e) => {
            formik.setFieldValue(
              "selectedDate1",
              moment(e).format("YYYY-MM-DD hh:mm:ss")
            );
          }}
        />
      </Grid>

      <Grid>
        <TextField
          fullWidth
          id="amount"
          value={formik.values.amount}
          error={formik.touched.amount ? Boolean(formik.errors.amount) : null}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.amount && Boolean(formik.errors.amount)
              ? formik.errors.amount
              : null
          }
          label="مبلغ"
          variant="outlined"
        />
      </Grid>

      <Grid>
        <TextField
          fullWidth
          id="from_account"
          value={formik.values.from_account}
          error={
            formik.touched.from_account
              ? Boolean(formik.errors.from_account)
              : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.from_account && Boolean(formik.errors.from_account)
              ? formik.errors.from_account
              : null
          }
          label="حساب مبدا"
          variant="outlined"
        />
      </Grid>

      <Grid>
        <TextField
          fullWidth
          id="to_account"
          value={formik.values.to_account}
          error={
            formik.touched.to_account ? Boolean(formik.errors.to_account) : null
          }
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          helperText={
            formik.touched.to_account && Boolean(formik.errors.to_account)
              ? formik.errors.to_account
              : null
          }
          label="حساب مقصد"
          variant="outlined"
        />
      </Grid>

      <RadioGroup
        row
        id="type"
        name="type"
        value={formik.values.type}
        onChange={formik.handleChange}
      >
        <FormControlLabel value="online" control={<Radio />} label="آنلاین" />
        <FormControlLabel value="bank" control={<Radio />} label="توسط بانک" />
      </RadioGroup>

      <ImageUpload
        onChange={factorPaymentHandler}
        images={profileImages}
        maxNumber={1}
        title={"تصویر تراکنش"}
      />

      {isEdit && formik.values.transaction_image[0]?.includes("https") && (
        <Grid container justifyContent="center" alignItems="center" xs={12}>
          <ShowImage src={formik.values.transaction_image[0]} size="100px" />
        </Grid>
      )}

      <Button
        variant="contained"
        disabled={!formik.isValid}
        fullWidth
        onClick={() => {
          if (isEdit) {
            let req = {
              transaction_key: item?.key,
              image: formik.values.transaction_image[0]?.includes("https")
                ? null
                : formik.values.transaction_image[0],
              date: formik.values.selectedDate1,
              from_account: formik.values.from_account,
              to_account: formik.values.to_account,
              type: formik.values.type,
              amount: parseInt(formik.values.amount),
            };
            req = Object.fromEntries(
              Object.entries(req).filter(([_, value]) => value !== null)
            );
            dispatch(
              provinceSubSectorCitySharesWageDetailsEditDepositService(req)
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                updateTable();
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
              }
            });
          } else {
            let req = {
              role_key: formik.values.receiver_key,
              role_type: type,
              image: formik.values.transaction_image[0],
              date: formik.values.selectedDate1,
              from_account: formik.values.from_account,
              to_account: formik.values.to_account,
              type: formik.values.type,
              amount: parseInt(formik.values.amount),
            };
            req = Object.fromEntries(
              Object.entries(req).filter(([_, value]) => value !== null)
            );
            dispatch(
              provinceSubSectorCitySharesWageDetailsSubmitDepositService(req)
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
                updateTable();
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
              }
            });
          }
        }}
      >
        ثبت
      </Button>
    </Grid>
  );
};
