import React, {
  useContext,
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
} from "react";
import axios from "axios";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import { Button, TextField, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import {
  CLOSE_MODAL,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { slaughterInventoryFinalSubmitService } from "../../../slaughter-house/services/slaughter-inventory-final-submit";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { StewardShowAllocationsOperations } from "../steward-show-allocations-operations/StewardShowAllocationsOperations";
import { getAllocationType } from "../../../../utils/getAllocationType";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
// import { format } from "date-fns-jalali";

export const StewardShowAllocations = forwardRef(
  ({ type, handleUpdate, priceInfo, remainWeight }, ref) => {
    const dispatch = useDispatch();
    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);
    }, []);

    const handleTextChange = (event) => {
      setTextValue(event.target.value);
      8;
    };

    const [data, setData] = useState([]);
    const [totalRows, setTotalRows] = useState(0);
    const [perPage, setPerPage] = useState(10);
    const [textValue, setTextValue] = useState("");
    const [page, setPage] = useState(1);
    const [tableData, setTableData] = useState([]);
    const [openNotif] = useContext(AppContext);

    const fetchApiData = async (pageParam = 1) => {
      try {
        dispatch(LOADING_START());
        const response = await axios.get(
          `steward-allocation/?role=${getRoleFromUrl()}${
            checkPathStartsWith("steward")
              ? `&role_key=${selectedSubUser?.key}`
              : ""
          }&search=filter&value=${textValue}${
            type !== "not_entered"
              ? `&date1=${selectedDate1}&date2=${selectedDate2}`
              : ""
          }&page=${pageParam}&page_size=${perPage}${
            type ? "&type=" + type : ""
          }`
        );
        dispatch(LOADING_END());
        setData(response.data.results || []);
        setTotalRows(response.data.count || 0);
      } catch (err) {
        dispatch(LOADING_END());
        console.error("Error fetching allocations:", err);
      }
    };

    const updateTable = () => {
      fetchApiData(1);
    };

    useImperativeHandle(ref, () => ({
      updateTable,
    }));

    const handlePageChange = (newPage) => {
      fetchApiData(newPage);
      setPage(newPage);
    };

    const getAllocationData = (item) => {
      let typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`;
      switch (item?.allocationType) {
        case "steward_killhouse":
          typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`;
          break;
        case "steward_steward":
          typeText = `${item?.toStewards?.name} - ${item?.toStewards?.user?.fullname} (${item?.toStewards?.user?.mobile})`;
          break;
        case "steward_guild":
          typeText = `${item?.toGuilds?.guildsName} - ${item?.toGuilds?.user?.fullname} (${item?.toGuilds?.user?.mobile})`;
          break;
        case "ColdHouse":
          typeText = `${item?.toColdHouse?.name}`;
          break;
        case "killhouse_steward":
          typeText = `${item?.toStewards?.name || "-"} - ${
            item?.toStewards?.user?.fullname || "-"
          } (${item?.toStewards?.user?.mobile || "-"})`;
          break;
        case "killhouse_guild":
          typeText = `${item?.toGuilds?.guildsName || "-"} - ${
            item?.toGuilds?.user?.fullname || "-"
          } (${item?.toGuilds?.user?.mobile || "-"})`;
          break;
        default:
          typeText = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`;
          break;
      }
      return typeText;
    };

    const getSellerName = (item) => {
      let type = "";
      switch (item?.allocationType) {
        case "steward_guild":
        case "steward_steward":
          type = `${!item?.stewards ? "-" : item?.stewards?.user?.fullname} (${
            item?.stewards?.user?.mobile
          })`;
          break;
        case "killhouse_steward":
          type = `${!item?.killHouse ? "-" : item?.killHouse?.name} (${
            item?.killHouse?.killHouseOperator?.user?.fullname
          } - ${item?.killHouse?.killHouseOperator?.user?.mobile})`;
          break;
        case "killhouse_guild":
          type = `${!item?.killHouse ? "-" : item?.killHouse?.name} (${
            item?.killHouse?.killHouseOperator?.user?.fullname
          } - ${item?.killHouse?.killHouseOperator?.user?.mobile})`;
          break;
        default:
          type = `${!item?.steward ? "-" : item?.steward?.user?.fullname} (${
            item?.steward?.user?.mobile
          })`;
          break;
      }
      return type;
    };

    const handlePerRowsChange = (perRows) => {
      setPerPage(perRows);
      setPage(1);
    };

    const getLastItem = () => {
      if (!type || type === "not_entered") {
        return ["عملیات"];
      } else {
        return [];
      }
    };
    const getRegCodeItemData = (item) => {
      if (type === "not_entered") {
        return [];
      } else {
        return [
          item?.loggedRegistrationCode ? item.loggedRegistrationCode : "-",
          item?.registrationCode ? "ارسال شده" : "ارسال نشده",
        ];
      }
    };
    const getRegCodeItemColumns = () => {
      if (type === "not_entered") {
        return [];
      } else {
        return ["کداحراز", "وضعیت کد احراز"];
      }
    };
    const getAprovedItemData = (item) => {
      if (!type) {
        return [item?.receiverRealWeightOfCarcasses?.toLocaleString()];
      } else if (type === "not_entered") {
        return [];
      } else {
        return [
          item?.receiverRealNumberOfCarcasses?.toLocaleString(),
          item?.receiverRealWeightOfCarcasses?.toLocaleString(),
        ];
      }
    };

    const getAprovedItemColumns = () => {
      if (!type) {
        return ["وزن تایید شده"];
      } else if (type === "not_entered") {
        return [];
      } else {
        return ["حجم تایید شده", "وزن تایید شده"];
      }
    };

    useEffect(() => {
      const d = data?.map((item, i) => {
        return [
          page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
          item?.date ? formatTime(item?.date) : "-",
          item?.productionDate ? formatJustDate(item?.productionDate) : "-",
          item?.distributionType === "web"
            ? "سایت"
            : item?.distributionType === "app"
            ? "موبایل"
            : item?.distributionType === "pos"
            ? "پوز"
            : item?.distributionType || "-",
          getAllocationType(item),
          getAllocationData(item),
          getSellerName(item),
          item?.sellType === "exclusive" ? "اختصاصی" : "آزاد",
          item?.amount?.toLocaleString() + " ریال",
          item?.totalAmount?.toLocaleString() + " ریال",
          item?.realWeightOfCarcasses?.toLocaleString(),
          ...getAprovedItemData(item),
          ...getRegCodeItemData(item),
          item?.weightLossOfCarcasses?.toLocaleString(),
          item?.quota === "governmental"
            ? "دولتی"
            : item?.quota === "free"
            ? "آزاد"
            : "-",
          item?.approvedPriceStatus ? "دولتی" : "آزاد",
          item?.receiverState === "accepted"
            ? "تایید شده"
            : item?.receiverState === "rejected"
            ? "رد شده"
            : "در انتظار تایید",
          <StewardShowAllocationsOperations
            key={i}
            item={item}
            updateTable={updateTable}
            handleUpdate={handleUpdate}
            type={type}
            priceInfo={priceInfo}
            remainWeight={remainWeight}
          />,
        ];
      });

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

    useEffect(() => {
      fetchApiData(1);
    }, [dispatch, selectedDate1, selectedDate2, perPage]);

    const handleSubmit = async (event) => {
      event.preventDefault();
      dispatch(LOADING_START());

      try {
        const response = await axios.get(
          `steward-allocation/?role=${getRoleFromUrl()}${
            checkPathStartsWith("steward")
              ? `&role_key=${selectedSubUser?.key}`
              : ""
          }&search=filter&value=${textValue}${
            type !== "not_entered"
              ? `&date1=${selectedDate1}&date2=${selectedDate2}`
              : ""
          }&page=${page}&page_size=${perPage}${type ? "&type=" + type : ""}`
        );
        setData(response.data.results);
        setTotalRows(response.data.count);
        dispatch(LOADING_END());
      } catch (error) {
        console.error("Error fetching data:", error);
        dispatch(LOADING_END());
      }
    };

    return (
      <Grid container justifyContent="start" alignItems="center" xs={12}>
        <Grid
          container
          xs={12}
          justifyContent="start"
          alignItems="center"
          gap={2}
        >
          <Grid
            container
            xs={12}
            justifyContent="start"
            alignItems="center"
            gap={2}
          >
            {type !== "not_entered" && (
              <>
                <Grid>
                  <DatePicker
                    label="از تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField
                        style={{ width: "160px" }}
                        {...params}
                        size="small"
                      />
                    )}
                    value={selectedDate1}
                    onChange={(e) => {
                      setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
                <Grid>
                  <DatePicker
                    label="تا تاریخ"
                    id="date"
                    renderInput={(params) => (
                      <TextField
                        style={{ width: "160px" }}
                        {...params}
                        size="small"
                      />
                    )}
                    value={selectedDate2}
                    onChange={(e) => {
                      setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                    }}
                  />
                </Grid>
              </>
            )}
            <Grid>
              <form onSubmit={handleSubmit}>
                <TextField
                  id="outlined-basic"
                  size="small"
                  label="جستجو"
                  variant="outlined"
                  style={{ width: 250 }}
                  onChange={handleTextChange}
                />
                <Button
                  type="submit"
                  onClick={handleSubmit}
                  endIcon={<RiSearchLine />}
                >
                  جستجو
                </Button>
              </form>
            </Grid>

            {!(type === "entered" || type === "not_entered") && (
              <Button
                variant="outlined"
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "ثبت نهایی",
                      content: (
                        <Grid container gap={SPACING.SMALL}>
                          <Typography>
                            در صورت ثبت نهایی انجام هیچگونه عملیاتی مانند حذف و
                            ویرایش امکان پذیر نمی باشد.
                          </Typography>
                          <Grid
                            container
                            direction="column"
                            gap={SPACING.TINY}
                            width="100%"
                          >
                            <Button
                              fullWidth
                              variant="contained"
                              onClick={() => {
                                dispatch(
                                  slaughterInventoryFinalSubmitService({
                                    steward_allocation_list: data.map(
                                      (item) => item.key
                                    ),
                                  })
                                ).then((r) => {
                                  dispatch(CLOSE_MODAL());
                                  if (r.payload?.error) {
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: r.payload.error,
                                      severity: "error",
                                    });
                                  } else {
                                    updateTable();
                                    handleUpdate?.();
                                    openNotif({
                                      vertical: "top",
                                      horizontal: "center",
                                      msg: "عملیات با موفقیت انجام شد.",
                                      severity: "success",
                                    });
                                  }
                                });
                              }}
                            >
                              تایید
                            </Button>
                            <Button
                              fullWidth
                              color="error"
                              variant="contained"
                              onClick={() => {
                                dispatch(CLOSE_MODAL());
                              }}
                            >
                              لغو
                            </Button>
                          </Grid>
                        </Grid>
                      ),
                    })
                  );
                }}
              >
                تایید نهایی (یکجا)
              </Button>
            )}
          </Grid>
        </Grid>

        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "تاریخ ثبت",
            "تاریخ تولید گوشت",
            "ثبت شده",
            "نوع تخصیص",
            "مشخصات خریدار",
            "مشخصات فروشنده",
            "نوع فروش",
            "قیمت هر کیلو",
            "قیمت کل",
            "وزن تخصیصی",
            ...getAprovedItemColumns(),
            ...getRegCodeItemColumns(),
            "افت وزن(کیلوگرم)",
            "سهمیه",
            "نوع فروش",
            "وضعیت",
            ...getLastItem(),
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title={
            type === "entered"
              ? "وارد شده به انبار"
              : type === "not_entered"
              ? "در انتظار ورود"
              : "تخصیصات صورت گرفته"
          }
        />
      </Grid>
    );
  }
);

StewardShowAllocations.displayName = "StewardShowAllocations";
