import { useEffect, useState, useCallback, useRef, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";
import { tradePanelChart } from "../../services/trade-panel-chat";
import { provincePolicyGetTradeTimeRagnge } from "../../services/province-policy-edit-trade-time-range";
import { provinceGetDirectBuyingPoultryRequests } from "../../services/province-get-direct-buying-poultry-requests";

export const useTradePanelData = () => {
  const dispatch = useDispatch();
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );

  const [range, setRange] = useState();
  const [chartsData, setChartsData] = useState([]);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [cities, setCities] = useState([]);

  const isInitialMount = useRef(true);
  const lastRequestPayload = useRef(null);
  const isFetching = useRef(false);

  const roleKey = useMemo(
    () => (checkPathStartsWith("slaughter") ? selectedSubUser?.key || "" : ""),
    [selectedSubUser?.key]
  );

  useEffect(() => {
    const fetchCities = async () => {
      try {
        const response = await axios.get("/cities");
        setCities(response.data);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات", error);
      }
    };
    fetchCities();
  }, []);

  const fetchTradeTimeRange = useCallback(async () => {
    const r = await dispatch(provincePolicyGetTradeTimeRagnge());
    if (r?.payload?.data) {
      const { startTime, endTime, allow } = r.payload.data;
      setRange({ start_time: startTime, end_time: endTime, allow });
    }
  }, [dispatch, roleKey]);

  const fetchChartData = useCallback(async () => {
    const r = await dispatch(
      tradePanelChart({
        role_key: checkPathStartsWith("slaughter") ? roleKey || "" : "",
      })
    );
    if (r?.payload?.data) {
      setChartsData(r.payload.data);
    }
  }, [dispatch, roleKey]);

  const fetchApiData = useCallback(
    async (pageNumber, searchValue, filters, perPage, forceFetch = false) => {
      const {
        selectedBreeds = [],
        selectedCities = [],
        showRemaining = false,
        minPrice = "",
        maxPrice = "",
        minAge = "",
        maxAge = "",
      } = filters || {};

      const payload = {
        selectedBreeds: [...(selectedBreeds || [])].sort().join(","),
        selectedCities: [...(selectedCities || [])].sort().join(","),
        showRemaining,
        minPrice: minPrice || "",
        maxPrice: maxPrice || "",
        minAge: minAge || "",
        maxAge: maxAge || "",
        textValue: searchValue || "",
        page: pageNumber || 1,
        perPage: perPage || 20,
      };

      const payloadKey = JSON.stringify(payload);

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

      if (isFetching.current) {
        return;
      }

      isFetching.current = true;
      lastRequestPayload.current = payloadKey;

      try {
        const r = await dispatch(
          provinceGetDirectBuyingPoultryRequests({
            selectedBreeds: selectedBreeds || [],
            selectedCities: selectedCities || [],
            showRemaining,
            minPrice: minPrice || "",
            maxPrice: maxPrice || "",
            minAge: minAge || "",
            maxAge: maxAge || "",
            textValue: searchValue || "",
            page: pageNumber || 1,
            perPage: perPage || 20,
          })
        );
        if (r?.payload?.error) {
          console.error("Error fetching data:", r.payload.error);
          setData([]);
          setTotalRows(0);
        } else if (r?.payload?.data) {
          setData(r.payload.data.results || []);
          setTotalRows(r.payload.data.count || 0);
        }
      } catch (error) {
        console.error("Error in fetchApiData:", error);
        setData([]);
        setTotalRows(0);
      } finally {
        isFetching.current = false;
      }
    },
    [dispatch, roleKey]
  );

  const initializeData = useCallback(
    async (textValue, filters, perPage) => {
      if (isInitialMount.current) {
        isInitialMount.current = false;
        lastRequestPayload.current = null;
        try {
          await Promise.all([
            fetchTradeTimeRange(),
            fetchChartData(),
            fetchApiData(1, textValue, filters, perPage, true),
          ]);
        } catch (error) {
          console.error("Error in initial fetch:", error);
        }
      }
    },
    [fetchTradeTimeRange, fetchChartData, fetchApiData]
  );

  const resetPayload = useCallback(() => {
    lastRequestPayload.current = null;
  }, []);

  return {
    range,
    chartsData,
    data,
    totalRows,
    cities,
    roleKey,
    userKey,
    fetchApiData,
    initializeData,
    resetPayload,
  };
};
