
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 IndexBar = () => {
  const indices = [
    { name: '코스피', value: '2,561.32', change: '+12.45', percent: '0.49%', isUp: true },
    { name: '코스닥', value: '842.11', change: '-3.21', percent: '0.38%', isUp: false },
    { name: '나스닥', value: '15,628.95', change: '+215.12', percent: '1.40%', isUp: true },
    { name: 'S&P 500', value: '4,850.12', change: '+45.23', percent: '0.94%', isUp: true },
    { name: 'USD/KRW', value: '1,324.50', change: '+2.10', percent: '0.16%', isUp: true },
  ];

  return (
    <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide -mx-2 px-2 items-center">
      {indices.map((idx, i) => (
        <div key={i} className="flex items-center gap-3 bg-white px-4 py-2 rounded-xl border border-slate-100 shadow-sm shrink-0 hover:border-blue-200 transition-colors cursor-pointer">
          <div className="flex flex-col">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-tighter">{idx.name}</span>
            <span className="text-[14px] font-black text-slate-900 font-mono tracking-tighter">{idx.value}</span>
          </div>
          <div className={`flex flex-col items-end ${idx.isUp ? 'text-rose-500' : 'text-blue-600'}`}>
            <span className="text-[10px] font-bold flex items-center gap-0.5">
              {idx.isUp ? <ArrowUpRight size={10} /> : <ArrowDownRight size={10} />}
              {idx.percent}
            </span>
            <span className="text-[9px] font-bold opacity-70">{idx.change}</span>
          </div>
        </div>
      ))}
      <button className="flex items-center gap-1 text-slate-400 hover:text-blue-500 transition-colors shrink-0 px-2">
         <span className="text-[11px] font-black">더보기</span>
         <ChevronRight size={14} />
      </button>
    </div>
  );
};

const Dashboard: React.FC<DashboardProps> = ({ 
  marketMode, watchlistGroups, stocks, reservedOrders, onAddReservedOrder, onDeleteReservedOrder, onRefreshHoldings, orders
}) => {
  const [holdings, setHoldings] = useState<HoldingItem[]>([]);
  const [summary, setSummary] = useState({ totalAssets: 0, buyingPower: 0 });
  
  const [activeGroupId, setActiveGroupId] = useState<string | null>(null);
  const [detailStock, setDetailStock] = useState<StockItem | null>(null);
  const [tradeContext, setTradeContext] = useState<{ stock: StockItem, type: OrderType } | null>(null);

  const dbService = useMemo(() => new DbService(), []);

  useEffect(() => {
    loadData();
  }, [orders, marketMode, reservedOrders]);

  const activeMarketGroups = useMemo(() => {
    return watchlistGroups.filter(group => group.market === marketMode);
  }, [watchlistGroups, marketMode]);

  useEffect(() => {
    if (activeMarketGroups.length > 0) {
      if (!activeGroupId || !activeMarketGroups.find(g => g.id === activeGroupId)) {
        setActiveGroupId(activeMarketGroups[0].id);
      }
    } else {
      setActiveGroupId(null);
    }
  }, [marketMode, activeMarketGroups, activeGroupId]);

  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;

  const selectedGroup = activeMarketGroups.find(g => g.id === activeGroupId) || activeMarketGroups[0];

  return (
    <div className="space-y-6 animate-in fade-in duration-500 pb-20">
      {/* 1. 지수 및 환율 바 */}
      <IndexBar />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="bg-white p-5 rounded-2xl shadow-sm border border-slate-100 flex flex-col h-[650px] lg:col-span-1">
          <div className="flex justify-between items-center mb-5">
            <h3 className="text-[15px] font-black text-slate-800 flex items-center gap-2 uppercase tracking-tighter">
              <PieChart size={20} className="text-blue-600" /> 관심 그룹
            </h3>
          </div>
          <div className="flex gap-2 mb-6 overflow-x-auto pb-2 scrollbar-hide">
            {activeMarketGroups.map(group => (
              <button key={group.id} onClick={() => setActiveGroupId(group.id)} className={`relative px-4 py-2 rounded-xl font-black text-[11px] transition-all border-2 whitespace-nowrap ${activeGroupId === group.id ? 'bg-white border-blue-500 text-blue-600 shadow-sm' : 'bg-transparent border-slate-50 text-slate-400 hover:border-slate-200'}`}>
                {group.name}
              </button>
            ))}
          </div>
          <div className="flex-1 overflow-y-auto pr-1 scrollbar-hide">
            <table className="w-full">
              <tbody className="divide-y divide-slate-50">
                {selectedGroup?.codes.map(code => stocks.find(s => s.code === code)).filter(s => s?.market === marketMode).map(stock => {
                  if (!stock) return null;
                  return (
                    <StockRow 
                      key={stock.code} 
                      stock={stock} 
                      showActions={true}
                      onTrade={(type) => setTradeContext({ stock, type })}
                      onClick={() => setDetailStock(stock)}
                    />
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <div className="lg:col-span-2 space-y-6">
           <div className="bg-white p-5 rounded-2xl shadow-sm border border-slate-100 flex flex-col h-[350px]">
              <div className="flex justify-between items-center mb-5">
                <h3 className="text-[15px] 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-[10px] 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-[274px] overflow-hidden">
              <h3 className="text-[15px] 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-[13px] 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>
      </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;
