"use client"

import { useOrderHistory } from "@/app/api-requests/getOrderHistory"
import OrderProductCard from "./OrderProductCard"
import Loading from "@/app/[lang]/loading"
import { useCallback, useMemo, useRef } from "react"
import LoadingSpinner from "../shared/loadingSpinner/LoadingSpinner"
import { Button } from "@/components/ui/button"
import { Loader } from "lucide-react"
import TranslateClient from "@/components/ui/localization/TranslateClient"

const OrderHistory = () => {
  const { data: ordersData, isLoading, hasNextPage, fetchNextPage, isFetchingNextPage } = useOrderHistory()

  const observer = useRef<IntersectionObserver | null>(null)
  const lastElementRef = useCallback(
    (node: Element | null) => {
      if (isLoading) return
      if (observer.current) observer.current.disconnect()
      observer.current = new IntersectionObserver((entries) => {
        if (entries[0].isIntersecting && hasNextPage) {
          fetchNextPage()
        }
      })
      if (node) observer.current?.observe(node)
    },
    [fetchNextPage, hasNextPage, isLoading]
  )

  const allData = useMemo(() => {
    let data: any = []
    ordersData?.pages?.forEach((page) => {
      page.data.forEach((group: any) => {
        data.push(group)
      })
    })
    return data
  }, [ordersData?.pages])

  if (isLoading) return <Loading className="min-h-[200px]" />

  return (
    <div className="container">
      {allData && allData?.length > 0 ? (
        allData?.map((order: any, index: number) => {
          const isLastItem = allData?.length - 1 === index

          return (
            <OrderProductCard
              allData={allData}
              lastElementRef={lastElementRef}
              order={order}
              key={order?.order_id}
              index={index}
            />
          )
        })
      ) : (
        <h4 className="text-center text-3xl text-mainBlue py-10 my-5">No orders found</h4>
      )}

      {isFetchingNextPage && (
        <Button
          variant="outline"
          className="gap-2 border-gray-300 text-gray-300 mx-auto flex mb-5 hover:text-gray-300 hover:border-gray-300 cursor-auto"
        >
          <Loader className="w-4 h-4 animate-spin" />
          <TranslateClient text="loading" />
        </Button>
      )}
    </div>
  )
}

export default OrderHistory
