import OrderCard from "@/components/order-card";
import { useOrderAutoRefresh, useOrders } from "@/hooks/useOrders";
import { useQueryClient } from "@tanstack/react-query";
import ErrorMessage from "./ErrorPage";
import LoadingPage from "./Loading";

export default function Home() {
  const { data: orders, status } = useOrders();
  const queryClient = useQueryClient();
  useOrderAutoRefresh(queryClient);

  if (status === "pending") {
    return <LoadingPage />;
  }
  if (!orders) {
    return <ErrorMessage>주문을 불러오지 못했습니다.</ErrorMessage>;
  }

  const sortedOrders = orders.sort((a, b) => {
    // id format: "{date}/{order_number}"
    const [, anum] = a.id.split("/");
    const [, bnum] = b.id.split("/");
    return parseInt(bnum) - parseInt(anum);
  });

  return (
    <>
      {sortedOrders.length === 0 && <ErrorMessage>주문이 없습니다.</ErrorMessage>}
      <section>
        {sortedOrders.map((order) => <OrderCard key={order.id} order={order} />)}
      </section>
    </>
  );
}
