"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useOrders, ORDER_TAB_FILTERS, ORDERS_PATH } from "@/lib/orders";
import { OrderStatusFilter } from "./list/OrderStatusFilter";
import { OrderCardList } from "./list/OrderCardList";
import { OrdersSkeleton } from "./state/OrdersSkeleton";
import { OrdersEmptyState } from "./state/OrdersEmptyState";

export function OrdersPageView() {
  const [activeFilter, setActiveFilter] = useState("all");
  const router = useRouter();

  const tab = ORDER_TAB_FILTERS.find((f) => f.id === activeFilter);
  const statusFilter = tab?.statuses?.map(String);

  const { orders, isLoading, hasMore, loadMore, status } =
    useOrders(statusFilter);

  if (isLoading) {
    return <OrdersSkeleton />;
  }

  return (
    <div className="space-y-6">
      <OrderStatusFilter
        activeFilter={activeFilter}
        onFilterChange={setActiveFilter}
      />

      {orders.length === 0 ? (
        <OrdersEmptyState
          message={
            activeFilter === "all"
              ? "When you place an order, it will appear here."
              : "No orders match this filter."
          }
        />
      ) : (
        <OrderCardList
          orders={orders}
          hasMore={hasMore}
          isLoadingMore={status === "LoadingMore"}
          onLoadMore={loadMore}
          onViewDetails={(id) => router.push(`${ORDERS_PATH}/${id}`)}
        />
      )}
    </div>
  );
}
