import { useEffect, useState } from "react";
import type { OrderSummary } from "@orderops/shared";
import { listOrders } from "./order-api";
import { OrderList } from "./order-list";
import { OrderSearch } from "./order-search";

export function OrdersPage() {
  const [query, setQuery] = useState("");
  const [orders, setOrders] = useState<OrderSummary[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const timeout = window.setTimeout(() => {
      void listOrders(query)
        .then((nextOrders) => {
          setOrders(nextOrders);
          setError(null);
        })
        .catch((caught: unknown) => setError(caught instanceof Error ? caught.message : "Failed to load orders."));
    }, 150);

    return () => window.clearTimeout(timeout);
  }, [query]);

  return (
    <div className="mx-auto max-w-4xl space-y-4">
      <div>
        <h1 className="text-2xl font-semibold text-slate-900">Orders</h1>
        <p className="text-sm text-slate-600">Search orders and open an order workspace.</p>
      </div>
      <OrderSearch query={query} onQueryChange={setQuery} />
      {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}
      <OrderList orders={orders} />
    </div>
  );
}
