import {
  Button,
  IconButton,
  InputAdornment,
  TextField,
  Typography,
} from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { BankAccountInformation } from "../bank-account-information/BankAccountInformation";
import ImgUploader from "../../../../components/img-uploader/ImgUploader";
import { slaughterGetPayFactorRequestsService } from "../../../slaughter-house/services/slaughter-get-pay-factor-requests";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { slaughterGetPaiedFactorsService } from "../../../slaughter-house/services/slaughter-get-paied-factors";
import { slaughterUpdatePayProvinceFactor } from "../../services/slaughterUpdatePayProvinceFactor";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { slaughterPayProvinceFactor } from "../../services/slaughterPayProvinceFactor";
import { useDispatch } from "react-redux";
import { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom";

export const SlaughterPayFactorManual = ({
  provinceFactorToKillHouse,
  price,
  isRejected,
  barCode,
  killHouseFactorToProvince,
}) => {
  const dispatch = useDispatch();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  const [openNotif] = useContext(AppContext);
  const [inputValues, setInputValues] = useState([
    { id: 11, paymentId: "", doc: "", amount: "" },
    { id: 22, paymentId: "", doc: "", amount: "" },
  ]);

  const totalAmount = inputValues.reduce(
    (acc, item) => acc + Number(item.amount),
    0
  );

  return (
    <Grid container>
      <Grid container alignItems={"start"}>
        <Grid>
          <BankAccountInformation
            card={provinceFactorToKillHouse?.card}
            shaba={provinceFactorToKillHouse?.shaba}
            info={provinceFactorToKillHouse?.nameOfBankUser}
            price={price}
            priceText={provinceFactorToKillHouse?.totalAmountChar}
            bankName={provinceFactorToKillHouse?.bankName}
            bankUser={provinceFactorToKillHouse?.nameOfBankUser}
          />
        </Grid>
        <Grid
          container
          direction="column"
          gap={SPACING.SMALL}
          mt={SPACING.SMALL}
          pl={SPACING.SMALL}
        >
          <Grid>
            <Grid container gap={SPACING.MEDIUM}>
              <Grid>
                <Typography variant={"body2"} color="primary">
                  مبلغ قابل پرداخت
                </Typography>
                <Typography variant={"body2"} color="error" fontWeight={"bold"}>
                  {totalAmount
                    ? (Number(price) - totalAmount)?.toLocaleString()
                    : Number(price)?.toLocaleString()}{" "}
                  ریال
                </Typography>
              </Grid>
              <Grid>
                <Typography variant={"body2"} color="primary">
                  شناسه پرداخت
                </Typography>
                <Typography variant={"body2"} color="error" fontWeight={"bold"}>
                  {barCode}
                </Typography>
              </Grid>
            </Grid>
            <Grid>
              <Typography variant={"body1"} fontWeight={"bold"}>
                {/* {info} */}
              </Typography>
            </Grid>
          </Grid>
          <Grid
            container
            direction="column"
            alignItems="center"
            gap={SPACING.SMALL}
          >
            {inputValues
              .sort((a, b) => a.id - b.id)
              .map((item, i) => {
                return (
                  <Grid
                    key={i}
                    container
                    alignItems="center"
                    gap={SPACING.SMALL}
                  >
                    <Typography>{i + 1}.</Typography>
                    <Grid>
                      <NumberInput
                        allowLeadingZeros
                        thousandSeparator=","
                        InputProps={{
                          endAdornment: (
                            <InputAdornment position="end">ریال</InputAdornment>
                          ),
                        }}
                        label="مبلغ پرداخت شده"
                        value={item.amount}
                        onChange={(e) => {
                          setInputValues((prevState) => {
                            const idToRemove = item.id;
                            const filteredArray = prevState.filter(
                              (obj) => obj.id !== idToRemove
                            );
                            return [
                              ...filteredArray,
                              {
                                ...item,
                                id: item.id,
                                amount: e.target.value,
                              },
                            ];
                          });
                        }}
                      />
                    </Grid>
                    <Grid>
                      <TextField
                        label="شناسه واریز"
                        value={item.paymentId}
                        onChange={(e) => {
                          setInputValues((prevState) => {
                            const idToRemove = item.id;
                            const filteredArray = prevState.filter(
                              (obj) => obj.id !== idToRemove
                            );
                            return [
                              ...filteredArray,
                              {
                                ...item,
                                id: item.id,
                                paymentId: e.target.value,
                              },
                            ];
                          });
                        }}
                      />
                    </Grid>
                    <Grid>
                      <ImgUploader />
                    </Grid>
                    <Grid>
                      <IconButton
                        aria-label="delete"
                        color="error"
                        onClick={() => {
                          setInputValues((prevState) => {
                            const idToRemove = item.id;
                            const filteredArray = prevState.filter(
                              (obj) => obj.id !== idToRemove
                            );
                            return filteredArray;
                          });
                        }}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Grid>
                  </Grid>
                );
              })}

            <Button
              color="primary"
              aria-label="Add"
              onClick={() => {
                setInputValues((prevState) => [
                  ...prevState,
                  { id: Date.now() },
                ]);
              }}
            >
              <AddIcon />
              افزودن سند
            </Button>
            <Grid>
              <Button
                variant={"contained"}
                onClick={() => {
                  dispatch(LOADING_START());

                  const reqCallback = (r) => {
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      dispatch(
                        slaughterGetPayFactorRequestsService({
                          selectedDate1,
                          selectedDate2,
                        })
                      );
                      dispatch(
                        slaughterGetPaiedFactorsService({
                          selectedDate1,
                          selectedDate2,
                        })
                      );
                      dispatch(
                        DRAWER({
                          right: false,
                          bottom: false,
                          top: false,
                          content: null,
                          size: null,
                        })
                      );
                      // getFileFromApi(roles, id, dispatch);
                      // setFactorPaymentImages([]);
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                    dispatch(LOADING_END());
                  };
                  if (isRejected) {
                    const req = {
                      //   key: killHouseFactorToProvince.factorKey,
                      // factor_image: factorPaymentImg,
                      //   payment_code: formik.values.paymentId,
                      role: getRoleFromUrl(),
                    };
                    dispatch(slaughterUpdatePayProvinceFactor(req)).then(
                      reqCallback
                    );
                  } else {
                    const req = {
                      //   key: factorKey,
                      // factor_image: factorPaymentImg,
                      //   payment_code: formik.values.paymentId,
                      role: getRoleFromUrl(),
                    };
                    dispatch(slaughterPayProvinceFactor(req)).then(reqCallback);
                  }
                }}
              >
                ثبت
              </Button>
            </Grid>
          </Grid>
        </Grid>
      </Grid>
    </Grid>
  );
};
