import { useEffect, useState, useMemo, useRef } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { ProvinceTradePanelMarketRequest } from "../province-trade-panel-market-request/ProvinceTradePanelMarketRequest";
import { ProvinceTradePanelMarketOldRequest } from "../province-trade-panel-market-old-request/ProvinceTradePanelMarketOldRequest";
import { TradePanelTabs } from "./TradePanelTabs";
import { TradeTimeRangeInfo } from "./TradeTimeRangeInfo";
import { TradePanelChart } from "./TradePanelChart";
import { TradePanelSearchBar } from "./TradePanelSearchBar";
import { TradePanelTable } from "./TradePanelTable";
import { useTradePanelData } from "./useTradePanelData";
import { useTradePanelFilters } from "./useTradePanelFilters";

export const ProvinceTradePanel = () => {
  const [perPage, setPerPage] = useState(20);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [value, setValue] = useState(0);
  const marketRequestUpdateRef = useRef(null);

  const {
    range,
    chartsData,
    data,
    totalRows,
    cities,
    roleKey,
    userKey,
    fetchApiData,
    initializeData,
  } = useTradePanelData();

  const {
    filters,
    updateFilter,
    handleCityChange,
    handleBreedChange,
    handlePriceFilterSubmit,
    handleAgeFilterSubmit,
    getExcelUrlParams,
  } = useTradePanelFilters();

  const excelUrlParams = useMemo(() => {
    if (!userKey) return "";
    return getExcelUrlParams(userKey, roleKey, textValue, page, perPage);
  }, [getExcelUrlParams, userKey, roleKey, textValue, page, perPage]);

  useEffect(() => {
    initializeData(textValue, filters, perPage);
  }, []);

  useEffect(() => {
    if (page === 1 && textValue === "") {
      return;
    }
    fetchApiData(page, textValue, filters, perPage);
  }, [
    page,
    textValue,
    filters.selectedBreeds,
    filters.selectedCities,
    filters.showRemaining,
    filters.minPrice,
    filters.maxPrice,
    filters.minAge,
    filters.maxAge,
    perPage,
    fetchApiData,
  ]);

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

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

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

  const handlePageChange = (pageNum) => {
    setPage(pageNum);
    fetchApiData(pageNum, textValue, filters, perPage);
  };

  const updateTable = () => {
    fetchApiData(1, textValue, filters, perPage);
  };

  const updateAllTables = () => {
    // Update "لیست اعلام کشتار های مرغداران" (tab 0)
    updateTable();
    // Update "خریدهای ثبت شده" (tab 1) - call all services for ProvinceTradePanelMarketRequest
    if (
      marketRequestUpdateRef.current &&
      typeof marketRequestUpdateRef.current === "function"
    ) {
      // Force all fetches: dashboard, overview, and market requests
      marketRequestUpdateRef.current(true, true, true);
    }
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setPage(1);
    fetchApiData(1, textValue, filters, perPage);
  };

  const handlePriceFilterSubmitWithPageReset = () => {
    handlePriceFilterSubmit();
    setPage(1);
  };

  const handleAgeFilterSubmitWithPageReset = () => {
    handleAgeFilterSubmit();
    setPage(1);
  };

  return (
    <>
      <TradePanelTabs value={value} onChange={handleChange} />
      <Grid xs={12} px={1}>
        <TradeTimeRangeInfo range={range} />
        {value === 0 && (
          <Grid container direction="row" gap={SPACING.SMALL}>
            <TradePanelChart
              chartsData={chartsData}
              updateTable={updateTable}
            />
            <TradePanelSearchBar
              textValue={textValue}
              onTextChange={handleTextChange}
              onSubmit={handleSubmit}
              excelUrlParams={excelUrlParams}
            />
            <TradePanelTable
              data={data}
              page={page}
              perPage={perPage}
              totalRows={totalRows}
              filters={filters}
              cities={cities}
              onFilterUpdate={updateFilter}
              onCityChange={handleCityChange}
              onBreedChange={handleBreedChange}
              onPriceFilterSubmit={handlePriceFilterSubmitWithPageReset}
              onAgeFilterSubmit={handleAgeFilterSubmitWithPageReset}
              onPageChange={handlePageChange}
              onPerRowsChange={handlePerRowsChange}
              updateTable={updateAllTables}
            />
          </Grid>
        )}

        <Grid xs={12} sx={{ display: value === 1 ? "block" : "none" }}>
          <ProvinceTradePanelMarketRequest
            updateTable={updateTable}
            setUpdateRef={(updateFn) => {
              marketRequestUpdateRef.current = updateFn;
            }}
          />
        </Grid>
        {value === 2 && (
          <Grid xs={12}>
            <ProvinceTradePanelMarketOldRequest />
          </Grid>
        )}
      </Grid>
    </>
  );
};

export default ProvinceTradePanel;
