"use client";

import { formatQty, productLabel, quantityWithUnit } from "@/lib/product-unit";

import { AccessAction } from "@/features/auth/components/access-action";

import { OrderStatusBadge as StatusBadge } from "@/components/order-status-badge";

import { displayValue, formatDate } from "@/lib/display-format";

import { useState } from "react";
import { OrderActions } from "./order-actions";
import {
  ShoppingCart,
  Plus,
  Search,
  Eye,
  ChevronLeft,
  ChevronRight,
  Package,
  CreditCard,
  Truck,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { OrderTrackingModal } from "./order-tracking-modal";
import type {
  OrderResponseDTO,
  OrderItemResponseDTO,
} from "../dtos/order.dto";

// ============================================
// Order Items Summary
// ============================================
function OrderItemsSummary({ items }: { items: OrderItemResponseDTO[] }) {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <div className="space-y-1">
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="text-left text-xs text-blue-600 hover:text-blue-800"
      >
        {items.length} item{items.length !== 1 ? "s" : ""} ·{" "}
        {formatQty(items.reduce((sum, i) => sum + i.quantity, 0))} total
        qty
      </button>
      {isExpanded && (
        <div className="mt-2 space-y-1 rounded-lg border border-gray-100 bg-gray-50 p-2">
          {items.map((item) => (
            <div
              key={item.id}
              className="flex items-center justify-between text-xs"
            >
              <div className="flex items-center gap-1.5">
                {item.imageUrl ? (
                  <img src={item.imageUrl} alt={item.productName} className="h-3.5 w-3.5 rounded object-cover" />
                ) : item.isBusinessCard ? (
                  <CreditCard className="h-3 w-3 text-pink-500" />
                ) : (
                  <Package className="h-3 w-3 text-gray-400" />
                )}
                <span className="text-gray-700">{productLabel(item.productName, item.defaultUnit)}</span>
                {item.variantName && (
                  <span className="text-gray-400">({displayValue(item.variantName)})</span>
                )}
                {item.size && (
                  <span className="text-gray-400">[{item.size}]</span>
                )}
                {item.isBusinessCard && item.businessCards.length > 0 && (
                  <span className="text-pink-500">
                    · {item.businessCards.length} card
                    {item.businessCards.length !== 1 ? "s" : ""}
                  </span>
                )}
              </div>
              <span className="font-medium text-gray-900">
                ×{quantityWithUnit(item.quantity, item.defaultUnit)}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ============================================
// Skeleton Loader (White Theme)
// ============================================
function SkeletonTable() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-4 rounded-lg border border-gray-200 bg-gray-50 p-4"
        >
          <div className="h-10 w-10 animate-pulse rounded-lg bg-gray-200" />
          <div className="flex-1 space-y-2">
            <div className="h-4 w-32 animate-pulse rounded bg-gray-200" />
            <div className="h-3 w-48 animate-pulse rounded bg-gray-200" />
          </div>
          <div className="h-6 w-16 animate-pulse rounded-full bg-gray-200" />
        </div>
      ))}
    </div>
  );
}

// ============================================
// Empty State (White Theme)
// ============================================
function EmptyState({ searchQuery }: { searchQuery?: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16">
      <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-2xl bg-gray-100">
        <ShoppingCart className="h-8 w-8 text-gray-400" />
      </div>
      <h3 className="mb-1 text-lg font-semibold text-gray-900">
        {searchQuery ? "No orders found" : "No orders yet"}
      </h3>
      <p className="text-sm text-gray-500">
        {searchQuery
          ? "Try adjusting your search criteria."
          : "Create your first order to get started."}
      </p>
    </div>
  );
}

// ============================================
// Actions Dropdown (White Theme)
// ============================================
function ActionsDropdown({
  order,
  onView,
  onTrack,
  onUpdated,
}: {
  order: OrderResponseDTO;
  onView: (order: OrderResponseDTO) => void;
  onTrack: (id: string) => void;
  onUpdated?: () => void | Promise<void>;
}) {
  return (
    <div className="inline-flex w-max flex-nowrap items-center justify-end gap-1.5 align-middle [&>button]:h-8 [&>button]:w-8 [&>button]:shrink-0 [&>button]:justify-center [&>button]:p-0">
      <button
        title="View order details"
        aria-label="View order details"
        onClick={() => onView(order)}
        className="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-700 transition-colors hover:bg-gray-50"
      >
        <Eye aria-hidden="true" className="h-4 w-4" />
      </button>
      <OrderActions order={order} onUpdated={onUpdated} showDelete />
      <button
        type="button"
        onClick={() => onTrack(order.id)}
        aria-haspopup="dialog"
        title="Track order"
        aria-label="Track order"
        className="inline-flex items-center gap-1.5 whitespace-nowrap rounded-lg border border-blue-200 bg-blue-50 px-3 py-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-100"
      >
        <Truck aria-hidden="true" className="h-4 w-4" />
      </button>

    </div>
  );
}

// ============================================
// Order List Props
// ============================================
interface OrderListProps {
  onUpdated?: () => void | Promise<void>;
  orders: OrderResponseDTO[];
  isLoading: boolean;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onAdd?: () => void;
  onView: (order: OrderResponseDTO) => void;
  page: number;
  totalPages: number;
  onPageChange: (page: number) => void;
}

// ============================================
// Order List Component (White Theme)
// ============================================
export function OrderList({
  orders,
  isLoading,
  searchQuery,
  onSearchChange,
  onAdd,
  onView,
  page,
  onUpdated,
  totalPages,
  onPageChange,
}: OrderListProps) {
  const [trackingOrderId, setTrackingOrderId] = useState<string | null>(null);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Orders</h1>
          <p className="mt-1 text-sm text-gray-500">
            Manage all orders and track their status
          </p>
        </div>
        {onAdd && (
          <AccessAction ability="orders.create"><Button onClick={onAdd} size="md">
            <Plus className="h-4 w-4" />
            New Order
          </Button></AccessAction>
        )}
      </div>

      {/* Search */}
      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
        <input
          type="text"
          placeholder="Search orders..."
          value={searchQuery}
          onChange={(e) => onSearchChange(e.target.value)}
          className="block w-full rounded-lg border border-gray-200 bg-gray-50 py-2.5 pl-10 pr-4 text-sm text-gray-900 shadow-sm transition-colors placeholder:text-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-1 focus:ring-blue-500"
        />
      </div>

      {/* Table */}
      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
        {isLoading ? (
          <div className="p-6">
            <SkeletonTable />
          </div>
        ) : orders.length === 0 ? (
          <EmptyState searchQuery={searchQuery} />
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-gray-200 text-left">
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Order
                    </th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Company
                    </th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Community
                    </th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Items
                    </th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">Ordered By</th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">Urgent</th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Status
                    </th>
                    <th className="px-6 py-3 text-xs font-medium uppercase tracking-wider text-gray-500">
                      Created
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {orders.map((order) => (
                    <tr
                      key={order.id}
                      className="transition-colors hover:bg-gray-50"
                    >
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-3">
                          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-indigo-50">
                            <ShoppingCart className="h-5 w-5 text-indigo-600" />
                          </div>
                          <div>
                            <p className="text-sm font-medium text-gray-900">
                              {displayValue(order.orderNumber)}
                            </p>
                            {order.notes && (
                              <p className="max-w-xs truncate text-xs text-gray-500">
                                {order.notes}
                              </p>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <p className="text-sm text-gray-700">
                          {displayValue(order.companyName)}
                        </p>
                      </td>
                      <td className="px-6 py-4">
                        <p className="text-sm text-gray-700">
                          {displayValue(order.departmentName)}
                        </p>
                      </td>
                      <td className="px-6 py-4">
                        <OrderItemsSummary items={order.items} />
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-700"><p>{displayValue(order.personName)}</p><p className="text-xs text-gray-500">{order.email}</p></td>
                      <td className="px-6 py-4 text-sm"><span className={order.isUrgent ? "font-medium text-red-600" : "text-gray-500"}>{order.isUrgent ? "Urgent" : "No"}</span></td>
                      <td className="px-6 py-4">
                        <StatusBadge status={order.status} />
                      </td>
                      <td className="px-6 py-4">
                        <p className="text-sm text-gray-500">
                          {formatDate(order.createdAt)}
                        </p>
                      </td>
                      <td className="whitespace-nowrap px-6 py-4 text-right">
                        <ActionsDropdown
                          order={order}
                          onView={onView}
                          onTrack={setTrackingOrderId}
                          onUpdated={onUpdated}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="flex flex-wrap items-center justify-between gap-3 border-t border-gray-200 px-6 py-3">
                <p className="text-xs text-gray-500">
                  Page {page} of {totalPages}
                </p>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => onPageChange(page - 1)}
                    disabled={page <= 1}
                    className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    <ChevronLeft className="h-4 w-4" />
                  </button>
                  <button
                    onClick={() => onPageChange(page + 1)}
                    disabled={page >= totalPages}
                    className="rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-50"
                  >
                    <ChevronRight className="h-4 w-4" />
                  </button>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {trackingOrderId && (
        <OrderTrackingModal
          key={trackingOrderId}
          orderId={trackingOrderId}
          onClose={() => setTrackingOrderId(null)}
        />
      )}
    </div>
  );
}
