
import React, { useState, useEffect, useMemo } from 'react';
import { 
  TrendingUp, TrendingDown, Wallet, Activity, Briefcase, PieChart, Database, Zap, Timer, Trash2, Globe, ArrowUpRight, ArrowDownRight, ChevronRight
} from 'lucide-react';
import { StockItem, TradeOrder, MarketType, WatchlistGroup, OrderType, AutoTradeConfig, ReservedOrder } from '../types';
import { DbService, HoldingItem } from '../services/dbService';
import StockDetailModal from '../components/StockDetailModal';
import TradeModal from '../components/TradeModal';
import { StatCard } from '../components/CommonUI';
import { StockRow } from '../components/StockRow';

interface DashboardProps {
  marketMode: MarketType;
  watchlistGroups: WatchlistGroup[];
  stocks: StockItem[];
  orders: TradeOrder[];
  reservedOrders: ReservedOrder[];
  autoTrades: AutoTradeConfig[];
  onManualOrder: (order: Omit<TradeOrder, 'id' | 'timestamp' | 'status'>) => Promise<void>;
  onAddReservedOrder: (order: Omit<ReservedOrder, 'id' | 'status' | 'createdAt'>) => Promise<void>;
  onDeleteReservedOrder: (id: string) => Promise<void>;
  onRefreshHoldings: () => void;
}

const Dashboard: React.FC<DashboardProps> = ({ 
  marketMode, stocks, reservedOrders, onAddReservedOrder, onDeleteReservedOrder, onRefreshHoldings, orders
}) => {
  const [holdings, setHoldings] = useState<HoldingItem[]>([]);
  const [summary, setSummary] = useState({ totalAssets: 0, buyingPower: 0 });
  
  // Data loading
  useEffect(() => {
    loadData();
  }, [orders, marketMode, reservedOrders]);

  const loadData = async () => {
    const allHoldings = await dbService.getHoldings();
    const filteredHoldings = allHoldings.filter(h => h.market === marketMode);
    const accSummary = await dbService.getAccountSummary();
    setHoldings(filteredHoldings);
    setSummary(accSummary);
  };

  const calculatePL = (holding: HoldingItem) => {
    const currentStock = stocks.find(s => s.code === holding.code);
    const currentPrice = currentStock ? currentStock.price : holding.avgPrice;
    const pl = (currentPrice - holding.avgPrice) * holding.quantity;
    const plPercent = ((currentPrice - holding.avgPrice) / holding.avgPrice) * 100;
    const value = currentPrice * holding.quantity;
    return { pl, plPercent, currentPrice, value, stock: currentStock };
  };

  const totalLiquidationSummary = holdings.reduce((acc, h) => {
    const plData = calculatePL(h);
    return {
      totalValue: acc.totalValue + plData.value,
      totalPL: acc.totalPL + plData.pl,
      totalCost: acc.totalCost + (h.avgPrice * h.quantity)
    };
  }, { totalValue: 0, totalPL: 0, totalCost: 0 });

  const aggregatePLPercent = totalLiquidationSummary.totalCost > 0 
    ? (totalLiquidationSummary.totalPL / totalLiquidationSummary.totalCost) * 100 
    : 0;

  // Remove detailStock and tradeContext initialization if not used elsewhere, but they are used in JSX below.
  const [detailStock, setDetailStock] = useState<StockItem | null>(null);
  const [tradeContext, setTradeContext] = useState<{ stock: StockItem, type: OrderType } | null>(null);
  const dbService = useMemo(() => new DbService(), []);

  return (
    <div className="space-y-6 animate-in fade-in duration-500 pb-20">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-white p-5 rounded-2xl shadow-sm border border-slate-100 flex flex-col h-[650px]">
          <div className="flex justify-between items-center mb-5">
            <h3 className="text-[16px] font-black text-slate-800 flex items-center gap-2 tracking-tighter">
              <Database size={20} className="text-emerald-600" /> 보유 포트폴리오
            </h3>
          </div>
          <div className="overflow-x-auto flex-1 scrollbar-hide">
            <table className="w-full text-left">
              <thead>
                <tr className="text-[11px] font-black text-slate-400 uppercase tracking-widest border-b border-slate-50">
                  <th className="pb-3 px-3">종목</th>
                  <th className="pb-3 px-3 text-right">현재가</th>
                  <th className="pb-3 px-3 text-right">수익금 (%)</th>
                  <th className="pb-3 px-3 text-right">주문</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {holdings.map(holding => {
                  const { pl, plPercent, stock } = calculatePL(holding);
                  if (!stock) return null;
                  return (
                    <StockRow 
                      key={holding.code}
                      stock={stock}
                      showPL={{ pl, percent: plPercent }}
                      showActions={true}
                      onTrade={(type) => setTradeContext({ stock, type })}
                      onClick={() => setDetailStock(stock)}
                    />
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <div className="bg-white p-5 rounded-2xl shadow-sm border border-slate-100 flex flex-col h-[650px] overflow-hidden">
          <h3 className="text-[16px] font-black text-slate-800 flex items-center gap-2 mb-5">
            <Timer size={20} className="text-blue-600" /> 실시간 감시 목록
          </h3>
          <div className="flex-1 overflow-y-auto space-y-2 scrollbar-hide">
             {reservedOrders.filter(o => o.market === marketMode).map(order => (
               <div key={order.id} className="bg-slate-50 p-3 rounded-xl border border-slate-100 flex justify-between items-center group">
                  <div className="flex items-center gap-3">
                     <div className={`p-2 rounded-lg ${order.type === OrderType.BUY ? 'bg-rose-50 text-rose-500' : 'bg-blue-50 text-blue-600'}`}><Zap size={14} fill="currentColor" /></div>
                     <div><p className="font-black text-[14px] text-slate-800">{order.stockName}</p></div>
                  </div>
                  <button onClick={() => onDeleteReservedOrder(order.id)} className="p-2 bg-white hover:bg-rose-50 rounded-lg text-slate-300 hover:text-rose-500 transition-all shadow-sm">
                    <Trash2 size={16} />
                  </button>
               </div>
             ))}
          </div>
        </div>
      </div>

      {detailStock && <StockDetailModal stock={detailStock} onClose={() => setDetailStock(null)} />}
      {tradeContext && <TradeModal stock={tradeContext.stock} type={tradeContext.type} onClose={() => setTradeContext(null)} onExecute={onAddReservedOrder} />}
    </div>
  );
};

export default Dashboard;
