"use client";

import { useState, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useOrders } from "@/features/orders/hooks/use-orders";
import { AdminLayout } from "@/components/admin-layout";
import { OrderList } from "@/features/orders/components/order-list";
import type { OrderResponseDTO, OrderStatus } from "@/features/orders/dtos/order.dto";

// ============================================
// Status Tabs Config
// ============================================
const STATUS_TABS: { key: OrderStatus | "all"; label: string }[] = [
  { key: "all", label: "All" },
  { key: "ordered", label: "Ordered" },
  { key: "processing", label: "Processing" },
  { key: "dispatched", label: "Dispatched" },
  { key: "delivered", label: "Delivered" },
];

// ============================================
// Month/Year Options
// ============================================
function getMonthYearOptions(): { value: string; label: string }[] {
  const options: { value: string; label: string }[] = [
    { value: "all", label: "All Months" },
  ];
  const now = new Date();
  for (let i = 0; i < 12; i++) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    const value = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
    const label = d.toLocaleDateString("en-US", { month: "long", year: "numeric" });
    options.push({ value, label });
  }
  return options;
}

// ============================================
// Orders Page
// P1: Calls hook only. Never call service, adapter, or apiClient directly.
// P3: Always handle: loading → skeleton | error → message | empty → empty state.
// P4: Never import service / adapter / apiClient.
// ============================================

export default function OrdersPage() {
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState("");
  const [page, setPage] = useState(1);
  const [activeTab, setActiveTab] = useState<OrderStatus | "all">("all");
  const [monthFilter, setMonthFilter] = useState("all");

  // H1: Calls hook only
  const { orders, isLoading, error } = useOrders({

    search: searchQuery || undefined,
  });

  const perPage = 15;

  // Filter orders by status tab and month/year
  const filteredOrders = useMemo(() => {
    let result = orders;

    // Filter by status tab
    if (activeTab !== "all") {
      result = result.filter((o) => o.status === activeTab);
    }

    // Filter by month/year
    if (monthFilter !== "all") {
      const [year, month] = monthFilter.split("-").map(Number);
      result = result.filter((o) => {
        const d = new Date(o.createdAt);
        return d.getFullYear() === year && d.getMonth() + 1 === month;
      });
    }

    return result;
  }, [orders, activeTab, monthFilter]);

  const totalPages = Math.max(1, Math.ceil(filteredOrders.length / perPage));

  // Count orders per status (from all orders, not filtered by month)
  const statusCounts = useMemo(() => {
    const counts: Record<string, number> = { all: orders.length };
    for (const order of orders) {
      counts[order.status] = (counts[order.status] || 0) + 1;
    }
    return counts;
  }, [orders]);

  // --- Handlers ---
  const handleAdd = useCallback(() => {
    router.push("/orders/new");
  }, [router]);

  const handleView = useCallback(
    (order: OrderResponseDTO) => {
      router.push(`/orders/${order.id}`);
    },
    [router]
  );

  const handleTabChange = useCallback((tab: OrderStatus | "all") => {
    setActiveTab(tab);
    setPage(1);
  }, []);

  const handleMonthChange = useCallback((value: string) => {
    setMonthFilter(value);
    setPage(1);
  }, []);

  const monthYearOptions = useMemo(() => getMonthYearOptions(), []);

  return (
    <AdminLayout>
      {/* Error State */}
      {error && !isLoading && orders.length === 0 && (
        <div className="mb-6 rounded-xl border border-red-200 bg-red-50 p-4">
          <p className="text-sm text-red-600">{error}</p>
        </div>
      )}

      {/* Status Tabs */}
      <div className="mb-4 flex items-center gap-1 overflow-x-auto rounded-lg border border-gray-200 bg-white p-1">
        {STATUS_TABS.map((tab) => {
          const count = statusCounts[tab.key] || 0;
          const isActive = activeTab === tab.key;
          return (
            <button
              key={tab.key}
              onClick={() => handleTabChange(tab.key)}
              className={`inline-flex items-center gap-1.5 rounded-md px-3 py-2 text-sm font-medium transition-colors whitespace-nowrap ${
                isActive
                  ? "bg-blue-50 text-blue-700 border border-blue-200"
                  : "text-gray-600 hover:bg-gray-50 hover:text-gray-900 border border-transparent"
              }`}
            >
              {tab.label}
              <span
                className={`rounded-full px-1.5 py-0.5 text-[10px] font-bold ${
                  isActive
                    ? "bg-blue-100 text-blue-700"
                    : "bg-gray-100 text-gray-500"
                }`}
              >
                {count}
              </span>
            </button>
          );
        })}

        {/* Month/Year Filter */}
        <div className="ml-auto">
          <select
            value={monthFilter}
            onChange={(e) => handleMonthChange(e.target.value)}
            className="rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-sm text-gray-700 shadow-sm focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
          >
            {monthYearOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* P2: Sub-components receive typed DTOs as props */}
      <OrderList
        orders={filteredOrders.slice((page - 1) * perPage, page * perPage)}
        isLoading={isLoading}
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        onAdd={handleAdd}
        onView={handleView}
        page={page}
        totalPages={totalPages}
        onPageChange={setPage}
      />
    </AdminLayout>
  );
}
