import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  TextField,
  Autocomplete,
  Button,
  FormHelperText,
  Select,
  InputLabel,
  FormControl,
  MenuItem,
} from "@mui/material";
import { useFormik } from "formik";
import { Yup } from "../../../../lib/yup/yup";
import { useDispatch } from "react-redux";
import { provinceGetBuyersService } from "../../services/province-get-buyers";
import { AppContext } from "../../../../contexts/AppContext";
import {
  provinceWagePaymentCreateTransactionService,
  provinceWagePaymentEditTransactionService,
} from "../../services/province-wage-payment-create-transaction-service";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";

export const ProvinceWagePaymentCreateTransaction = ({
  fetchApiData,
  item,
  isEdit,
}) => {
  const [killHouses, setKillHouses] = useState([]);
  const dispatch = useDispatch();

  const [openNotif] = useContext(AppContext);
  const [profileImages, setProfileImages] = useState([]);

  const [, , selectedDate1, setSelectedDate1] = useContext(AppContext);

  useEffect(() => {
    if (item?.date) {
      setSelectedDate1(moment(item?.date).format("YYYY-MM-DD HH:MM"));
    }
  }, []);

  const validationSchema = Yup.object({
    kill_house_key: Yup.string().required("کشتارگاه را انتخاب کنید!"),
    description: Yup.string(),
    amount: Yup.number().required("مبلغ را وارد کنید!"),
    image: Yup.string(),
    transaction_type: Yup.string().required("نوع تراکنش را وارد کنید!"),
    refId: Yup.string().required("شناسه ارجاع را وارد کنید!"),
    orderId: Yup.string().required("شناسه سفارش را وارد کنید!"),
    cardHolderPan: Yup.string().required("کارت بانکی را وارد کنید!"),
    union_share: Yup.number().required("سهم اتحادیه را وارد کنید!"),
    company_share: Yup.number().required("سهم شرکت را وارد کنید!"),
    guilds_share: Yup.number().required("سهم اصناف را وارد کنید!"),
    other_share: Yup.number().required("سایر سهم ها را وارد کنید!"),
  });

  const formik = useFormik({
    initialValues: {
      kill_house_key: isEdit ? "test" : "",
      description: item?.description ? item?.description : "",
      amount: item?.amount ? item?.amount : "",
      transaction_type: item?.transactionType ? item?.transactionType : "",
      refId: item?.refId ? item?.refId : "",
      orderId: item?.orderId ? item?.orderId : "",
      cardHolderPan: item?.cardHolderPan ? item?.cardHolderPan : "",
      union_share: item?.unionShare ? item?.unionShare : 0,
      company_share: item?.companyShare ? item?.companyShare : 0,
      guilds_share: item?.guildsShare ? item?.guildsShare : 0,
      other_share: item?.otherShare ? item?.otherShare : 0,
      image: "",
    },
    validationSchema,
  });

  useEffect(() => {
    if (!isEdit) {
      dispatch(
        provinceGetBuyersService({ dispenser: true, role: getRoleFromUrl() })
      ).then((r) => {
        setKillHouses(r.payload.data);
      });
    }
  }, []);

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

  const factorPaymentHandler = (imageList, addUpdateIndex) => {
    if (imageList[0]) {
      formik.setFieldValue("image", fixBase64(imageList[0]?.data_url));
    }
    setProfileImages(imageList);
  };

  return (
    <Grid container spacing={2}>
      <Grid item xs={12}>
        <DatePicker
          label="تاریخ تراکنش"
          id="date"
          renderInput={(params) => <TextField {...params} />}
          value={selectedDate1}
          onChange={(e) => {
            setSelectedDate1(moment(e).format("YYYY-MM-DD HH:MM:SS"));
          }}
        />
      </Grid>

      {!isEdit && (
        <Grid item xs={12}>
          <Autocomplete
            fullWidth
            id="kill_house_key"
            options={killHouses || []}
            getOptionLabel={(option) => option.name}
            onChange={(event, newValue) => {
              formik.setFieldValue("kill_house_key", newValue.key);
            }}
            onBlur={formik.handleBlur}
            renderInput={(params) => (
              <TextField
                {...params}
                label="کشتارگاه"
                variant="outlined"
                error={
                  formik.touched.kill_house_key &&
                  Boolean(formik.errors.kill_house_key)
                }
                helperText={
                  formik.touched.kill_house_key && formik.errors.kill_house_key
                }
              />
            )}
          />
        </Grid>
      )}

      <Grid item xs={12}>
        <FormControl fullWidth>
          <InputLabel id="demo-simple-select-label">نوع تراکنش</InputLabel>
          <Select
            labelId="demo-simple-select-label"
            id="transaction_type"
            label="نوع تراکنش"
            value={formik.values.transaction_type}
            error={
              formik.touched.transaction_type
                ? Boolean(formik.errors.transaction_type)
                : null
            }
            onChange={(e) => {
              formik.setFieldValue("transaction_type", e.target.value);
            }}
            onBlur={formik.handleBlur}
          >
            <MenuItem value={"wage-gateway-manual"}>دستی</MenuItem>
            <MenuItem value={"wage-gateway-auto"}>آنلاین</MenuItem>
          </Select>
          <FormHelperText>
            {formik.touched.transaction_type &&
            Boolean(formik.errors.transaction_type)
              ? formik.errors.transaction_type
              : null}
          </FormHelperText>
        </FormControl>
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="refId"
          name="refId"
          label="شماره پیگیری"
          value={formik.values.refId}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={formik.touched.refId && Boolean(formik.errors.refId)}
          helperText={formik.touched.refId && formik.errors.refId}
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="orderId"
          name="orderId"
          label="شماره درخواست"
          value={formik.values.orderId}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={formik.touched.orderId && Boolean(formik.errors.orderId)}
          helperText={formik.touched.orderId && formik.errors.orderId}
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="cardHolderPan"
          name="cardHolderPan"
          label="کارت بانکی"
          value={formik.values.cardHolderPan}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={
            formik.touched.cardHolderPan && Boolean(formik.errors.cardHolderPan)
          }
          helperText={
            formik.touched.cardHolderPan && formik.errors.cardHolderPan
          }
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="amount"
          name="amount"
          label="مبلغ تراکنش"
          value={formik.values.amount}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={formik.touched.amount && Boolean(formik.errors.amount)}
          helperText={formik.touched.amount && formik.errors.amount}
        />
      </Grid>

      <Grid item xs={12}>
        <TextField
          fullWidth
          id="union_share"
          name="union_share"
          label="سهم اتحادیه"
          value={formik.values.union_share}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={
            formik.touched.union_share && Boolean(formik.errors.union_share)
          }
          helperText={formik.touched.union_share && formik.errors.union_share}
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="company_share"
          name="company_share"
          label="سهم شرکت"
          value={formik.values.company_share}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={
            formik.touched.company_share && Boolean(formik.errors.company_share)
          }
          helperText={
            formik.touched.company_share && formik.errors.company_share
          }
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="guilds_share"
          name="guilds_share"
          label="سهم اصناف"
          value={formik.values.guilds_share}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={
            formik.touched.guilds_share && Boolean(formik.errors.guilds_share)
          }
          helperText={formik.touched.guilds_share && formik.errors.guilds_share}
        />
      </Grid>
      <Grid item xs={12}>
        <TextField
          fullWidth
          id="other_share"
          name="other_share"
          label="سهم دیگر"
          value={formik.values.other_share}
          onChange={formik.handleChange}
          onBlur={formik.handleBlur}
          variant="outlined"
          error={
            formik.touched.other_share && Boolean(formik.errors.other_share)
          }
          helperText={formik.touched.other_share && formik.errors.other_share}
        />
      </Grid>

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

      <Grid item xs={12} justifyContent="center">
        <ImageUpload
          onChange={factorPaymentHandler}
          images={profileImages}
          maxNumber={1}
          title={"سند"}
        />
        {item?.image && !profileImages.length && (
          <img
            src={item?.image}
            alt="سند"
            style={{ width: "150px", borderRadius: "5px" }}
          />
        )}
      </Grid>

      <Grid item xs={12}>
        <Button
          variant="contained"
          disabled={!formik.isValid}
          fullWidth
          onClick={() => {
            if (
              parseInt(formik.values.union_share) +
                parseInt(formik.values.company_share) +
                parseInt(formik.values.other_share) +
                parseInt(formik.values.guilds_share) !==
              parseInt(formik.values.amount)
            ) {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "مجموع سهم ها باید با مبلغ تراکنش برابر باشد!",
                severity: "error",
              });
              return;
            } else {
              if (isEdit) {
                dispatch(
                  provinceWagePaymentEditTransactionService({
                    transaction_key: item?.key,
                    image: formik.values.image,
                    description: formik.values.description.length
                      ? formik.values.description
                      : null,
                    amount: formik.values.amount,
                    transaction_type: formik.values.transaction_type,
                    refId: formik.values.refId,
                    orderId: formik.values.orderId,
                    cardHolderPan: formik.values.cardHolderPan,
                    union_share: formik.values.union_share,
                    company_share: formik.values.company_share,
                    guilds_share: formik.values.guilds_share,
                    other_share: formik.values.other_share,
                    date: selectedDate1,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                    return;
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                    fetchApiData(1);
                    dispatch(
                      DRAWER({
                        right: false,
                        bottom: false,
                        content: null,
                      })
                    );
                  }
                });
              } else {
                dispatch(
                  provinceWagePaymentCreateTransactionService({
                    kill_house_key: formik.values.kill_house_key,
                    image: formik.values.image,
                    description: formik.values.description.length
                      ? formik.values.description
                      : null,
                    amount: formik.values.amount,
                    transaction_type: formik.values.transaction_type,
                    refId: formik.values.refId,
                    orderId: formik.values.orderId,
                    cardHolderPan: formik.values.cardHolderPan,
                    union_share: formik.values.union_share,
                    company_share: formik.values.company_share,
                    guilds_share: formik.values.guilds_share,
                    other_share: formik.values.other_share,
                    date: selectedDate1,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                    return;
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                    fetchApiData(1);
                    dispatch(
                      DRAWER({
                        right: false,
                        bottom: false,
                        content: null,
                      })
                    );
                  }
                });
              }
            }
          }}
        >
          {isEdit ? "ویرایش تراکنش" : "ثبت تراکنش"}
        </Button>
      </Grid>
    </Grid>
  );
};
