'use client';

import {ArrowDownLeft, ArrowUpRight, BookOpen, RefreshCw} from 'lucide-react';
import {formatInvestmentAmount} from '@/lib/investment-amount';
import type {Locale} from '@/lib/catalog';

type Order = {price: string; quantity: string};
type Props = {
  symbol: string;
  locale: Locale;
  bids?: Order[];
  asks?: Order[];
  available?: boolean;
  loading?: boolean;
  updatedAt?: string;
  unavailableMessage?: string;
  onRefresh?: () => void;
};

const words = {
  fa: {title: 'سفارش‌های خرید و فروش', intro: 'قیمت و تعداد سفارش‌های ثبت‌شده در بازار', buyers: 'خریداران', sellers: 'فروشندگان', buy: 'سفارش‌های خرید', sell: 'سفارش‌های فروش', price: 'قیمت (تومان)', quantity: 'تعداد توکن', empty: 'در حال حاضر سفارشی گزارش نشده است.', unavailable: 'اطلاعات سفارش‌های این بازار در دسترس نیست.', loading: 'در حال دریافت سفارش‌ها…', refresh: 'به‌روزرسانی سفارش‌ها', updated: 'آخرین دریافت', rows: 'ردیف', unit: 'تومان'},
  en: {title: 'Buy and sell orders', intro: 'Prices and quantities reported by the market', buyers: 'Buyers', sellers: 'Sellers', buy: 'Buy orders', sell: 'Sell orders', price: 'Price (TMN)', quantity: 'Token quantity', empty: 'No orders are currently reported.', unavailable: 'Order data for this market is unavailable.', loading: 'Loading orders…', refresh: 'Refresh orders', updated: 'Last received', rows: 'levels', unit: 'TMN'},
  ar: {title: 'أوامر الشراء والبيع', intro: 'أسعار وكميات الأوامر المسجلة في السوق', buyers: 'المشترون', sellers: 'البائعون', buy: 'أوامر الشراء', sell: 'أوامر البيع', price: 'السعر (تومان)', quantity: 'كمية الرموز', empty: 'لا توجد أوامر مُبلّغ عنها حالياً.', unavailable: 'بيانات أوامر هذا السوق غير متاحة.', loading: 'جارٍ تحميل الأوامر…', refresh: 'تحديث الأوامر', updated: 'آخر تحديث', rows: 'صفوف', unit: 'تومان'},
};

export function AssetOrderBook({symbol, locale, bids = [], asks = [], available = false, loading = false, updatedAt, unavailableMessage, onRefresh}: Props) {
  const copy = words[locale];
  const timestamp = updatedAt && Number.isFinite(Date.parse(updatedAt)) ? new Date(updatedAt) : null;
  const groups = [
    {side: 'buy', label: copy.buyers, orders: copy.buy, rows: bids, Icon: ArrowDownLeft},
    {side: 'sell', label: copy.sellers, orders: copy.sell, rows: asks, Icon: ArrowUpRight},
  ];

  return <section className="asset-order-book" aria-labelledby="asset-order-book-title" dir={locale === 'en' ? 'ltr' : 'rtl'}>
    <header className="asset-order-book-heading">
      <div><span className="asset-order-book-eyebrow"><BookOpen size={15}/><bdi>{symbol} / TMN</bdi></span><h2 id="asset-order-book-title">{copy.title}</h2><p>{copy.intro}</p></div>
      <div className="asset-order-book-tools">
        {timestamp && available && <span>{copy.updated} <time dateTime={timestamp.toISOString()}>{timestamp.toLocaleTimeString(locale === 'fa' ? 'fa-IR' : locale === 'ar' ? 'ar' : 'en-GB', {hour: '2-digit', minute: '2-digit', second: '2-digit'})}</time></span>}
        {onRefresh && <button type="button" onClick={onRefresh} disabled={loading} aria-label={copy.refresh} title={copy.refresh}><RefreshCw size={17} className={loading ? 'asset-book-refreshing' : undefined}/></button>}
      </div>
    </header>
    <div className="asset-order-book-grid">{groups.map(({side, label, orders, rows, Icon}) => <section className={`asset-order-side asset-order-side-${side}`} key={side} aria-label={orders}>
      <header><span className="asset-order-side-icon"><Icon size={21}/></span><div><h3>{label}</h3><span>{orders} <bdi>{symbol}</bdi></span></div>{available && <small>{formatInvestmentAmount(String(rows.length), locale)} {copy.rows}</small>}</header>
      <table><caption className="sr-only">{orders} {symbol}</caption><thead><tr><th scope="col">{copy.price}</th><th scope="col">{copy.quantity}</th></tr></thead><tbody>
        {available && rows.map((row, index) => <tr key={`${row.price}-${index}`}><td className="asset-order-price"><bdi>{formatInvestmentAmount(row.price, locale)}</bdi></td><td><bdi>{formatInvestmentAmount(row.quantity, locale)}</bdi></td></tr>)}
        {(!available || !rows.length) && <tr><td colSpan={2} className="asset-order-empty"><span role={loading ? 'status' : undefined}>{loading && !available ? copy.loading : available ? copy.empty : unavailableMessage || copy.unavailable}</span></td></tr>}
      </tbody></table>
    </section>)}</div>
  </section>;
}
