"use client";

import { Suspense, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  ClipboardDocumentListIcon,
  ClockIcon,
  CheckCircleIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/outline";
import { PageLayout } from "@/components/templates/PageLayout";
import {
  AnimatedCard,
  SummaryStats,
  FilterDropdown,
  ClearFiltersButton,
} from "@/components/molecules";
import type { StatItem } from "@/components/molecules/SummaryStats";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import { AlertBanner } from "@/components/molecules/AlertBanner/AlertBanner";
import { OrderCard } from "@/features/orders/components/OrderCard";
import { OrderCardSkeleton } from "@/features/orders/components/OrderCardSkeleton";
import { EmptyState, SearchEmptyState } from "@/components/atoms/empty-state";
import { useOrdersList } from "@/features/orders/hooks/useOrdersList";
import {
  useOrdersFilter,
  type OrderStatusFilter,
  type OrderTypeFilter,
} from "@/features/orders/hooks/useOrdersFilter";
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>
  );
}

const STATUS_FILTER_OPTIONS = [
  { value: "all", label: "All Statuses" },
  { value: "pending", label: "Pending" },
  { value: "active", label: "Active" },
  { value: "processing", label: "Processing" },
  { value: "cancelled", label: "Cancelled" },
];

const TYPE_FILTER_OPTIONS = [
  { value: "all", label: "All Types" },
  { value: "internet", label: "Internet" },
  { value: "sim", label: "SIM" },
  { value: "vpn", label: "VPN" },
];

function getErrorInfo(isError: boolean, error: unknown) {
  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 };
}

function buildOrderSummaryStats(stats: {
  total: number;
  pending: number;
  active: number;
  processing: number;
}): StatItem[] {
  return [
    {
      icon: <ClipboardDocumentListIcon className="h-4 w-4" />,
      label: "Total",
      value: stats.total,
      tone: "muted",
    },
    {
      icon: <ClockIcon className="h-4 w-4" />,
      label: "Pending",
      value: stats.pending,
      tone: "info",
    },
    {
      icon: <CheckCircleIcon className="h-4 w-4" />,
      label: "Active",
      value: stats.active,
      tone: "success",
    },
    {
      icon: <ArrowPathIcon className="h-4 w-4" />,
      label: "Processing",
      value: stats.processing,
      tone: "warning",
      show: stats.processing > 0,
    },
  ];
}

function OrdersLoadingState() {
  return (
    <div className="space-y-4">
      {Array.from({ length: 4 }).map((_, idx) => (
        <OrderCardSkeleton key={idx} />
      ))}
    </div>
  );
}

function OrdersContent({
  orders,
  filteredOrders,
  summaryStatsItems,
  searchTerm,
  setSearchTerm,
  statusFilter,
  setStatusFilter,
  typeFilter,
  setTypeFilter,
  hasActiveFilters,
  clearFilters,
}: {
  orders: OrderSummaryLike[];
  filteredOrders: OrderSummaryLike[];
  summaryStatsItems: StatItem[];
  searchTerm: string;
  setSearchTerm: (v: string) => void;
  statusFilter: string;
  setStatusFilter: (v: OrderStatusFilter) => void;
  typeFilter: string;
  setTypeFilter: (v: OrderTypeFilter) => void;
  hasActiveFilters: boolean;
  clearFilters: () => void;
}) {
  const router = useRouter();

  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 (
    <>
      <SummaryStats variant="inline" items={summaryStatsItems} />
      <SearchFilterBar
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Search by order number..."
        filterValue={statusFilter}
        onFilterChange={value => setStatusFilter(value as OrderStatusFilter)}
        filterOptions={STATUS_FILTER_OPTIONS}
        filterLabel="Filter by status"
      >
        <FilterDropdown
          value={typeFilter}
          onChange={value => setTypeFilter(value as OrderTypeFilter)}
          options={TYPE_FILTER_OPTIONS}
          label="Filter by type"
          width="w-36"
        />
        <ClearFiltersButton onClick={clearFilters} show={hasActiveFilters} />
      </SearchFilterBar>

      {hasActiveFilters && (
        <p className="text-sm text-muted-foreground">
          Showing {filteredOrders.length} of {orders.length} orders
        </p>
      )}

      {filteredOrders.length > 0 ? (
        <div className="border border-border rounded-xl bg-card divide-y divide-border overflow-hidden shadow-[var(--cp-shadow-1)]">
          {filteredOrders.map(order => (
            <OrderCard
              key={String(order.id)}
              order={order}
              variant="list"
              onClick={() => router.push(`/account/orders/${order.id}`)}
            />
          ))}
        </div>
      ) : (
        <AnimatedCard className="p-8" variant="static">
          <SearchEmptyState searchTerm={searchTerm || "filters"} onClearSearch={clearFilters} />
        </AnimatedCard>
      )}
    </>
  );
}

type OrderSummaryLike = Parameters<typeof OrderCard>[0]["order"];

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

  const {
    searchTerm,
    setSearchTerm,
    statusFilter,
    setStatusFilter,
    typeFilter,
    setTypeFilter,
    filteredOrders,
    stats,
    hasActiveFilters,
    clearFilters,
  } = useOrdersFilter({ orders });

  const { errorMessage, showRetry } = useMemo(() => getErrorInfo(isError, error), [error, isError]);
  const summaryStatsItems = useMemo(() => buildOrderSummaryStats(stats), [stats]);

  return (
    <PageLayout icon={<ClipboardDocumentListIcon />} title="My 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>
      )}

      {(isLoading || !orders) && !isError && <OrdersLoadingState />}
      {isError && !isLoading && null}
      {!isLoading && orders && !isError && (
        <OrdersContent
          orders={orders}
          filteredOrders={filteredOrders}
          summaryStatsItems={summaryStatsItems}
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          statusFilter={statusFilter}
          setStatusFilter={setStatusFilter}
          typeFilter={typeFilter}
          setTypeFilter={setTypeFilter}
          hasActiveFilters={hasActiveFilters}
          clearFilters={clearFilters}
        />
      )}
    </PageLayout>
  );
}

export default OrdersListContainer;
