"use client";
import getUserProfile from "@/api/user/getUserProfile";
import { useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { useLocale } from "next-intl";
import SectionHeader from "../shared/SectionHeader";
import AuctionClientList from "./AuctionClientList";
import UpdateAuctionsPricesButton from "./UpdateAuctionsPricesButton";
import { useEffect, useState } from "react";
import fetchData from "@/api/fetch-data";

export default function Auctions() {
  const queryClient = useQueryClient();
  const locale = useLocale();

  const initialResponse = queryClient.getQueryData([
    `/auctions?page=1&random=true&limit=${process.env.NEXT_PUBLIC_NUMBER_OF_AUCTIONS_AT_HOME_PAGE}`,
    locale,
  ]);

  const [pageNumber, setPageNumber] = useState(1);
  const [currentAuctions, setCurrentAuctions] = useState(
    initialResponse?.data?.auctions || []
  );
  const [currentTotalPages, setCurrentTotalPages] = useState(1);

  const { refetch, isLoading, isFetching, data } = useSuspenseQuery({
    queryKey: [
      `/auctions?page=${pageNumber}&random=true&limit=${process.env.NEXT_PUBLIC_NUMBER_OF_AUCTIONS_AT_HOME_PAGE}`,
      locale,
    ],
    queryFn: () =>
      fetchData({
        endPoint: `/auctions?page=${pageNumber}&random=true&limit=${process.env.NEXT_PUBLIC_NUMBER_OF_AUCTIONS_AT_HOME_PAGE}`,
      }),
  });

  const { data: profile } = useSuspenseQuery({
    queryKey: ["/user/get/profile"],
    queryFn: () => getUserProfile(),
  });

  // Update displayed data only when new data arrives
  useEffect(() => {
    if (data?.data?.auctions) {
      setCurrentAuctions(data?.data?.auctions);
    }
    if (data?.data?.meta?.last_page) {
      setCurrentTotalPages(data.data.meta.last_page);
    }
  }, [data]);

  // Auto-cycle through pages every 30 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      setPageNumber((prevPage) => {
        // If we're at the last page, go back to page 1
        // Otherwise, go to the next page
        return prevPage >= currentTotalPages ? 1 : prevPage + 1;
      });
    }, process.env.NEXT_PUBLIC_NUMBER_OF_MILLIE_SECONDS_BEFORE_FETCHING_NEW_AUCTIONS);

    // Cleanup interval on component unmount
    return () => clearInterval(interval);
  }, [currentTotalPages]); // Use currentTotalPages instead of data-dependent value

  return (
    <>
      <SectionHeader
        title={locale == "ar" ? "اخر" : "Last"}
        marker={locale == "ar" ? "المزادات" : "Auctions"}
        link="/auctions"
      />
      <div className="flex justify-center">
        <UpdateAuctionsPricesButton
          refetch={refetch}
          isLoading={isLoading}
          isFetching={isFetching}
        />
      </div>
      <div className="">
        <AuctionClientList
          isLoading={false}
          auctions={currentAuctions} // Use stored auctions instead of direct data
          totalNumberOfPages={currentTotalPages} // Use stored total pages
          profile={profile}
          currentPage={pageNumber}
        />
      </div>
    </>
  );
}
