'use client';

import Link from 'next/link';
import { useMemo } from 'react';

interface Order {
  orderNumber: string;
  date: string;
  time: string;
  products: string[];
  cardsCount: number;
  total: number;
  status: string;
  paymentMethod: string;
}

interface OrdersTableProps {
  orders: Order[];
}

/**
 * Returns Tailwind classes and an icon name based on the order status.
 * The function is defensive – if an unknown status is supplied it falls back
 * to a neutral style instead of throwing.
 */
function getStatusStyle(status: string) {
  switch (status) {
    case 'مكتمل':
      return {
        bg: 'bg-green-100',
        text: 'text-green-700',
        icon: 'ri-checkbox-circle-fill',
      };
    case 'قيد المعالجة':
      return {
        bg: 'bg-amber-100',
        text: 'text-amber-700',
        icon: 'ri-time-fill',
      };
    case 'ملغي':
      return {
        bg: 'bg-red-100',
        text: 'text-red-700',
        icon: 'ri-close-circle-fill',
      };
    default:
      return {
        bg: 'bg-gray-100',
        text: 'text-gray-700',
        icon: 'ri-question-line',
      };
  }
}

/**
 * Returns the appropriate icon name for the payment method.
 * Any unknown method falls back to a generic card icon.
 */
function getPaymentIcon(method: string) {
  return method === 'المحفظة' ? 'ri-wallet-3-line' : 'ri-bank-card-line';
}

/**
 * OrdersTable – a reusable component that renders a list of orders.
 * It gracefully handles empty data and unexpected runtime errors.
 */
export default function OrdersTable({ orders }: OrdersTableProps) {
  // Guard against undefined / null / non‑array values.
  const safeOrders = useMemo(() => {
    if (!Array.isArray(orders)) return [];
    return orders;
  }, [orders]);

  if (safeOrders.length === 0) {
    // Render a friendly placeholder instead of returning null –
    // this avoids layout shifts in parent components.
    return (
      <div className="p-6 text-center text-gray-500">
        لا توجد طلبات للعرض
      </div>
    );
  }

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
      <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
        <h2 className="text-lg font-bold text-gray-900">
          جميع الطلبات ({safeOrders.length})
        </h2>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                رقم الطلب
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                التاريخ والوقت
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                المنتجات
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                عدد البطاقات
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                طريقة الدفع
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                الإجمالي
              </th>
              <th className="px-6 py-4 text-right text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                الحالة
              </th>
              <th className="px-6 py-4 text-center text-xs font-bold text-gray-500 uppercase whitespace-nowrap">
                الإجراءات
              </th>
            </tr>
          </thead>

          <tbody className="divide-y divide-gray-50">
            {safeOrders.map((order) => {
              const statusStyle = getStatusStyle(order.status);

              // Defensive URL creation – removes any stray '#' characters.
              const orderUrl = `/orders/${order.orderNumber.replace('#', '')}`;

              return (
                <tr
                  key={order.orderNumber}
                  className="hover:bg-blue-50/30 transition-colors"
                >
                  <td className="px-6 py-4">
                    <span className="text-blue-600 font-bold text-sm whitespace-nowrap">
                      {order.orderNumber}
                    </span>
                  </td>

                  <td className="px-6 py-4">
                    <div className="text-gray-900 text-sm font-medium whitespace-nowrap">
                      {order.date}
                    </div>
                    <div className="text-xs text-gray-400 mt-0.5 whitespace-nowrap">
                      {order.time}
                    </div>
                  </td>

                  <td className="px-6 py-4">
                    <div className="flex flex-wrap gap-1 max-w-[220px]">
                      {order.products.slice(0, 2).map((product, i) => (
                        <span
                          key={i}
                          className="inline-block bg-blue-50 text-blue-700 text-xs px-2 py-0.5 rounded-full whitespace-nowrap"
                        >
                          {product}
                        </span>
                      ))}

                      {order.products.length > 2 && (
                        <span className="inline-block bg-gray-100 text-gray-600 text-xs px-2 py-0.5 rounded-full whitespace-nowrap">
                          +{order.products.length - 2} أخرى
                        </span>
                      )}
                    </div>
                  </td>

                  <td className="px-6 py-4">
                    <div className="flex items-center gap-1.5">
                      <i className="ri-coupon-line text-gray-400"></i>
                      <span className="text-gray-900 font-semibold text-sm whitespace-nowrap">
                        {order.cardsCount}
                      </span>
                    </div>
                  </td>

                  <td className="px-6 py-4">
                    <div className="flex items-center gap-1.5">
                      <i
                        className={`${getPaymentIcon(order.paymentMethod)} text-gray-400`}
                      ></i>
                      <span className="text-gray-700 text-sm whitespace-nowrap">
                        {order.paymentMethod}
                      </span>
                    </div>
                  </td>

                  <td className="px-6 py-4">
                    <span className="text-gray-900 font-bold text-sm whitespace-nowrap">
                      {order.total.toLocaleString('ar-SA')} ر.س
                    </span>
                  </td>

                  <td className="px-6 py-4">
                    <span
                      className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold ${statusStyle.bg} ${statusStyle.text} whitespace-nowrap`}
                    >
                      <i className={`${statusStyle.icon} text-sm`}></i>
                      {order.status}
                    </span>
                  </td>

                  <td className="px-6 py-4 text-center">
                    {/* The Link component must have a child; using an <i> icon is valid. */}
                    <Link
                      href={orderUrl}
                      className="inline-flex items-center justify-center w-9 h-9 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                      title="عرض التفاصيل"
                    >
                      <i className="ri-eye-line text-lg"></i>
                    </Link>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
