import { useState, useCallback } from 'react';
import type { TradeRecord, TradeRecordGroup, StockData } from '../types/index';

export function useTradeRecords(stockData: StockData[]) {
  const [trades, setTrades] = useState<TradeRecord[]>([]);
  const [tradeGroups, setTradeGroups] = useState<TradeRecordGroup[]>([]);
  const [hasBought, setHasBought] = useState(false);
  const [buyPrice, setBuyPrice] = useState(0);

  const toggleTrade = useCallback((type: 'BUY' | 'SELL') => {
    if (type === 'BUY' && hasBought) return;
    if (type === 'SELL' && !hasBought) return;

    // 确保有数据才能进行交易
    if (stockData.length === 0) return;

    const currentDate = stockData[stockData.length - 1]?.d;
    if (!currentDate) return;

    const closePrice = parseFloat(stockData[stockData.length - 1].c);

    if (type === 'BUY') {
      setHasBought(true);
      setBuyPrice(closePrice);
    } else {
      setHasBought(false);
      setBuyPrice(0);
    }

    const newTrade: TradeRecord = {
      type,
      price: closePrice,
      timestamp: Date.now(),
      date: currentDate,
      ...(type === 'SELL' ? { buyPrice: buyPrice } : {})
    };

    setTrades((prev: TradeRecord[]) => [...prev, newTrade]);
    setTradeGroups((prevGroups: TradeRecordGroup[]) => {
      const existingGroup = prevGroups.find(
        (group: TradeRecordGroup) => group.date === currentDate && group.type === type
      );

      if (existingGroup) {
        return prevGroups.map((group: TradeRecordGroup) => 
          group === existingGroup
            ? { ...group, records: [...group.records, newTrade] }
            : group
        );
      }

      return [...prevGroups, {
        date: currentDate,
        type,
        records: [newTrade]
      }];
    });
  }, [stockData, hasBought, buyPrice]);

  return {
    trades,
    tradeGroups,
    toggleTrade,
    hasBought,
  };
} 