'use client';

/**
 * OrderTable — displays a list of orders with status management controls.
 *
 * Validates: Requirements 9.1, 9.3
 */

import StatusBadge from './StatusBadge';
import { formatPrice, formatDateTime } from '../../lib/formatters';

/** All valid order status values for the dropdown. */
const ORDER_STATUSES = [
  'pending',
  'confirmed',
  'preparing',
  'ready',
  'delivered',
  'cancelled',
];

/**
 * Builds a compact item summary string from an array of order items.
 * e.g. "2x Burger, 1x Coke"
 *
 * @param {Array<{ quantity: number, menuItem?: { name: string }, name?: string }>} orderItems
 * @returns {string}
 */
function buildItemSummary(orderItems) {
  if (!Array.isArray(orderItems) || orderItems.length === 0) return '—';
  return orderItems
    .map((item) => {
      const name = item.menuItem?.name ?? item.name ?? 'Item';
      return `${item.quantity}x ${name}`;
    })
    .join(', ');
}

/**
 * @param {{
 *   orders: Array<{
 *     id: number|string,
 *     referenceNumber: string,
 *     customerName: string,
 *     fulfillmentMethod: string,
 *     orderItems: Array<{ quantity: number, menuItem?: { name: string }, name?: string }>,
 *     totalPrice: number,
 *     status: string,
 *     createdAt: string,
 *   }>,
 *   onStatusChange: (orderId: number|string, newStatus: string) => void,
 * }} props
 */
export default function OrderTable({ orders = [], onStatusChange }) {
  if (orders.length === 0) {
    return (
      <div className="rounded-lg border border-secondary-200 bg-white px-6 py-12 text-center">
        <p className="text-secondary-500">No orders found.</p>
      </div>
    );
  }

  return (
    <div className="overflow-x-auto rounded-lg border border-secondary-200 bg-white">
      <table className="min-w-full divide-y divide-secondary-200 text-sm">
        <thead className="bg-secondary-50">
          <tr>
            {[
              'Reference',
              'Customer',
              'Fulfillment',
              'Items',
              'Total',
              'Status',
              'Actions',
            ].map((heading) => (
              <th
                key={heading}
                scope="col"
                className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide text-secondary-600"
              >
                {heading}
              </th>
            ))}
          </tr>
        </thead>
        <tbody className="divide-y divide-secondary-100">
          {orders.map((order) => (
            <tr key={order.id} className="hover:bg-secondary-50 transition-colors">
              {/* Reference */}
              <td className="whitespace-nowrap px-4 py-3 font-mono text-xs text-secondary-700">
                {order.referenceNumber}
              </td>

              {/* Customer */}
              <td className="px-4 py-3">
                <div className="font-medium text-secondary-900">{order.customerName}</div>
                <div className="text-xs text-secondary-500">
                  {formatDateTime(order.createdAt)}
                </div>
              </td>

              {/* Fulfillment */}
              <td className="whitespace-nowrap px-4 py-3 capitalize text-secondary-700">
                {order.fulfillmentMethod}
              </td>

              {/* Items */}
              <td className="px-4 py-3 text-secondary-700">
                {buildItemSummary(order.orderItems)}
              </td>

              {/* Total */}
              <td className="whitespace-nowrap px-4 py-3 font-medium text-secondary-900">
                {formatPrice(Number(order.totalPrice))}
              </td>

              {/* Status */}
              <td className="whitespace-nowrap px-4 py-3">
                <StatusBadge status={order.status} />
              </td>

              {/* Actions */}
              <td className="whitespace-nowrap px-4 py-3">
                <label htmlFor={`status-${order.id}`} className="sr-only">
                  Change status for order {order.referenceNumber}
                </label>
                <select
                  id={`status-${order.id}`}
                  value={order.status}
                  onChange={(e) => onStatusChange(order.id, e.target.value)}
                  className="rounded-md border border-secondary-300 bg-white px-2 py-1.5 text-xs text-secondary-700 shadow-sm focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500"
                >
                  {ORDER_STATUSES.map((s) => (
                    <option key={s} value={s} className="capitalize">
                      {s.charAt(0).toUpperCase() + s.slice(1)}
                    </option>
                  ))}
                </select>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
