"use client";

import { Suspense, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { PageLayout } from "@/components/templates/PageLayout";
import { ClipboardDocumentListIcon, CheckCircleIcon } from "@heroicons/react/24/outline";
import { AnimatedCard } from "@/components/molecules";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { OrderCard } from "@/features/orders/components/OrderCard";
import { OrderCardSkeleton } from "@/features/orders/components/OrderCardSkeleton";
import { EmptyState } from "@/components/atoms/empty-state";
import { useOrdersList } from "@/features/orders/hooks/useOrdersList";
import { isApiError } from "@/lib/api";

function OrdersSuccessBanner() {
  const searchParams = useSearchParams();
  const showSuccess = searchParams.get("status") === "success";
  if (!showSuccess) return null;
  return (
    <div className="bg-green-50 border border-green-200 rounded-xl p-6 mb-6">
      <div className="flex items-start">
        <CheckCircleIcon className="h-6 w-6 text-green-600 mt-0.5 mr-3 flex-shrink-0" />
        <div>
          <h3 className="text-lg font-semibold text-green-900 mb-2">
            Order Submitted Successfully!
          </h3>
          <p className="text-green-800">
            Your order has been created and is now being processed. You can track its progress
            below.
          </p>
        </div>
      </div>
    </div>
  );
}

export function OrdersListContainer() {
  const router = useRouter();
  const { data: orders, isLoading, isError, error, refetch, isFetching } = useOrdersList();

  const { errorMessage, showRetry } = useMemo(() => {
    if (!isError) {
      return { errorMessage: null, showRetry: false };
    }

    if (isApiError(error) && error.response.status === 429) {
      return {
        errorMessage:
          "We're receiving a high volume of requests from the orders service. Please wait a few seconds and try again.",
        showRetry: true,
      };
    }

    if (error instanceof Error) {
      return { errorMessage: error.message, showRetry: true };
    }

    return { errorMessage: "We couldn't load your orders right now.", showRetry: true };
  }, [error, isError]);

  return (
    <PageLayout
      icon={<ClipboardDocumentListIcon />}
      title="My Orders"
      description="View and track all your orders"
    >
      <Suspense fallback={null}>
        <OrdersSuccessBanner />
      </Suspense>

      {errorMessage && (
        <AlertBanner variant="error" title="Unable to load orders" className="mb-6" elevated>
          <div className="flex flex-wrap items-center justify-between gap-3">
            <span className="text-sm">{errorMessage}</span>
            {showRetry && (
              <button
                type="button"
                onClick={() => void refetch()}
                className="inline-flex items-center rounded-lg border border-blue-200 px-3 py-1.5 text-sm font-medium text-blue-700 transition hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-60"
                disabled={isFetching}
              >
                {isFetching ? "Retrying…" : "Retry"}
              </button>
            )}
          </div>
        </AlertBanner>
      )}

      {isLoading || !orders ? (
        <div className="space-y-4">
          {Array.from({ length: 4 }).map((_, idx) => (
            <OrderCardSkeleton key={idx} />
          ))}
        </div>
      ) : isError ? null : orders.length === 0 ? (
        <AnimatedCard className="p-8 text-center" variant="static">
          <EmptyState
            icon={<ClipboardDocumentListIcon className="h-12 w-12" />}
            title="No orders yet"
            description="You haven't placed any orders yet."
            action={{ label: "Browse Catalog", onClick: () => router.push("/catalog") }}
          />
        </AnimatedCard>
      ) : (
        <div className="space-y-4">
          {orders.map(order => (
            <OrderCard
              key={String(order.id)}
              order={order}
              onClick={() => router.push(`/orders/${order.id}`)}
            />
          ))}
        </div>
      )}
    </PageLayout>
  );
}

export default OrdersListContainer;
