import { useMemo } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import type {
  DashboardRealtimeTradeTick,
  DashboardStockOrderBookResponse,
} from "@/features/trade/types/trade.types";
import type { BookRow } from "./orderbook-utils";
import {
  buildBookRows,
  buildFallbackLevelsFromTick,
  hasOrderBookLevelData,
  resolveReferencePrice,
} from "./orderbook-utils";
import {
  BookHeader,
  BookSideRows,
  CumulativeRows,
  CurrentPriceBar,
  OrderBookSkeleton,
  SummaryPanel,
  TradeTape,
} from "./orderbook-sections";

interface OrderBookProps {
  symbol?: string;
  referencePrice?: number;
  latestTick: DashboardRealtimeTradeTick | null;
  recentTicks: DashboardRealtimeTradeTick[];
  orderBook: DashboardStockOrderBookResponse | null;
  isLoading?: boolean;
}

/**
 * @description 호가창 — 실시간 매도·매수 10호가와 체결 목록을 표시합니다.
 * @see features/trade/components/orderbook/orderbook-utils.ts 호가 계산/포맷 유틸
 * @see features/trade/components/orderbook/orderbook-sections.tsx 호가/체결/요약 UI 섹션
 */
export function OrderBook({
  symbol,
  referencePrice,
  latestTick,
  recentTicks,
  orderBook,
  isLoading,
}: OrderBookProps) {
  const realtimeLevels = useMemo(() => orderBook?.levels ?? [], [orderBook]);
  const fallbackLevelsFromTick = useMemo(
    () => buildFallbackLevelsFromTick(latestTick),
    [latestTick],
  );
  const hasRealtimeLevelData = useMemo(
    () => hasOrderBookLevelData(realtimeLevels),
    [realtimeLevels],
  );
  const levels = useMemo(() => {
    if (hasRealtimeLevelData) return realtimeLevels;
    return fallbackLevelsFromTick;
  }, [fallbackLevelsFromTick, hasRealtimeLevelData, realtimeLevels]);

  const isTickFallbackActive =
    !hasRealtimeLevelData && fallbackLevelsFromTick.length > 0;

  const latestPrice =
    latestTick?.price && latestTick.price > 0 ? latestTick.price : 0;

  const basePrice = resolveReferencePrice({ referencePrice, latestTick });

  const askRows: BookRow[] = useMemo(
    () =>
      buildBookRows({
        levels,
        side: "ask",
        basePrice,
        latestPrice,
      }),
    [levels, basePrice, latestPrice],
  );

  const bidRows: BookRow[] = useMemo(
    () =>
      buildBookRows({
        levels,
        side: "bid",
        basePrice,
        latestPrice,
      }),
    [levels, basePrice, latestPrice],
  );

  const askMax = useMemo(() => Math.max(1, ...askRows.map((r) => r.size)), [askRows]);
  const bidMax = useMemo(() => Math.max(1, ...bidRows.map((r) => r.size)), [bidRows]);
  const mobileAskRows = useMemo(() => askRows.slice(0, 6), [askRows]);
  const mobileBidRows = useMemo(() => bidRows.slice(0, 6), [bidRows]);

  const { bestAsk, spread, totalAsk, totalBid, imbalance } = useMemo(() => {
    const resolvedBestAsk = levels.find((level) => level.askPrice > 0)?.askPrice ?? 0;
    const resolvedBestBid = levels.find((level) => level.bidPrice > 0)?.bidPrice ?? 0;
    const resolvedSpread =
      resolvedBestAsk > 0 && resolvedBestBid > 0
        ? resolvedBestAsk - resolvedBestBid
        : 0;
    const resolvedTotalAsk =
      orderBook?.totalAskSize && orderBook.totalAskSize > 0
        ? orderBook.totalAskSize
        : (latestTick?.totalAskSize ?? 0);
    const resolvedTotalBid =
      orderBook?.totalBidSize && orderBook.totalBidSize > 0
        ? orderBook.totalBidSize
        : (latestTick?.totalBidSize ?? 0);
    const resolvedImbalance =
      resolvedTotalAsk + resolvedTotalBid > 0
        ? ((resolvedTotalBid - resolvedTotalAsk) /
            (resolvedTotalAsk + resolvedTotalBid)) *
          100
        : 0;

    return {
      bestAsk: resolvedBestAsk,
      spread: resolvedSpread,
      totalAsk: resolvedTotalAsk,
      totalBid: resolvedTotalBid,
      imbalance: resolvedImbalance,
    };
  }, [latestTick?.totalAskSize, latestTick?.totalBidSize, levels, orderBook]);

  if (!symbol) {
    return (
      <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
        종목을 선택해주세요.
      </div>
    );
  }
  if (isLoading && !orderBook && fallbackLevelsFromTick.length === 0) {
    return <OrderBookSkeleton />;
  }
  if (!orderBook && fallbackLevelsFromTick.length === 0) {
    return (
      <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
        호가 정보를 가져오지 못했습니다.
      </div>
    );
  }

  return (
    <div className="flex h-full min-h-0 flex-col bg-white dark:bg-[linear-gradient(180deg,rgba(13,13,24,0.95),rgba(8,8,18,0.98))]">
      <Tabs defaultValue="normal" className="h-full min-h-0">
        {/* ========== ORDERBOOK TAB HEADER ========== */}
        <div className="border-b border-border/60 bg-muted/15 px-2 pt-2 dark:border-brand-800/50 dark:bg-brand-950/60">
          <TabsList variant="line" className="w-full justify-start">
            <TabsTrigger value="normal" className="px-3">
              일반호가
            </TabsTrigger>
            <TabsTrigger value="cumulative" className="px-3">
              누적호가
            </TabsTrigger>
            <TabsTrigger value="order" className="px-3">
              호가주문
            </TabsTrigger>
          </TabsList>
        </div>

        {/* ========== ORDERBOOK NORMAL TAB ========== */}
        <TabsContent value="normal" className="min-h-0 flex-1">
          <div className="flex h-full min-h-0 flex-col border-t dark:border-brand-800/45 xl:grid xl:grid-cols-[minmax(0,1fr)_220px_220px] 2xl:grid-cols-[minmax(0,1fr)_250px_240px] xl:overflow-hidden">
            <div className="flex min-h-0 flex-col xl:border-r dark:border-brand-800/45">
              {isTickFallbackActive && (
                <div className="border-b border-amber-200 bg-amber-50 px-2 py-1 text-[11px] text-amber-700 dark:border-amber-700/40 dark:bg-amber-900/20 dark:text-amber-200">
                  시간외 전용 호가(`H0STOAA0`) 미수신 상태입니다.
                  체결(`H0UNCNT0`) 1호가 기준으로 표시 중입니다.
                </div>
              )}
              <BookHeader />
              <div className="xl:hidden">
                <BookSideRows rows={mobileAskRows} side="ask" maxSize={askMax} />
                <CurrentPriceBar
                  latestPrice={latestPrice}
                  basePrice={basePrice}
                  bestAsk={bestAsk}
                  totalAsk={totalAsk}
                  totalBid={totalBid}
                />
                <BookSideRows rows={mobileBidRows} side="bid" maxSize={bidMax} />
              </div>
              <ScrollArea className="hidden min-h-0 flex-1 xl:block">
                <BookSideRows rows={askRows} side="ask" maxSize={askMax} />
                <CurrentPriceBar
                  latestPrice={latestPrice}
                  basePrice={basePrice}
                  bestAsk={bestAsk}
                  totalAsk={totalAsk}
                  totalBid={totalBid}
                />
                <BookSideRows rows={bidRows} side="bid" maxSize={bidMax} />
              </ScrollArea>
            </div>

            <div className="min-h-[180px] border-t border-border/60 dark:border-brand-800/45 xl:min-h-0 xl:border-t-0 xl:border-r">
              <div className="h-full min-h-0">
                <TradeTape ticks={recentTicks} maxRows={10} />
              </div>
            </div>

            <div className="min-h-[180px] border-t border-border/60 dark:border-brand-800/45 xl:min-h-0 xl:border-t-0">
              <div className="h-full min-h-0">
                <SummaryPanel
                  orderBook={orderBook}
                  latestTick={latestTick}
                  spread={spread}
                  imbalance={imbalance}
                  totalAsk={totalAsk}
                  totalBid={totalBid}
                />
              </div>
            </div>
          </div>
        </TabsContent>

        {/* ========== ORDERBOOK CUMULATIVE TAB ========== */}
        <TabsContent value="cumulative" className="min-h-0 flex-1">
          <ScrollArea className="h-full border-t dark:border-brand-800/45">
            <div className="p-3">
              <div className="mb-2 grid grid-cols-3 text-[11px] font-medium text-muted-foreground">
                <span>매도누적</span>
                <span className="text-center">호가</span>
                <span className="text-right">매수누적</span>
              </div>
              <CumulativeRows asks={askRows} bids={bidRows} />
            </div>
          </ScrollArea>
        </TabsContent>

        {/* ========== ORDERBOOK ORDER TAB ========== */}
        <TabsContent value="order" className="min-h-0 flex-1">
          <div className="flex h-full items-center justify-center border-t px-4 text-sm text-muted-foreground dark:border-brand-800/45 dark:text-brand-100/75">
            호가주문 탭은 주문 입력 패널과 연동해 확장할 수 있습니다.
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
