import { Button, Grid, IconButton, TextField } from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import { SPACING } from "../../../../data/spacing";
import { useDispatch, useSelector } from "react-redux";
import {
  CLOSE_MODAL,
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { slaughterGetRequests } from "../../services/salughter-get-requests";
import { useContext, useEffect, useState } from "react";
import { slaughterDeleteRequest } from "../../services/slaughter-delete-request";
import { AppContext } from "../../../../contexts/AppContext";
import { SlaughterNewRequestForm } from "../slaughter-new-request/SlaughterNewRequestForm";
import { formatJustDate } from "../../../../utils/formatTime";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
// import { slaughterPayService } from "../../services/salughter-pay";

export const SlaughterRequests = () => {
  // const [refId, setRefId] = useState();
  const [dataTable, setDataTable] = useState([]);
  const { slaughterRequests } = useSelector((state) => state.slaughterSlice);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  useEffect(() => {
    dispatch(
      slaughterGetRequests({
        selectedDate1,
        selectedDate2,
        role_key: checkPathStartsWith("slaughter")
          ? selectedSubUser?.key || ""
          : "",
      })
    );
  }, [selectedDate1, selectedDate2, selectedSubUser?.key]);

  useEffect(() => {
    const d = slaughterRequests?.map((item, i) => {
      let state;
      if (item.state === "archive") {
        state = "بایگانی شده";
      } else if (item.provinceState === "pending") {
        state = "در انتظار تایید استان";
      } else if (item.provinceState === "accepted") {
        state = "تایید شده توسط استان";
      } else if (item.provinceState === "rejected") {
        state = "رد شده توسط استان";
      }
      return [
        i + 1,
        item.killHouse.name,
        formatJustDate(item?.createDate),
        item.provinceQuantity
          ? item.provinceQuantity.toLocaleString()
          : item.killCapacity?.toLocaleString(),
        item.provinceQuantity ? item.killCapacity?.toLocaleString() : 0,
        item.reciveTime,
        formatJustDate(item?.reciveDate),
        state,
        <IconButton
          key={i}
          aria-label="delete"
          color="error"
          onClick={() => {
            dispatch(
              OPEN_MODAL({
                title: "آیا مطمئن هستید؟",
                content: (
                  <Grid container alignItems="center" justifyContent={"center"}>
                    <Button
                      variant="contained"
                      onClick={() => {
                        dispatch(LOADING_START());
                        dispatch(
                          slaughterDeleteRequest({
                            id: item.id,
                          })
                        ).then((r) => {
                          dispatch(CLOSE_MODAL());
                          dispatch(LOADING_END());
                          if (r.error) {
                            if (r.error.message.includes("403")) {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "این درخواست از سمت استان پذیرفته شده و قابل حذف نمی باشد!",
                                severity: "error",
                              });
                            } else {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "مشکلی پیش آمده است!",
                                severity: "error",
                              });
                            }
                          } else {
                            dispatch(
                              slaughterGetRequests({
                                selectedDate1,
                                selectedDate2,
                                role_key: checkPathStartsWith("slaughter")
                                  ? selectedSubUser?.key || ""
                                  : "",
                              })
                            ).then(() => {
                              openNotif({
                                vertical: "top",
                                horizontal: "center",
                                msg: "عملیات با موفقیت انجام شد.",
                                severity: "success",
                              });
                            });
                          }
                        });
                      }}
                    >
                      تایید
                    </Button>
                    <Button
                      onClick={() => {
                        dispatch(CLOSE_MODAL());
                      }}
                    >
                      لغو
                    </Button>
                  </Grid>
                ),
              })
            );
          }}
        >
          <DeleteIcon />
        </IconButton>,
      ];
    });

    setDataTable(d);
  }, [slaughterRequests]);

  // useEffect(() => {
  //   dispatch(slaughterPayService()).then((r) => {
  //     setRefId(r.payload.data.refId);
  //   });
  // }, []);

  const [tableDataCol] = useState([
    "ردیف",
    "نام کشتارگاه",
    "تاریخ ایجاد درخواست",
    "تعداد درخواست اولیه",
    "تعداد مورد تایید",
    "زمان دریافت",
    "تاریخ درخواستی کشتار",
    "وضعیت",
    "حذف درخواست",
  ]);

  return (
    <>
      <Grid
        xs={12}
        container
        alignItems="center"
        gap={SPACING.SMALL}
        justifyContent="flex-start"
      >
        <Button
          className="new-request-form-button"
          variant={"contained"}
          onClick={() => {
            dispatch(
              DRAWER({
                right: !(window.innerWidth <= 600),
                bottom: window.innerWidth <= 600,
                content: <SlaughterNewRequestForm />,
                title: "ثبت درخواست کشتار",
              })
            );
          }}
        >
          ثبت درخواست کشتار جدید
        </Button>

        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>

        <ResponsiveTable
          title="درخواست های ثبت شده"
          columns={tableDataCol}
          data={dataTable}
          paginated
        />
      </Grid>
    </>
  );
};
