import MarketProbabilityChart from '@/components/user/default/market-probability-chart';
import OrderBook from '@/components/user/default/order-book';
import { useApiSWR } from '@/hooks/useSWR';
import {
  TMarketOutcome,
  TOrderBook,
  TOrderBookLevel,
} from '@/types/market.types';
import { useEchoPublic } from '@laravel/echo-react';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

const round6 = (n: number) => Math.round(n * 1e6) / 1e6;

/**
 * The CLOB market's live depth ladder + focused probability graph, shown below
 * the main chart. Follows the outcome selected in the trade panel (shared
 * state) — clicking a book level prefills the panel's limit price via onPickPrice.
 */
export default function ClobBook({
  slug,
  selected,
  onPickPrice,
  changes,
  onTraded,
}: {
  slug: string;
  selected: TMarketOutcome;
  onPickPrice?: (price: number) => void;
  changes: Record<number, number | null>;
  onTraded?: () => void;
}) {
  const { t } = useTranslation();
  const [view, setView] = useState<'book' | 'graph'>('book');

  const { data: book, mutate: mutateBook } = useApiSWR<TOrderBook>(
    `/markets/${slug}/book`,
  );

  useEchoPublic(
    `market.${slug}`,
    'MarketBookUpdated',
    (e: { book: TOrderBook }) => {
      if (e?.book) mutateBook(e.book, false);
      onTraded?.();
    },
  );

  // The API returns a single YES-denominated book; mirror it for the complement.
  const { asks, bids } = useMemo(() => {
    if (!book)
      return { asks: [] as TOrderBookLevel[], bids: [] as TOrderBookLevel[] };
    const isRef = book.reference_outcome_id === selected.id;
    if (isRef) return { asks: book.asks, bids: book.bids };
    return {
      asks: book.bids
        .map((b) => ({ price: round6(1 - b.price), shares: b.shares }))
        .sort((a, b) => a.price - b.price),
      bids: book.asks
        .map((a) => ({ price: round6(1 - a.price), shares: a.shares }))
        .sort((a, b) => b.price - a.price),
    };
  }, [book, selected.id]);

  const change = changes[selected.id];

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-4 border-b border-black/5 dark:border-white/10">
        {(['book', 'graph'] as const).map((v) => (
          <button
            key={v}
            type="button"
            onClick={() => setView(v)}
            className={`-mb-px border-b-2 pb-2 text-sm font-semibold transition-colors ${
              view === v
                ? 'border-foreground text-foreground'
                : 'border-transparent text-black/40 hover:text-black/70 dark:text-white/40 dark:hover:text-white/70'
            }`}
          >
            {v === 'book' ? t('Order Book') : t('Graph')}
          </button>
        ))}
      </div>

      {view === 'book' ? (
        <OrderBook
          asks={asks}
          bids={bids}
          outcomeLabel={selected.title}
          lastPrice={selected.probability}
          onPick={onPickPrice}
        />
      ) : (
        <div>
          <div className="mb-1 flex items-baseline gap-2">
            <span
              className="text-2xl font-bold"
              style={{ color: selected.color ?? undefined }}
            >
              {Math.round((selected.probability ?? 0) * 100)}% {t('chance')}
            </span>
            {change != null && change !== 0 && (
              <span
                className={`text-sm font-semibold ${
                  change > 0 ? 'text-green-500' : 'text-red-500'
                }`}
              >
                {change > 0 ? '▲' : '▼'} {Math.abs(change)}%
              </span>
            )}
          </div>
          <MarketProbabilityChart slug={slug} focusName={selected.title} />
        </div>
      )}
    </div>
  );
}
