"use client";

import { Suspense, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { PageLayout } from "@/components/templates/PageLayout";
import { ClipboardDocumentListIcon } 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 "@/core/api";
import { Button } from "@/components/atoms/button";

function OrdersSuccessBanner() {
  const searchParams = useSearchParams();
  const showSuccess = searchParams.get("status") === "success";
  if (!showSuccess) return null;
  return (
    <AlertBanner variant="success" title="Order submitted" className="mb-6" elevated>
      Your order has been created and is now being processed. You can track its progress below.
    </AlertBanner>
  );
}

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"
                variant="outline"
                size="sm"
                onClick={() => void refetch()}
                isLoading={isFetching}
                loadingText="Retrying…"
              >
                Retry
              </Button>
            )}
          </div>
        </AlertBanner>
      )}

      {(() => {
        if (isLoading || !orders) {
          return (
            <div className="space-y-4">
              {Array.from({ length: 4 }).map((_, idx) => (
                <OrderCardSkeleton key={idx} />
              ))}
            </div>
          );
        }
        if (isError) return null;
        if (orders.length === 0) {
          return (
            <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 Services",
                  onClick: () => router.push("/account/services"),
                }}
              />
            </AnimatedCard>
          );
        }
        return (
          <div className="space-y-4">
            {orders.map(order => (
              <OrderCard
                key={String(order.id)}
                order={order}
                onClick={() => router.push(`/account/orders/${order.id}`)}
              />
            ))}
          </div>
        );
      })()}
    </PageLayout>
  );
}

export default OrdersListContainer;
