import { useContext, useEffect, useRef, useState } from "react";
import { ProvinceDirectBuyOperation } from "../province-direct-buy-operation/ProvinceDirectBuyOperation";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { Grid } from "../../../../components/grid/Grid";
import {
  formatJustDate,
  formatTime,
  formatTimeFull,
} from "../../../../utils/formatTime";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import PdfKillRequest from "../province-settlement-pdf-kill-request/ProvinceSettlementPdfKillRequest";
import {
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Typography,
} from "@mui/material";
import {
  provinceTradePanelMarketRequestAdminOverview,
  provinceTradePanelMarketRequestOverview,
} from "../../services/province-trade-panel-market-request-overview";
import { AppContext } from "../../../../contexts/AppContext";
import { RiFileExcel2Fill } from "react-icons/ri";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceTradePanelMarketRequest = ({
  updateTable,
  setUpdateRef,
}) => {
  const dispatch = useDispatch();
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [openNotif] = useContext(AppContext);
  const [data, setData] = useState([]);
  const [filter, setFilter] = useState("pending");
  const [tableData, setTableData] = useState([]);
  const [overViewData, setOverViewData] = useState([]);
  const [overViewDataList, setOverViewDataList] = useState([]);
  const [overViewDataDashboard, setOverViewDataDashboard] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const isFetching = useRef(false);
  const hasFetchedDashboardApi = useRef(false);
  const isFetchingDashboardApi = useRef(false);
  const hasFetchedOverviewApi = useRef(false);
  const isFetchingOverviewApi = useRef(false);
  const lastOverviewRequestPayload = useRef(null);
  const lastMarketRequestsPayload = useRef(null);
  const isFetchingMarketRequests = useRef(false);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const handlePageChange = (pageNum) => {
    lastMarketRequestsPayload.current = null;
    fetchApiData(pageNum);
    setPage(pageNum);
  };

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

  const fetchDashboardOverview = async (forceFetch = false) => {
    if (!forceFetch && hasFetchedDashboardApi.current) {
      return;
    }

    if (isFetchingDashboardApi.current) {
      return;
    }

    isFetchingDashboardApi.current = true;
    hasFetchedDashboardApi.current = true;

    try {
      const r = await dispatch(
        provinceTradePanelMarketRequestAdminOverview({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
      if (r?.payload?.data) {
        setOverViewDataDashboard(r.payload.data);
      }
    } catch (error) {
      console.error("Error fetching dashboard overview:", error);
      hasFetchedDashboardApi.current = false;
    } finally {
      isFetchingDashboardApi.current = false;
    }
  };

  const fetchMarketOverview = async (forceFetch = false) => {
    const role = getRoleFromUrl();
    const payloadKey = JSON.stringify({ role });

    if (!forceFetch && lastOverviewRequestPayload.current === payloadKey) {
      return;
    }

    if (isFetchingOverviewApi.current) {
      return;
    }

    isFetchingOverviewApi.current = true;
    lastOverviewRequestPayload.current = payloadKey;
    hasFetchedOverviewApi.current = true;

    try {
      const r = await dispatch(
        provinceTradePanelMarketRequestOverview({
          role_key: checkPathStartsWith("slaughter")
            ? selectedSubUser?.key || ""
            : "",
        })
      );
      if (r?.payload?.data) {
        setOverViewData(r.payload.data);
      }
    } catch (error) {
      console.error("Error fetching market overview:", error);
      lastOverviewRequestPayload.current = null;
      hasFetchedOverviewApi.current = false;
    } finally {
      isFetchingOverviewApi.current = false;
    }
  };

  const fetchMarketRequestsData = async (
    pageNumber = page,
    forceFetch = false
  ) => {
    const payload = {
      role: getRoleFromUrl(),
      search: "filter",
      value: "",
      page: pageNumber,
      page_size: perPage,
      type: filter,
    };

    const payloadKey = JSON.stringify(payload);

    if (!forceFetch && lastMarketRequestsPayload.current === payloadKey) {
      return null;
    }

    if (isFetchingMarketRequests.current) {
      return null;
    }

    isFetchingMarketRequests.current = true;
    lastMarketRequestsPayload.current = payloadKey;

    try {
      const response = await axios.get(
        `/market-requests/?role=${payload.role}&search=${
          payload.search
        }&value=${payload.value}&page=${payload.page}&page_size=${
          payload.page_size
        }&type=${payload.type}${
          checkPathStartsWith("slaughter")
            ? `&role_key=${selectedSubUser?.key || ""}`
            : ""
        }`
      );

      setData(response.data.results);
      setTotalRows(response.data.count);
      return response;
    } catch (error) {
      console.error("Error fetching market requests:", error);
      lastMarketRequestsPayload.current = null;
      throw error;
    } finally {
      isFetchingMarketRequests.current = false;
    }
  };

  const fetchApiData = async (
    pageNumber = page,
    forceDashboardFetch = false,
    forceOverviewFetch = false,
    forceMarketRequestsFetch = false
  ) => {
    try {
      dispatch(LOADING_START());

      await fetchMarketRequestsData(pageNumber, forceMarketRequestsFetch);

      fetchDashboardOverview(forceDashboardFetch);

      fetchMarketOverview(forceOverviewFetch);

      dispatch(LOADING_END());
    } catch (error) {
      dispatch(LOADING_END());
      console.error("Error fetching data:", error);
    }
  };

  const parseMarketStateMessage = (messageString) => {
    if (!messageString || typeof messageString !== "string") {
      return null;
    }

    try {
      let jsonString = messageString.trim();
      if (
        (jsonString.startsWith("'") && jsonString.endsWith("'")) ||
        (jsonString.startsWith('"') && jsonString.endsWith('"'))
      ) {
        jsonString = jsonString.slice(1, -1);
      }
      jsonString = jsonString.replace(/'/g, '"');
      const parsed = JSON.parse(jsonString);
      return {
        fullname: parsed?.fullname || "",
        mobile: parsed?.mobile || "",
        date: parsed?.date || "",
      };
    } catch (error) {
      console.error("Error parsing marketStateMessage:", error);
      return null;
    }
  };

  const handleUpdate = async (
    forceDashboardFetch = true,
    forceOverviewFetch = true,
    forceMarketRequestsFetch = true
  ) => {
    if (isFetching.current) return;
    try {
      isFetching.current = true;
      // Reset flags to force fresh data fetch
      hasFetchedDashboardApi.current = false;
      hasFetchedOverviewApi.current = false;
      lastMarketRequestsPayload.current = null;
      lastOverviewRequestPayload.current = null;

      await fetchApiData(
        1,
        forceDashboardFetch,
        forceOverviewFetch,
        forceMarketRequestsFetch
      );

      // Also call parent updateTable to update main trade panel table
      if (updateTable && typeof updateTable === "function") {
        updateTable();
      }
    } finally {
      isFetching.current = false;
    }
  };

  useEffect(() => {
    fetchDashboardOverview(true);
    fetchMarketOverview(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    const d = data?.map((item, i) => {
      const marketStateInfo = parseMarketStateMessage(item?.marketStateMessage);
      const statusText = `${
        item?.marketState === "deleted"
          ? "حذف شده"
          : item?.marketCodeStatus === true &&
            item?.marketFinalAccept === true &&
            !item?.inputMarketCode &&
            item?.marketState === "pending"
          ? "در انتظار ورود کد احراز"
          : item?.marketFinalAccept === false
          ? "در انتظار تایید خریدار"
          : item?.marketState === "pending"
          ? "در انتظار تایید استان"
          : item?.marketState === "accepted"
          ? "تایید شده"
          : item?.marketState === "rejected"
          ? "رد شده"
          : item?.marketState === "deleted"
          ? "حذف شده"
          : ""
      }`;

      const isDeleted = item?.marketState === "deleted";
      const hasMarketStateMessage =
        item?.marketStateMessage &&
        item.marketStateMessage !== null &&
        item.marketStateMessage !== "";

      const statusDisplay =
        isDeleted && marketStateInfo
          ? `${statusText}${statusText ? " " : ""}( ${
              marketStateInfo.fullname
            } ${marketStateInfo.mobile}) - ${formatTime(marketStateInfo.date)}`
          : isDeleted && !hasMarketStateMessage
          ? `${statusText}${statusText ? " " : ""}(سیستمی)`
          : statusText;

      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.poultry?.unitName || ""}`,
        `${item?.poultry?.fullname || ""} (${item?.poultry?.mobile || ""})`,
        item?.poultry?.city || "",
        ...(getRoleFromUrl() !== "KillHouse"
          ? [
              `${item?.killHouse?.killer === true ? "کشتارکن" : "کشتارگاه"} ${
                item?.killHouse?.name || ""
              }`,
              `${item?.killHouse?.fullname || ""} (${
                item?.killHouse?.mobile || ""
              })`,
              item?.killHouse?.city || "",
            ]
          : []),
        item?.chickenBreed || "",
        item?.poultryRequest?.killingAge?.toLocaleString() || "0",
        item?.killCapacity?.toLocaleString() || "0",
        formatJustDate(item?.reciveDate) || "-",
        item?.createDate ? formatTimeFull(item.createDate) : "-",
        item?.IndexWeight || 0,
        Math.round(
          item?.IndexWeight * item?.killCapacity || 0
        ).toLocaleString(),
        item?.amount ? item.amount.toLocaleString() : "0",
        item?.paymentDeadlineDate
          ? formatJustDate(item.paymentDeadlineDate)
          : "-",
        statusDisplay,
        item?.marketState === "accepted" ? (
          <PdfKillRequest pdf_key={item?.key} />
        ) : (
          "-"
        ),

        <ProvinceDirectBuyOperation
          updateTable={handleUpdate}
          updateTable2={updateTable}
          key={i}
          item={item}
        />,
      ];
    });

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

  useEffect(() => {
    lastMarketRequestsPayload.current = null;
    handleUpdate(false, false, true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [perPage, filter, updateTable]);

  useEffect(() => {
    // Expose handleUpdate function to parent component
    if (setUpdateRef && typeof setUpdateRef === "function") {
      setUpdateRef(() => handleUpdate);
    }
  }, [setUpdateRef, handleUpdate]);

  useEffect(() => {
    if (overViewData) {
      let d;
      if (getRoleFromUrl() === "KillHouse") {
        d = [
          {
            title: "سهمیه روز شما",
            data: overViewData?.info?.killHouseTodayShare?.toLocaleString(),
          },

          {
            title: "حجم خرید موقت",
            data: overViewData?.info?.killHouseMarketKillRequestsQuantityFirst?.toLocaleString(),
          },
          {
            title: "حجم خرید نهایی",
            data: overViewData?.info?.killHouseMarketKillRequestsQuantityFinal?.toLocaleString(),
          },
          {
            title: "مانده سهمیه",
            data: overViewData?.info?.killHouseTodayLeftShare?.toLocaleString(),
          },
          {
            title: "الزام به خرید سبک",
            data: overViewData?.info?.marketLightShare?.toLocaleString(),
          },
          {
            title: " حجم خرید سبک توافقی",
            data: overViewData?.info?.totalKillHouseMarketKillRequestsQuantityAgreementLightWeight?.toLocaleString(),
          },
          {
            title: "حجم خرید سبک ",
            data: overViewData?.info?.totalKillHouseMarketKillRequestsQuantityLightWeight?.toLocaleString(),
          },

          {
            title: "حجم خرید سنگین ",
            data: overViewData?.info?.totalKillHouseMarketKillRequestsQuantityHeavyWeight?.toLocaleString(),
          },
          {
            title: "حجم کل سفارشات",
            data: overViewData?.info?.totalPoultryRequestsQuantity?.toLocaleString(),
          },
          {
            title: "کل حجم خریداری شده",
            data: overViewData?.info?.killHouseMarketKillRequestsQuantity?.toLocaleString(),
          },
        ];
      } else {
        d = overViewData?.map((item, i) => {
          return [
            i + 1,
            item?.name,
            item?.info?.killHouseTodayShare?.toLocaleString() || "0",
            item?.info?.killHouseMarketKillRequestsQuantity?.toLocaleString() ||
              "0",
            item?.info?.killHouseMarketKillRequestsQuantityFirst?.toLocaleString() ||
              "0",
            item?.info?.killHouseMarketKillRequestsQuantityFinal?.toLocaleString() ||
              "0",
            item?.info?.killHouseMarketKillRequestsQuantityWeight?.toLocaleString() ||
              "0",
            item?.info?.killHouseMarketKillRequestsQuantityFirstWeight?.toLocaleString() ||
              "0",
            item?.info?.killHouseMarketKillRequestsQuantityFinalWeight?.toLocaleString() ||
              "0",
            item?.info?.totalKillHouseMarketKillRequestsQuantityAgreementLightWeight?.toLocaleString() ||
              "0",
            item?.info?.totalKillHouseMarketKillRequestsQuantityLightWeight?.toLocaleString() ||
              "0",
            item?.info?.totalKillHouseMarketKillRequestsQuantityHeavyWeight?.toLocaleString() ||
              "0",
            item?.info?.killHouseTodayLeftShare?.toLocaleString() || "0",
            item?.info?.marketLightShare?.toLocaleString() || "0",
          ];
        });
      }

      setOverViewDataList(d);
    }
  }, [overViewData]);

  return (
    <Grid mt={2}>
      {getRoleFromUrl() === "KillHouse" && (
        <Grid
          mb={2}
          container
          xs={12}
          p={1.5}
          gap={1}
          justifyContent="center"
          sx={{
            border: "1px solid",
            borderColor: "divider",
            borderRadius: 2,
            bgcolor: "background.paper",
            boxShadow: "0 8px 24px rgba(0,0,0,0.08)",
            backdropFilter: "blur(3px)",
          }}
        >
          {overViewDataList?.map((itemData, i) => (
            <Grid
              container
              direction="column"
              key={i}
              md={2.2}
              sx={{
                px: 1,
                py: 0.9,
                borderRadius: 1.5,
                bgcolor:
                  i === 4
                    ? "#f5f5a6"
                    : i >= 5 && i <= 9
                    ? "#e0e7ff87"
                    : "primary.light",

                border: "1px solid",
                borderColor: "divider",
                transition: "transform 200ms ease, box-shadow 200ms ease",
                transform: "translateY(0)",
                boxShadow: "0 4px 12px rgba(0,0,0,0.06)",
                "&:hover": {
                  boxShadow: "0 10px 28px rgba(0,0,0,0.12)",
                  transform: "translateY(-2px)",
                },
              }}
            >
              <Typography variant="body2" fontWeight={600} color="text.primary">
                {itemData?.title}
              </Typography>
              <Typography
                variant="caption"
                fontWeight={600}
                sx={{ color: "gray" }}
              >
                {itemData?.data?.toLocaleString()} قطعه
              </Typography>
            </Grid>
          ))}
        </Grid>
      )}
      <ResponsiveTable
        operation={
          <Grid xs={12} container gap={1} alignItems="center" direction="row">
            <Grid>
              <Button
                color="success"
                onClick={() => {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                    severity: "success",
                  });
                  const link = `${
                    axios.defaults.baseURL
                  }market_requests_excel/?role=${getRoleFromUrl()}&search=filter&value=&type=${filter}&key=${userKey}`;
                  window.location.href = link;
                }}
              >
                <RiFileExcel2Fill size={24} />
              </Button>
            </Grid>
            <Grid>
              <FormControl>
                <InputLabel id="demo-simple-select-label">
                  فیلتر نتایج
                </InputLabel>
                <Select
                  sx={{ minWidth: "120px" }}
                  size="small"
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={filter}
                  onChange={(event) => setFilter(event.target.value)}
                  label="Age"
                >
                  <MenuItem value={"pending"}>در انتظار</MenuItem>
                  <MenuItem value={"accepted"}>تایید شده</MenuItem>
                  <MenuItem value={"rejected"}>رد شده</MenuItem>
                  <MenuItem value={"deleted"}>حذف شده</MenuItem>
                  <MenuItem value={"all"}>همه سفارشات</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        }
        title={
          getRoleFromUrl() === "KillHouse"
            ? "خریدهای ثبت شده"
            : "سفارشات دریافتی"
        }
        customWidth="100%"
        data={tableData}
        columns={[
          "ردیف",
          "فارم",
          "مرغدار",
          "شهر",
          ...(getRoleFromUrl() !== "KillHouse"
            ? ["ماهیت خریدار", "خریدار", "آدرس خریدار"]
            : []),
          "نژاد",
          "سن (روز)",
          "تعداد قطعه",
          "تاریخ کشتار",
          "تاریخ ثبت سفارش",
          "میانگین وزنی (کیلوگرم)",
          "وزن تقریبی (کیلوگرم)",
          "مبلغ هر کیلو (ریال)",
          "حداکثر مهلت تسویه",
          "وضعیت",
          "توافق نامه",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        customColors={[{ rest: true, color: "green" }]}
      />

      {getRoleFromUrl() !== "KillHouse" && (
        <Grid container xs={12} mt={2} gap={2}>
          <ResponsiveTable
            isDashboard
            title="خلاصه معاملات"
            customWidth="100%"
            data={[
              [
                overViewDataDashboard?.totalPoultryRequestsQuantity?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseTodayShare?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantity?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantityFirst?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantityFinal?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantityWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantityFirstWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseMarketKillRequestsQuantityFinalWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityAgreementLightWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityLightWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.totalKillHouseMarketKillRequestsQuantityHeavyWeight?.toLocaleString() ||
                  "0",
                overViewDataDashboard?.killHouseTodayLeftShare?.toLocaleString() ||
                  "0",
                "0",
                overViewDataDashboard?.marketLightShare?.toLocaleString() ||
                  "0",
              ],
            ]}
            noPagination
            columns={[
              "حجم کل سفارشات (قطعه)",
              "سهمیه روز (قطعه)",
              "کل حجم خریداری شده (قطعه)",
              "حجم خرید موقت (قطعه)",
              "حجم خرید نهایی (قطعه)",
              "کل وزن خریداری شده (کیلوگرم)",
              "وزن خرید موقت (کیلوگرم)",
              "وزن خرید نهایی (کیلوگرم)",
              "حجم خرید سبک توافقی (قطعه)",
              "حجم خرید سبک (قطعه)",
              "حجم خرید سنگین (قطعه)",
              "مانده سهمیه (قطعه)",
              "الزام به خرید سبک (قطعه)",
            ]}
          />

          <ResponsiveTable
            title="گزارش معاملات"
            customWidth="100%"
            data={overViewDataList}
            paginated
            columns={[
              "ردیف",
              "کشتارگاه",
              "سهمیه روز",
              "کل حجم خریداری شده (قطعه)",
              "حجم خرید موقت (قطعه)",
              "حجم خرید نهایی (قطعه)",
              "کل وزن خریداری شده (کیلوگرم)",
              "وزن خرید موقت (کیلوگرم)",
              "وزن خرید نهایی (کیلوگرم)",
              "حجم خرید سبک توافقی (قطعه)",
              "حجم خرید سبک (قطعه)",
              "حجم خرید سنگین (قطعه)",
              "مانده سهمیه (قطعه)",
              "الزام به خرید سبک (قطعه)",
            ]}
          />
        </Grid>
      )}
    </Grid>
  );
};
