import { Button, TextField, Tooltip, Typography } from "@mui/material";
import axios from "axios";
import { useEffect, useState, useCallback, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { SPACING } from "../../../../data/spacing";
import { formatJustDate } from "../../../../utils/formatTime";
import { Tab, Tabs } from "@mui/material";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { TradepanelDetails } from "../trade-panel-details/TradepanelDetails";
import { TradePanelPurchaseOperation } from "../trade-panel-purchase-operation/TradePanelPurchaseOperation";
import { TradePanelFilters } from "../trade-panel-filter/TradePanelFilter";
import { AdvancedChart } from "../../../../components/advanced-chart/AdvancedChart";
import { tradePanelChart } from "../../services/trade-panel-chat";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvinceTradePanelMarketRequest } from "../province-trade-panel-market-request/ProvinceTradePanelMarketRequest";
import { provincePolicyGetTradeTimeRagnge } from "../../services/province-policy-edit-trade-time-range";
import InfoIcon from "@mui/icons-material/Info";
import { ProvinceTradePanelMarketOldRequest } from "../province-trade-panel-market-old-request/ProvinceTradePanelMarketOldRequest";
import { provinceGetDirectBuyingPoultryRequests } from "../../services/province-get-direct-buying-poultry-requests";

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

  const [range, setRange] = useState();

  const [chartsData, setChartsData] = useState([]);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(20);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [cities, setCities] = useState([]);
  const chickenBreeds = ["آرین", "راس", "کاب", "*ترکیبی"];
  const isInitialMount = useRef(true);
  const lastRequestPayload = useRef(null);
  const isFetching = useRef(false);

  const [value, setValue] = useState(0);

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

  const [filters, setFilters] = useState({
    showRemaining: false,
    selectedCities: [],
    selectedBreeds: [],
    minPrice: "",
    maxPrice: "",
    tempMinPrice: "",
    tempMaxPrice: "",
    minAge: "",
    maxAge: "",
    tempMinAge: "",
    tempMaxAge: "",
  });

  const updateFilter = (key, value) => {
    setFilters((prev) => ({ ...prev, [key]: value }));
  };

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

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

  const handleCityChange = (city) => {
    setFilters((prev) => ({
      ...prev,
      selectedCities: prev.selectedCities.includes(city)
        ? prev.selectedCities.filter((c) => c !== city)
        : [...prev.selectedCities, city],
    }));
  };

  const handleBreedChange = (breed) => {
    setFilters((prev) => ({
      ...prev,
      selectedBreeds: prev.selectedBreeds.includes(breed)
        ? prev.selectedBreeds.filter((b) => b !== breed)
        : [...prev.selectedBreeds, breed],
    }));
  };

  const handlePriceFilterSubmit = () => {
    setFilters((prev) => ({
      ...prev,
      minPrice: prev.tempMinPrice,
      maxPrice: prev.tempMaxPrice,
    }));
    setPage(1);
  };

  const handleAgeFilterSubmit = () => {
    setFilters((prev) => ({
      ...prev,
      minAge: prev.tempMinAge,
      maxAge: prev.tempMaxAge,
    }));
    setPage(1);
  };
  const {
    selectedCities,
    selectedBreeds,
    showRemaining,
    minPrice,
    maxPrice,
    minAge,
    maxAge,
  } = filters;

  const cityParams =
    selectedCities.length > 0 ? `&city=${selectedCities.join(",")}` : "";
  const minPriceParam = minPrice ? `&min_amount=${minPrice}` : "";
  const maxPriceParam = maxPrice ? `&max_amount=${maxPrice}` : "";

  // Fetch trade time range - called once on mount
  const fetchTradeTimeRange = useCallback(async () => {
    const r = await dispatch(provincePolicyGetTradeTimeRagnge());
    if (r?.payload?.data) {
      const d = r.payload.data;
      setRange({
        start_time: d.startTime,
        end_time: d.endTime,
        allow: d.allow,
      });
    }
  }, [dispatch]);

  // Fetch chart data - called once on mount
  const fetchChartData = useCallback(async () => {
    const r = await dispatch(tradePanelChart());
    if (r?.payload?.data) {
      setChartsData(r.payload.data);
    }
  }, [dispatch]);

  // Fetch poultry requests data
  const fetchApiData = useCallback(
    async (pageNumber = page, searchValue = textValue, forceFetch = false) => {
      // Create a payload signature to check for duplicates
      const payload = {
        selectedBreeds: [...selectedBreeds].sort().join(","),
        selectedCities: [...selectedCities].sort().join(","),
        showRemaining,
        minPrice,
        maxPrice,
        minAge,
        maxAge,
        textValue: searchValue,
        page: pageNumber,
        perPage,
      };

      const payloadKey = JSON.stringify(payload);

      // Prevent duplicate calls with the same payload
      if (!forceFetch && lastRequestPayload.current === payloadKey) {
        return;
      }

      // Prevent concurrent duplicate calls
      if (isFetching.current) {
        return;
      }

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

      try {
        const r = await dispatch(
          provinceGetDirectBuyingPoultryRequests({
            selectedBreeds,
            selectedCities,
            showRemaining,
            minPrice,
            maxPrice,
            minAge,
            maxAge,
            textValue: searchValue,
            page: pageNumber,
            perPage,
          })
        );
        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);
        }
      } finally {
        isFetching.current = false;
      }
    },
    [
      dispatch,
      selectedBreeds,
      selectedCities,
      showRemaining,
      minPrice,
      maxPrice,
      minAge,
      maxAge,
      textValue,
      perPage,
    ]
  );

  // Initial mount - fetch all APIs once
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false;
      // Clear any previous payload to ensure initial fetch runs
      lastRequestPayload.current = null;
      // Fetch all three APIs on initial mount (in parallel)
      // Pass forceFetch=true to ensure it runs on initial mount
      Promise.all([
        fetchTradeTimeRange(),
        fetchChartData(),
        fetchApiData(1, textValue, true),
      ]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Handle filter/page changes - only fetch poultry requests
  useEffect(() => {
    if (!isInitialMount.current) {
      // Reset payload to allow fetching with new filters
      lastRequestPayload.current = null;
      setPage(1);
      fetchApiData(1);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    perPage,
    selectedBreeds,
    selectedCities,
    showRemaining,
    minPrice,
    maxPrice,
    minAge,
    maxAge,
    value,
  ]);

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

  const handlePageChange = (pageNum) => {
    lastRequestPayload.current = null; // Reset to allow fetching new page
    fetchApiData(pageNum);
    setPage(pageNum);
  };

  const updateTable = () => {
    lastRequestPayload.current = null; // Reset to allow refreshing
    fetchApiData(1);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    lastRequestPayload.current = null; // Reset to allow searching with new text
    setPage(1);
    fetchApiData(1, textValue);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        <TradepanelDetails key={i} details_key={item?.age?.hatchingKey} />,
        `${item?.poultry?.fullname} (${item?.poultry?.mobile})`,
        item?.poultry?.city,
        item?.chickenBreed,
        item?.age?.age,
        item?.IndexWeight,
        formatJustDate(item?.sendDate),
        item?.quantity,
        item?.remainQuantity ? item?.remainQuantity.toLocaleString() : "0",
        item?.totalAllocated ? item?.totalAllocated?.toLocaleString() : "0",
        item?.amount ? item?.amount.toLocaleString() : "0",

        <TradePanelPurchaseOperation
          key={i}
          item={item}
          updateTable={updateTable}
        />,
      ];
    });

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

  const getSlaughterChartOptions = () => {
    return [
      {
        name: "تعداد کل",
        data: chartsData?.map((item) => item?.totalQuantity),
      },
      {
        name: `بین ${chartsData?.[0]?.category[0]?.minValue || 0} تا ${
          chartsData?.[0]?.category[0]?.maxValue || 0
        }`,
        data: chartsData?.map((item) => item?.category[0]?.quantity),
      },
      {
        name: `بین ${chartsData?.[0]?.category[1]?.minValue || 0} تا ${
          chartsData?.[0]?.category[1]?.maxValue || 0
        }`,
        data: chartsData?.map((item) => item?.category[1]?.quantity),
      },
      {
        name: `بین ${chartsData?.[0]?.category[2]?.minValue || 0} تا ${
          chartsData?.[0]?.category[2]?.maxValue || 0
        }`,
        data: chartsData?.map((item) => item?.category[2]?.quantity),
      },
    ];
  };

  return (
    <>
      {getRoleFromUrl() !== "KillHouse" && (
        <Grid
          xs={12}
          container
          alignItems="center"
          justifyContent="center"
          mb={2}
        >
          <Tabs
            scrollButtons="auto"
            variant="scrollable"
            allowScrollButtonsMobile
            value={value}
            onChange={handleChange}
          >
            <Tab label="اعلام کشتار مرغداران" value={0} />
            <Tab label="گزارش معاملات" value={1} />
            <Tab label="معاملات گذشته" value={2} />
          </Tabs>
        </Grid>
      )}
      <Grid xs={12} px={1}>
        {range?.allow && (
          <Grid
            container
            xs={12}
            gap={1}
            alignItems="center"
            justifyContent="center"
          >
            <InfoIcon color="primary" />
            <Typography variant="body2" color="error">
              {" "}
              زمان فعالیت پنل معاملات: از ساعت {range?.start_time?.slice(
                0,
                5
              )}{" "}
              الی ساعت {range?.end_time?.slice(0, 5)}
            </Typography>
          </Grid>
        )}
        {value === 0 && (
          <Grid container direction="row" gap={SPACING.SMALL}>
            <Grid container spacing={2} xs={12}>
              <Grid
                xs={12}
                md={getRoleFromUrl() === "KillHouse" ? 5 : 12}
                justifyContent="center"
                alignItems="center"
                height="400px"
              >
                <AdvancedChart
                  title={"درخواست های کشتار بر اساس وزن"}
                  type={"bar"}
                  group
                  seperator={chartsData?.map((item) => item?.city)}
                  info={getSlaughterChartOptions()}
                />
              </Grid>
              {getRoleFromUrl() === "KillHouse" && (
                <Grid xs={12} md={7}>
                  <ProvinceTradePanelMarketRequest updateTable={updateTable} />
                </Grid>
              )}
            </Grid>

            <Grid xs={12}>
              <form onSubmit={handleSubmit}>
                <Grid container alignItems="center" gap={SPACING.SMALL} p={2}>
                  <TextField
                    size="small"
                    autoComplete="off"
                    label="جستجو"
                    variant="outlined"
                    style={{ width: 250 }}
                    onChange={handleTextChange}
                  />

                  <Button
                    type="submit"
                    onClick={handleSubmit}
                    endIcon={<RiSearchLine />}
                  >
                    جستجو
                  </Button>

                  <Tooltip title="خروجی اکسل">
                    <a
                      href={`${
                        axios.defaults.baseURL
                      }direct_buying_poultry_requests/?key=${userKey}&breed=${selectedBreeds.join(
                        ","
                      )}${cityParams}&remain=${showRemaining}${minPriceParam}${maxPriceParam}&weight=&min_age=${minAge}&max_age=${maxAge}&role=${getRoleFromUrl()}&search=filter&value=${
                        textValue || ""
                      }&page=${page}&page_size=${perPage}`}
                      rel="noreferrer"
                    >
                      <Button color="success">
                        <RiFileExcel2Fill size={32} />
                      </Button>
                    </a>
                  </Tooltip>
                </Grid>
              </form>
            </Grid>

            <Grid container spacing={2} sx={{ width: "100%" }}>
              <Grid item xs={12} md={2}>
                <TradePanelFilters
                  filters={filters}
                  updateFilter={updateFilter}
                  handleCityChange={handleCityChange}
                  handleBreedChange={handleBreedChange}
                  handlePriceFilterSubmit={handlePriceFilterSubmit}
                  handleAgeFilterSubmit={handleAgeFilterSubmit}
                  cities={cities}
                  chickenBreeds={chickenBreeds}
                />
              </Grid>

              <Grid item xs={12} md={10}>
                <ResponsiveTable
                  title="لیست اعلام کشتار های مرغداران"
                  data={tableData}
                  customWidth="100%"
                  columns={[
                    "ردیف",
                    "جزئیات",
                    "نام و نام خانوادگی (تلفن)",
                    "استان / شهر",
                    "نژاد",
                    "سن جوجه",
                    "میانگین وزنی (کیلوگرم) ",
                    "تاریخ کشتار",
                    "تعداد قطعه",
                    "مانده قابل خرید",
                    "فروش رفته ",
                    "مبلغ هر کیلو (ریال)",
                    ...(getRoleFromUrl() === "KillHouse" ? ["خرید"] : []),
                  ]}
                  handlePageChange={handlePageChange}
                  totalRows={totalRows}
                  page={page}
                  perPage={perPage}
                  handlePerRowsChange={handlePerRowsChange}
                />
              </Grid>
            </Grid>
          </Grid>
        )}

        {value === 1 && (
          <Grid xs={12}>
            <ProvinceTradePanelMarketRequest updateTable={updateTable} />
          </Grid>
        )}
        {value === 2 && (
          <Grid xs={12}>
            <ProvinceTradePanelMarketOldRequest />
          </Grid>
        )}
      </Grid>
    </>
  );
};

export default ProvinceTradePanel;
