'use client';

import Link from 'next/link';
import { useI18n } from '@/lib/i18n/context';

export type OrderProductItem = string | { product_name?: string };
export interface OrderItem {
  id: number;
  order_number: string;
  products?: OrderProductItem[];
  cards_count?: number;
  total: number;
  status: string;
  created_at?: string;
}

interface LatestOrdersProps {
  orders: OrderItem[];
  loading?: boolean;
}

function productBreadcrumb(products: OrderProductItem[], dash: string): string {
  return (products ?? [])
    .map((p) => (typeof p === 'string' ? p : (p?.product_name ?? '').trim()))
    .filter(Boolean)
    .join(' > ');
}

export default function LatestOrders({ orders, loading }: LatestOrdersProps) {
  const { t, isRtl, locale } = useI18n();
  const numberLocale = locale === 'ar' ? 'ar-SA' : 'en-US';

  const moreIcon = isRtl ? 'ri-arrow-left-s-line' : 'ri-arrow-right-s-line';

  const formatOrderWhen = (iso?: string) => {
    if (!iso) return '';
    const d = new Date(iso);
    const time = d.toLocaleTimeString(numberLocale, { hour: '2-digit', minute: '2-digit' });
    const date = d.toLocaleDateString(numberLocale);
    return `${time} - ${date}`;
  };

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 flex flex-col h-full">
      <div className="flex items-center justify-between gap-3 mb-4">
        <h2 className="text-lg font-bold text-gray-900 whitespace-nowrap">{t('latestOrders.title')}</h2>
        <Link
          href="/orders"
          className="text-[#2563eb] hover:text-[#1d4ed8] font-semibold cursor-pointer whitespace-nowrap flex items-center gap-1 text-sm"
        >
          <span>{t('latestOrders.viewMore')}</span>
          <i className={`${moreIcon} text-lg`} aria-hidden />
        </Link>
      </div>

      <div className="flex-1 overflow-hidden">
        {loading ? (
          <div className="space-y-3">
            {[1, 2, 3].map((i) => (
              <div key={i} className="h-20 bg-gray-100 rounded-lg animate-pulse" />
            ))}
          </div>
        ) : orders.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-10 text-gray-400">
            <i className="ri-file-list-3-line text-4xl mb-2" aria-hidden />
            <span className="text-sm">{t('latestOrders.empty')}</span>
          </div>
        ) : (
          <div className="space-y-3">
            {orders.map((order) => {
              const names = (order.products ?? []).slice(0, 8);
              const breadcrumb =
                names.length > 0
                  ? productBreadcrumb(names, t('common.dash'))
                  : order.cards_count
                    ? t('latestOrders.cardsCount', { count: String(order.cards_count) })
                    : '';

              return (
                <Link
                  key={order.id}
                  href={`/orders/${order.id}`}
                  className="block p-4 rounded-xl bg-[#f9fafb] hover:bg-sky-50/60 border border-transparent hover:border-sky-100 transition-colors"
                >
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1 mb-1">
                        <span className="text-blue-600 font-bold text-sm">{order.order_number}</span>
                        {order.created_at && (
                          <span className="text-gray-500 text-xs">{formatOrderWhen(order.created_at)}</span>
                        )}
                      </div>
                      {breadcrumb && (
                        <p className="text-sm text-gray-700 leading-relaxed line-clamp-2">{breadcrumb}</p>
                      )}
                    </div>
                    <div
                      className={`shrink-0 flex flex-col items-end ${isRtl ? 'text-left' : 'text-right'}`}
                    >
                      <span className="text-base sm:text-lg font-bold text-gray-900 tabular-nums">
                        {order.total.toLocaleString(numberLocale, { maximumFractionDigits: 2 })}{' '}
                        <span className="text-gray-500 text-xs font-medium">{t('common.sar')}</span>
                      </span>
                      {order.cards_count != null && order.cards_count > 0 && (
                        <span className="text-xs text-gray-500 mt-1">
                          {t('latestOrders.quantityLine', { count: String(order.cards_count) })}
                        </span>
                      )}
                    </div>
                  </div>
                </Link>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
