import React, { useContext, useEffect, useState } from "react";
import { Grid, Button, TextField, Typography, IconButton } from "@mui/material";
import { SimpleTable } from "../../../../components/simple-table/SimpleTable";
import { useFormik } from "formik";
import * as Yup from "yup";
import { AppContext } from "../../../../contexts/AppContext";
import { useDispatch } from "react-redux";
import {
  vetFarmReturnAggregateBars,
  vetFarmSubmitAggregateBars,
} from "../../services/vet-farm-submit-aggegate-bars";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import DeleteIcon from "@mui/icons-material/Delete";
import { vetFarmDeleteAggregateBarService } from "../../services/vet-farm-delete-aggregate-bar";

export const VetFarmAggregateBars = ({
  bars,
  updateTable,
  canReturn,
  setAggregates,
  toShow,
}) => {
  const [tableData, setTableData] = useState([]);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [allBars, setAllBars] = useState(bars);

  useEffect(() => {
    let d;
    if (!toShow || !allBars[0]?.aggregateCode) {
      d = allBars?.map((item, i) => {
        return [
          i + 1,
          item?.barCode,
          item.quantity?.toLocaleString(),
          item?.weightInfo?.weight?.toLocaleString(),
          <IconButton
            color="error"
            key={i}
            disabled={allBars?.length < 3}
            onClick={() => {
              dispatch(
                vetFarmDeleteAggregateBarService({
                  kill_house_request_key: item?.key,
                })
              ).then((r) => {
                if (r.payload.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: r.payload.error,
                    severity: "error",
                  });
                } else {
                  setAllBars(
                    allBars?.filter((option) => option?.key !== item?.key)
                  );
                  setAggregates([]);
                  updateTable();
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
              });
            }}
          >
            <DeleteIcon />
          </IconButton>,
        ];
      });
    } else {
      d = allBars?.map((item, i) => {
        return [
          i + 1,
          item?.barCode,
          item.quantity?.toLocaleString(),
          item?.weightInfo?.weight?.toLocaleString(),
        ];
      });
    }

    setTableData(d);
  }, [allBars]);

  const formik = useFormik({
    initialValues: {
      clearanceCode: "",
      trafficCode: "",
    },
    validationSchema: Yup.object({
      clearanceCode: Yup.string().required("این فیلد اجباری است!"),
      trafficCode: Yup.string().required("این فیلد اجباری است!"),
    }),
  });

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

  const handleClearanceCodeChange = (event) => {
    const { value } = event.target;
    formik.setFieldValue("clearanceCode", value.toUpperCase());
  };

  const isSubmitButtonVisible =
    (formik.values.clearanceCode && formik.values.trafficCode) ||
    (!formik.values.clearanceCode && !formik.values.trafficCode);

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center">
      <Grid xs={12}>
        <Typography variant="body2">
          خریدار:{" "}
          {`${allBars[0]?.killhouseUser?.name} (${allBars[0]?.killhouseUser?.killHouseOperator?.user?.mobile})`}
        </Typography>
      </Grid>
      <Grid xs={12}>
        <Typography variant="body2">
          مرغدار:{" "}
          {`${allBars[0]?.poultryRequest?.poultry?.unitName} (${allBars[0]?.poultryRequest.poultry?.user?.mobile})`}
        </Typography>
      </Grid>
      <Grid xs={12} mb={1}>
        <Typography variant="body2">
          مجموع حجم بار:{" "}
          {allBars
            ?.reduce((total, obj) => total + obj?.quantity, 0)
            .toLocaleString()}{" "}
          قطعه
        </Typography>
      </Grid>
      <SimpleTable
        data={tableData}
        columns={
          !toShow || !allBars[0]?.aggregateCode
            ? ["ردیف", "کد بار", "تعداد اولیه", "وزن اولیه بار", "عملیات"]
            : ["ردیف", "کد بار", "تعداد اولیه", "وزن اولیه بار"]
        }
      />

      {!toShow && (
        <>
          <Grid
            container
            alignItems="center"
            xs={12}
            mt={1}
            justifyContent="space-between"
            spacing={2}
          >
            <Grid item xs={6}>
              <TextField
                size="small"
                fullWidth
                id="clearanceCode"
                name="clearanceCode"
                label="کد قرنطینه"
                value={formik.values.clearanceCode}
                onChange={handleClearanceCodeChange}
                error={
                  formik.touched.clearanceCode &&
                  Boolean(formik.errors.clearanceCode)
                }
                helperText={
                  formik.touched.clearanceCode && formik.errors.clearanceCode
                }
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                size="small"
                fullWidth
                id="trafficCode"
                name="trafficCode"
                label="کد حمل"
                value={formik.values.trafficCode}
                onChange={formik.handleChange}
                error={
                  formik.touched.trafficCode &&
                  Boolean(formik.errors.trafficCode)
                }
                helperText={
                  formik.touched.trafficCode && formik.errors.trafficCode
                }
              />
            </Grid>
          </Grid>

          <Grid xs={12} mt={1} gap={1}>
            <Button
              disabled={canReturn ? !formik.isValid : !isSubmitButtonVisible}
              fullWidth
              color="primary"
              variant="contained"
              onClick={() => {
                dispatch(
                  vetFarmSubmitAggregateBars({
                    kill_house_requests_list: allBars?.map((item) => item?.key),
                    role: getRoleFromUrl(),
                    code: formik.values.clearanceCode
                      ? formik.values.clearanceCode
                      : null,
                    traffic_code: formik.values.trafficCode
                      ? formik.values.trafficCode
                      : null,
                  })
                ).then((r) => {
                  if (r.payload.error) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: r.payload.error,
                      severity: "error",
                    });
                  } else {
                    dispatch(CLOSE_MODAL());
                    setAggregates([]);
                    updateTable();
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                });
              }}
            >
              {formik.isValid ? "ثبت" : "ثبت اولیه"}
            </Button>

            {canReturn && (
              <Button
                style={{ marginTop: "5px" }}
                fullWidth
                color="error"
                variant="contained"
                onClick={() => {
                  dispatch(
                    vetFarmReturnAggregateBars({
                      kill_house_request_key: allBars[0]?.key,
                      role: getRoleFromUrl(),
                      type: "cancel_aggregate",
                    })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      dispatch(CLOSE_MODAL());
                      setAggregates([]);
                      updateTable();
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              >
                برگشت از ادغام
              </Button>
            )}
          </Grid>
        </>
      )}
    </Grid>
  );
};
