"use client";
import { useState, useEffect, useCallback } from "react";
import type { Order, OrderStatus } from "@/types/marketplace";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export function useOrders(role: "buyer" | "seller" = "buyer") {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<OrderStatus | "all">("all");

  const fetchOrders = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ role });
      if (statusFilter !== "all") params.set("status", statusFilter);
      const res = await fetch(`${BASE_URL}/api/marketplace/orders?${params}`);
      if (!res.ok) throw new Error("Failed to fetch orders");
      const data: Order[] = await res.json();
      setOrders(data);
    } catch {
      setError("Could not load orders");
    } finally {
      setLoading(false);
    }
  }, [role, statusFilter]);

  useEffect(() => {
    fetchOrders();
  }, [fetchOrders]);

  return { orders, loading, error, statusFilter, setStatusFilter, refresh: fetchOrders };
}
