'use client';

import { useEffect, useState, useCallback } from 'react';
import { useSignalRContext } from '@/contexts/signalrProvider';
import { fetchApi } from '@/lib/utils/client';
import type { OrderbookData, OrderbookRestData } from '@/types/crypto';

export default function useOrderbook(market: string) {
	const { cryptoConnection, cryptoConnected } = useSignalRContext();
	const [orderbook, setOrderbook] = useState<OrderbookData | null>(null);

	// REST 초기 로드
	useEffect(() => {
		if (!market) {
			return;
		}

		const load = async () => {
			try {
				const res = await fetchApi<OrderbookRestData>(`/api/crypto/${market}/orderbook`);
				if (res.success && res.data) {
					setOrderbook({
						market,
						symbol: market.split('-')[1] || '',
						totalAskSize: res.data.totalAskSize,
						totalBidSize: res.data.totalBidSize,
						units: res.data.units,
						timestamp: res.data.timestamp,
						level: res.data.level,
						streamType: 'SNAPSHOT',
					});
				}
			} catch (error) {
				console.error('Failed to load orderbook:', error);
			}
		};

		load();
	}, [market]);

	// SignalR 실시간 업데이트
	const handleOrderbook = useCallback((data: OrderbookData) => {
		if (data.market === market) {
			setOrderbook(data);
		}
	}, [market]);

	useEffect(() => {
		if (!cryptoConnection || !cryptoConnected) {
			return;
		}

		cryptoConnection.on('ReceiveOrderbook', handleOrderbook);

		return () => {
			cryptoConnection.off('ReceiveOrderbook', handleOrderbook);
		};
	}, [cryptoConnection, cryptoConnected, handleOrderbook]);

	return orderbook;
}