
import React, { useState, useEffect, useMemo } from 'react';
import { 
  TrendingUp, Wallet, Activity, Briefcase, PieChart, Database, Zap, Timer, Trash2
} 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, 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-12 animate-in fade-in duration-500 pb-20">
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
        <StatCard title={`총 자산 (${marketMode === MarketType.DOMESTIC ? '원' : '달러'})`} value={`${marketMode === MarketType.DOMESTIC ? '₩' : '$'} ${summary.totalAssets.toLocaleString()}`} change="+4.2%" isUp={true} icon={<Wallet className="text-blue-500" />} />
        <StatCard title="총 평가손익" value={`${marketMode === MarketType.DOMESTIC ? '₩' : '$'} ${totalLiquidationSummary.totalPL.toLocaleString()}`} change={`${aggregatePLPercent.toFixed(2)}%`} isUp={totalLiquidationSummary.totalPL >= 0} icon={<TrendingUp className={totalLiquidationSummary.totalPL >= 0 ? "text-emerald-500" : "text-rose-500"} />} />
        <StatCard title="보유 종목수" value={`${holdings.length}개`} change="마켓 필터" isUp={true} icon={<Briefcase className="text-orange-500" />} />
        <StatCard title="예수금" value={`${marketMode === MarketType.DOMESTIC ? '₩' : '$'} ${summary.buyingPower.toLocaleString()}`} change="인출 가능" isUp={true} icon={<Activity className="text-purple-500" />} />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-10">
        <div className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 flex flex-col h-[800px] lg:col-span-1">
          <div className="flex justify-between items-center mb-8">
            <h3 className="text-2xl font-black text-slate-800 flex items-center gap-3 uppercase tracking-tighter">
              <PieChart size={28} className="text-blue-600" /> 관심 그룹
            </h3>
          </div>
          <div className="flex gap-3 mb-10 overflow-x-auto pb-4 scrollbar-hide">
            {activeMarketGroups.map(group => (
              <button key={group.id} onClick={() => setActiveGroupId(group.id)} className={`relative px-7 py-3 rounded-full font-black text-[12px] transition-all border-2 whitespace-nowrap ${activeGroupId === group.id ? 'bg-white border-blue-500 text-blue-600 shadow-md' : 'bg-transparent border-slate-100 text-slate-400'}`}>
                {group.name}
              </button>
            ))}
          </div>
          <div className="flex-1 overflow-y-auto pr-2 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-10">
           <div className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 flex flex-col h-[450px]">
              <div className="flex justify-between items-center mb-8">
                <h3 className="text-2xl font-black text-slate-800 flex items-center gap-3 tracking-tighter">
                  <Database size={28} 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-[0.25em] border-b">
                      <th className="pb-5 px-6">종목</th>
                      <th className="pb-5 px-6 text-right">현재가</th>
                      <th className="pb-5 px-6 text-right">수익금 (%)</th>
                      <th className="pb-5 px-6 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-10 rounded-[3.5rem] shadow-sm border border-slate-100 flex flex-col h-[350px] overflow-hidden">
              <h3 className="text-2xl font-black text-slate-800 flex items-center gap-3 mb-8">
                <Timer size={28} className="text-blue-600" /> 실시간 감시 목록
              </h3>
              <div className="flex-1 overflow-y-auto space-y-4 scrollbar-hide">
                 {reservedOrders.filter(o => o.market === marketMode).map(order => (
                   <div key={order.id} className="bg-slate-50 p-6 rounded-[2.5rem] border border-slate-100 flex justify-between items-center group">
                      <div className="flex items-center gap-5">
                         <div className={`p-4 rounded-2xl ${order.type === OrderType.BUY ? 'bg-rose-50 text-rose-500' : 'bg-blue-50 text-blue-600'}`}><Zap size={20} fill="currentColor" /></div>
                         <div><p className="font-black text-lg text-slate-800">{order.stockName}</p></div>
                      </div>
                      <button onClick={() => onDeleteReservedOrder(order.id)} className="p-3 bg-white hover:bg-rose-50 rounded-2xl text-slate-300 hover:text-rose-500 transition-all shadow-sm">
                        <Trash2 size={22} />
                      </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;
