
import React, { useState, useEffect, useMemo } from 'react';
import { X, RotateCcw, ChevronDown, Zap, Plus, Minus, Calendar, ToggleLeft, ToggleRight, CheckSquare, Square, TrendingUp, TrendingDown, Wallet, Target, ShieldAlert, BadgePercent, Save, PlayCircle, Info, BarChart3, Maximize2, Circle, CheckCircle2, Search } from 'lucide-react';
import { StockItem, OrderType, MarketType, ReservedOrder, TradeOrder } from '../types';
import { DbService, HoldingItem } from '../services/dbService';
import StockSearchModal from './StockSearchModal';

interface TradeModalProps {
  stock: StockItem;
  type: OrderType;
  onClose: () => void;
  onExecute: (order: Omit<ReservedOrder, 'id' | 'status' | 'createdAt'>) => Promise<void>;
  onImmediateOrder?: (order: Omit<TradeOrder, 'id' | 'timestamp' | 'status'>) => Promise<void>;
}

type StrategyType = 'NONE' | 'PROFIT' | 'LOSS' | 'TRAILING_STOP';

const TradeModal: React.FC<TradeModalProps> = ({ stock: initialStock, type: initialType, onClose, onExecute, onImmediateOrder }) => {
  const [localStock, setLocalStock] = useState<StockItem>(initialStock);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const [orderType, setOrderType] = useState<OrderType>(initialType);
  const isBuyMode = orderType === OrderType.BUY;

  const [holding, setHolding] = useState<HoldingItem | null>(null);
  const [buyingPower, setBuyingPower] = useState(0);
  const dbService = useMemo(() => new DbService(), []);

  useEffect(() => {
    const fetchData = async () => {
      const holdings = await dbService.getHoldings();
      const currentHolding = holdings.find(h => h.code === localStock.code) || null;
      setHolding(currentHolding);
      
      const summary = await dbService.getAccountSummary();
      setBuyingPower(summary.buyingPower);
    };
    fetchData();
  }, [localStock.code, dbService, orderType]);

  const plInfo = useMemo(() => {
    if (!holding) return null;
    const pl = (localStock.price - holding.avgPrice) * holding.quantity;
    const percent = ((localStock.price - holding.avgPrice) / holding.avgPrice) * 100;
    return { pl, percent };
  }, [holding, localStock.price]);

  const [monitoringEnabled, setMonitoringEnabled] = useState(false);
  const [immediateStart, setImmediateStart] = useState(true);
  
  // 전략 선택 (라디오 버튼 방식)
  const [activeStrategy, setActiveStrategy] = useState<StrategyType>(isBuyMode ? 'TRAILING_STOP' : 'NONE');

  // TS 설정
  const [tsValue, setTsValue] = useState<number>(3);
  const [tsUnit, setTsUnit] = useState<'PERCENT' | 'TICK' | 'AMOUNT'>('PERCENT');

  // TS 내부 감시 시작 조건 (Trigger)
  const [triggerEnabled, setTriggerEnabled] = useState(false); 
  const [triggerType, setTriggerType] = useState<'CURRENT' | 'HIGH' | 'LOW' | 'VOLUME'>('CURRENT');
  const [triggerValue, setTriggerValue] = useState<number>(localStock.price);
  const [monCondition, setMonCondition] = useState<'ABOVE' | 'BELOW'>(isBuyMode ? 'BELOW' : 'ABOVE');

  // 자동 조건 결정 로직
  const applyAutoCondition = (type: string, buyMode: boolean) => {
    if (!buyMode) {
      setMonCondition('ABOVE'); // 매도시에는 현재/고/저/거래량 모두 이상
    } else {
      // 매수시
      if (type === 'CURRENT' || type === 'HIGH') {
        setMonCondition('BELOW'); // 현재가, 고가는 이하
      } else {
        setMonCondition('ABOVE'); // 저가, 거래량은 이상
      }
    }
  };

  // 모드 변경 시 전략 및 조건 초기화
  useEffect(() => {
    if (isBuyMode) {
        setActiveStrategy('TRAILING_STOP');
    } else {
        setActiveStrategy('NONE');
    }
    applyAutoCondition(triggerType, isBuyMode);
    if (triggerType !== 'VOLUME') {
      setTriggerValue(localStock.price);
    }
  }, [isBuyMode, localStock.price]);

  const [monTargetUnit, setMonTargetUnit] = useState<'PRICE' | 'PERCENT' | 'AMOUNT'>('PRICE');
  const [profitValue, setProfitValue] = useState<number>(localStock.price * 1.1);
  const [lossValue, setLossValue] = useState<number>(localStock.price * 0.9);

  const [expiryDays, setExpiryDays] = useState<number>(1);
  const [customExpiryDate, setCustomExpiryDate] = useState<string>(
    new Date(Date.now() + 86400000).toISOString().split('T')[0]
  );

  const [priceMethod, setPriceMethod] = useState<'CURRENT' | 'MARKET' | 'HIGH' | 'LOW'>('CURRENT');
  const [tickOffset, setTickOffset] = useState<number>(0);
  const [quantityMode, setQuantityMode] = useState<'DIRECT' | 'RATIO'>('DIRECT');
  const [quantity, setQuantity] = useState<number>(1);
  const [quantityRatio, setQuantityRatio] = useState<number>(isBuyMode ? 10 : 100);

  const currencySymbol = localStock.market === MarketType.DOMESTIC ? '원' : '$';

  const handleMaxQuantity = () => {
    if (quantityMode === 'RATIO') {
      setQuantityRatio(100);
    } else {
      if (isBuyMode) {
        const maxQty = Math.floor(buyingPower / localStock.price);
        setQuantity(maxQty > 0 ? maxQty : 1);
      } else if (holding) {
        setQuantity(holding.quantity);
      }
    }
  };

  const handleReset = () => {
    setMonitoringEnabled(false);
    setImmediateStart(true);
    setActiveStrategy(isBuyMode ? 'TRAILING_STOP' : 'NONE');
    setTriggerEnabled(false);
    setTriggerType('CURRENT');
    setTriggerValue(localStock.price);
    applyAutoCondition('CURRENT', isBuyMode);
    setPriceMethod('CURRENT');
    setTickOffset(0);
    setQuantity(1);
    setQuantityRatio(isBuyMode ? 10 : 100);
    setExpiryDays(1);
  };

  const finalQuantity = useMemo(() => {
    if (quantityMode === 'RATIO') {
      if (isBuyMode) {
        const targetBudget = buyingPower * (quantityRatio / 100);
        return Math.floor(targetBudget / localStock.price) || 0;
      } else if (holding) {
        return Math.floor(holding.quantity * (quantityRatio / 100));
      }
    }
    return quantity;
  }, [isBuyMode, quantityMode, quantity, quantityRatio, holding, buyingPower, localStock.price]);

  const summaryMessage = useMemo(() => {
    const action = isBuyMode ? '매수' : '매도';
    const quantityText = quantityMode === 'RATIO' 
      ? `${finalQuantity}주(${isBuyMode ? '예수금' : '보유수량'}대비 ${quantityRatio}%)` 
      : `${finalQuantity}주`;
      
    const priceMethodMap = {
      CURRENT: '현재가',
      MARKET: '시장가',
      HIGH: '고가',
      LOW: '저가'
    };
    
    const tickText = tickOffset === 0 ? '+0틱' : (tickOffset > 0 ? `+${tickOffset}틱` : `${tickOffset}틱`);
    const priceText = priceMethod === 'MARKET' ? '시장가' : `${priceMethodMap[priceMethod]}${tickText}`;

    if (!monitoringEnabled) {
      return `${priceText}로 ${quantityText}를 ${action}합니다.`;
    }

    let strategyDesc = '';
    if (activeStrategy === 'TRAILING_STOP') {
      const triggerTypeMap = {
        CURRENT: '현재가',
        HIGH: '고가',
        LOW: '저가',
        VOLUME: '거래량'
      };
      const triggerLabel = triggerTypeMap[triggerType];
      const josa = triggerType === 'VOLUME' ? '이' : '가';
      const triggerDesc = triggerEnabled 
        ? `${triggerLabel}${josa} ${triggerValue.toLocaleString()}${triggerType === 'VOLUME' ? '주' : currencySymbol} ${monCondition === 'ABOVE' ? '이상' : '이하'} 도달 후`
        : '현재 시점부터';
      
      const tsUnitText = tsUnit === 'PERCENT' ? '%' : tsUnit === 'TICK' ? '틱' : currencySymbol;
      const turnAction = isBuyMode ? '반등' : '하락';
      strategyDesc = `${triggerDesc} ${tsValue}${tsUnitText} ${turnAction} 시`;
    } else if (activeStrategy === 'PROFIT') {
      const unitLabel = monTargetUnit === 'PRICE' ? '현재가' : monTargetUnit === 'PERCENT' ? '수익률(%)' : '수익금액';
      const unit = monTargetUnit === 'PERCENT' ? '%' : currencySymbol;
      strategyDesc = `(이익실현) ${unitLabel} ${profitValue.toLocaleString()}${unit} 이상 도달 시`;
    } else if (activeStrategy === 'LOSS') {
      const unitLabel = monTargetUnit === 'PRICE' ? '현재가' : monTargetUnit === 'PERCENT' ? '수익률(%)' : '수익금액';
      const unit = monTargetUnit === 'PERCENT' ? '%' : currencySymbol;
      strategyDesc = `(손절제한) ${unitLabel} ${lossValue.toLocaleString()}${unit} 이하 도달 시`;
    } else {
      strategyDesc = '조건 만족 시';
    }

    return `${strategyDesc} (${priceText})으로 ${quantityText}를 ${action}합니다.`;
  }, [isBuyMode, monitoringEnabled, activeStrategy, triggerEnabled, triggerType, triggerValue, monCondition, tsValue, tsUnit, priceMethod, tickOffset, finalQuantity, quantityMode, quantityRatio, profitValue, lossValue, monTargetUnit, currencySymbol]);

  const handleExecute = () => {
    if (monitoringEnabled) {
      let finalExpiry = new Date();
      if (expiryDays > 0) finalExpiry.setDate(finalExpiry.getDate() + expiryDays);
      else finalExpiry = new Date(customExpiryDate);

      onExecute({
        stockCode: localStock.code,
        stockName: localStock.name,
        type: orderType,
        quantity: finalQuantity,
        monitoringType: activeStrategy === 'TRAILING_STOP' ? 'TRAILING_STOP' : 'PRICE_TRIGGER',
        triggerPrice: triggerEnabled ? triggerValue : localStock.price,
        trailingType: tsUnit === 'PERCENT' ? 'PERCENT' : 'AMOUNT',
        trailingValue: tsValue,
        market: localStock.market,
        expiryDate: finalExpiry
      });
    } else {
      if (onImmediateOrder) {
        onImmediateOrder({
          stockCode: localStock.code,
          stockName: localStock.name,
          type: orderType,
          price: priceMethod === 'MARKET' ? 0 : localStock.price,
          quantity: finalQuantity
        });
      }
    }
    onClose();
  };

  const StrategyRadio = ({ type, label, icon: Icon }: { type: StrategyType, label: string, icon: any }) => {
    const isSelected = activeStrategy === type;
    return (
      <div 
        onClick={() => setActiveStrategy(type)}
        className={`p-3 rounded-2xl border-2 transition-all cursor-pointer flex items-center justify-between ${isSelected ? 'bg-amber-50/40 border-amber-300 shadow-sm' : 'bg-transparent border-slate-100 opacity-60'}`}
      >
        <div className="flex items-center gap-2">
          {isSelected ? <CheckCircle2 className="text-amber-600" size={16} /> : <Circle className="text-slate-300" size={16} />}
          <Icon className={isSelected ? 'text-amber-600' : 'text-slate-300'} size={16} />
          <span className="text-[12px] font-black text-slate-800 uppercase tracking-tight">{label}</span>
        </div>
        
        {isSelected && type === 'TRAILING_STOP' && (
          <div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
            <input type="number" className="w-16 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-amber-200 shadow-inner outline-none" value={tsValue} onChange={(e) => setTsValue(Number(e.target.value))} />
            <select value={tsUnit} onChange={(e) => setTsUnit(e.target.value as any)} className="bg-transparent font-black text-[12px] text-amber-600 outline-none">
              <option value="PERCENT">%</option>
              <option value="TICK">틱</option>
              <option value="AMOUNT">{currencySymbol}</option>
            </select>
          </div>
        )}

        {isSelected && type === 'PROFIT' && (
          <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
            <input type="number" className="w-20 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-rose-200 shadow-inner outline-none" value={profitValue} onChange={e => setProfitValue(Number(e.target.value))} />
            <span className="text-[12px] font-black text-rose-500">{monTargetUnit === 'PERCENT' ? '%' : currencySymbol}</span>
          </div>
        )}

        {isSelected && type === 'LOSS' && (
          <div className="flex items-center gap-2" onClick={e => e.stopPropagation()}>
            <input type="number" className="w-20 p-2 bg-white rounded-xl text-center font-black text-[14px] border border-blue-200 shadow-inner outline-none" value={lossValue} onChange={e => setLossValue(Number(e.target.value))} />
            <span className="text-[12px] font-black text-blue-500">{monTargetUnit === 'PERCENT' ? '%' : currencySymbol}</span>
          </div>
        )}
      </div>
    );
  };

  return (
    <div className="fixed inset-0 z-[300] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4">
      <div className="bg-white w-full max-w-4xl rounded-3xl shadow-2xl animate-in zoom-in-95 duration-200 flex flex-col max-h-[90vh] overflow-hidden border border-slate-200">
        
        {/* 헤더 */}
        <div className="px-5 py-2 flex justify-between items-center bg-white border-b border-slate-100 shrink-0">
          <button onClick={handleReset} className="flex items-center gap-1.5 text-slate-400 hover:text-slate-600 transition-colors">
            <RotateCcw size={16} />
            <span className="text-[11px] font-black uppercase tracking-wider">전체 초기화</span>
          </button>
          
          <div className="flex bg-slate-100 p-1 rounded-xl border border-slate-200 shadow-inner">
             <button onClick={() => setOrderType(OrderType.BUY)} className={`px-10 py-1.5 rounded-lg text-[11px] font-black transition-all ${isBuyMode ? 'bg-rose-500 text-white shadow-md' : 'text-slate-400 hover:text-slate-600'}`}>매수설정</button>
             <button onClick={() => setOrderType(OrderType.SELL)} className={`px-10 py-1.5 rounded-lg text-[11px] font-black transition-all ${!isBuyMode ? 'bg-blue-600 text-white shadow-md' : 'text-slate-400 hover:text-slate-600'}`}>매도설정</button>
          </div>

          <button onClick={onClose} className="p-1.5 hover:bg-slate-100 rounded-full transition-colors text-slate-400"><X size={24} /></button>
        </div>

        <div className="flex-1 overflow-y-auto custom-scrollbar bg-slate-50/20">
          {/* 상단 통합 정보 */}
          <div className="px-5 py-3 bg-white border-b border-slate-100 flex items-center justify-between gap-4">
            {/* 1. 종목 정보 */}
            <div className="flex items-center gap-3 min-w-0 group relative">
              <button 
                onClick={() => setIsSearchOpen(true)}
                className="w-10 h-10 bg-slate-900 rounded-xl flex items-center justify-center text-white font-black italic text-[14px] shrink-0 shadow-md transition-all hover:bg-slate-800 relative group-hover:bg-blue-600"
              >
                <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                  <Search size={18} />
                </div>
                <span className="group-hover:opacity-0 transition-opacity">{localStock.name[0]}</span>
              </button>
              <div className="min-w-0 cursor-pointer" onClick={() => setIsSearchOpen(true)}>
                <h3 className="text-[15px] font-black text-slate-900 truncate flex items-center gap-1 leading-tight group-hover:text-blue-600 transition-colors">
                  {localStock.name} <ChevronDown size={14} className="text-slate-300" />
                </h3>
                <div className="flex items-center gap-1.5 text-[9px] font-black uppercase text-slate-400 mt-0.5">
                  <span className="bg-slate-100 px-1 py-0.5 rounded text-slate-600 border border-slate-200/50">{localStock.market === MarketType.DOMESTIC ? 'KRX' : 'NYSE'}</span>
                  <span className="tracking-widest">{localStock.code}</span>
                </div>
              </div>
            </div>

            {/* 2. 시세 및 계좌 정보 (가로 나열) */}
            <div className="flex items-center gap-4 shrink-0">
               {/* 시세 */}
               <div className="border-l border-slate-100 pl-4 flex flex-col justify-center">
                 <p className={`text-[17px] font-black font-mono leading-none ${localStock.changePercent >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                    {localStock.market === MarketType.DOMESTIC ? localStock.price.toLocaleString() : `$${localStock.price}`}
                 </p>
                 <div className={`text-[10px] font-black flex items-center gap-1 mt-1 ${localStock.changePercent >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                    {localStock.changePercent >= 0 ? <TrendingUp size={12} /> : <TrendingDown size={12} />}
                    {Math.abs(localStock.changePercent)}%
                 </div>
               </div>

               {/* 거래량 */}
               <div className="border-l border-slate-100 pl-4 flex flex-col justify-center">
                  <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest leading-none mb-1">거래량</p>
                  <p className="text-[12px] font-black font-mono text-slate-900 leading-none">{localStock.volume.toLocaleString()}</p>
                  <div className="flex items-center gap-1 text-[9px] font-black text-rose-500 mt-1">
                     <TrendingUp size={10} /> +5.2%
                  </div>
               </div>

               {/* 예수금 */}
               <div className="border-l border-slate-100 pl-4 flex flex-col justify-center">
                  <p className="text-[8px] font-black text-slate-400 uppercase tracking-widest leading-none mb-1 flex items-center gap-1"><Wallet size={11} className="text-blue-500" /> 예수금</p>
                  <p className="text-[13px] font-black font-mono text-slate-900 leading-none">{buyingPower.toLocaleString()}{currencySymbol}</p>
               </div>

               {/* 보유/평가 */}
               <div className="border-l border-slate-100 pl-4 flex flex-col justify-center min-w-[110px]">
                 {holding ? (
                   <div className="space-y-1">
                      <div className="flex justify-between items-center gap-3">
                         <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest leading-none">보유</span>
                         <span className="text-[11px] font-black font-mono text-slate-900 leading-none">{holding.quantity} <span className="text-[8px] text-slate-300">EA</span></span>
                      </div>
                      <div className="flex justify-between items-center gap-3">
                         <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest leading-none">수익</span>
                         <span className={`text-[11px] font-black font-mono leading-none ${plInfo!.pl >= 0 ? 'text-rose-500' : 'text-blue-600'}`}>
                           {plInfo!.percent.toFixed(1)}%
                         </span>
                      </div>
                   </div>
                 ) : (
                   <div className="py-1 px-2 bg-slate-50 rounded border border-dashed border-slate-200 text-center">
                      <p className="text-[9px] font-black text-slate-300 uppercase tracking-widest">미보유</p>
                   </div>
                 )}
               </div>
            </div>
          </div>

          <div className="grid grid-cols-2 gap-px bg-slate-200">
            <div className={`bg-white p-5 space-y-5 transition-all duration-300 ${!monitoringEnabled ? 'opacity-40 grayscale-[0.5]' : ''}`}>
              <div className="flex items-center justify-between">
                <h4 className="text-[13px] font-black text-slate-800 uppercase tracking-tight flex items-center gap-2">
                   <ShieldAlert size={16} className={monitoringEnabled ? 'text-rose-500' : 'text-slate-300'} />
                   1. 자동 감시 전략
                </h4>
                <button 
                  onClick={() => setMonitoringEnabled(!monitoringEnabled)}
                  className={`flex items-center gap-2 px-4 py-1.5 rounded-full text-[10px] font-black transition-all border shadow-sm ${monitoringEnabled ? 'bg-slate-900 border-slate-900 text-white' : 'bg-white border-slate-200 text-slate-400 hover:border-slate-300'}`}
                >
                  {monitoringEnabled ? <ToggleRight size={18} /> : <ToggleLeft size={18} />}
                  {monitoringEnabled ? '감시 중' : '비활성'}
                </button>
              </div>

              <div className="space-y-6">
                {!isBuyMode ? (
                  <div className="space-y-4">
                     <div className="flex items-center justify-between pl-1">
                        <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest flex items-center gap-1.5">
                           <TrendingUp size={14} /> 스마트 수익/손실 관리
                        </label>
                        <div className="flex gap-1 bg-slate-100 p-0.5 rounded-lg border border-slate-200">
                           {['PRICE', 'PERCENT', 'AMOUNT'].map(unit => (
                             <button key={unit} onClick={() => setMonTargetUnit(unit as any)} className={`text-[9px] font-black px-2 py-1 rounded-md transition-all ${monTargetUnit === unit ? 'bg-white text-slate-900 shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}>
                               {unit === 'PRICE' ? '현재가' : unit === 'PERCENT' ? '수익률(%)' : '수익금액'}
                             </button>
                           ))}
                        </div>
                     </div>
                     
                     <div className="space-y-3">
                        <StrategyRadio type="PROFIT" label="이익실현 (TAKE PROFIT)" icon={Target} />
                        <StrategyRadio type="LOSS" label="손실제한 (STOP LOSS)" icon={ShieldAlert} />
                        <StrategyRadio type="TRAILING_STOP" label="반등 시 주문 (TRAILING STOP)" icon={PlayCircle} />
                     </div>
                  </div>
                ) : (
                  <div className="space-y-3">
                    <StrategyRadio type="TRAILING_STOP" label="반등 시 주문 (TRAILING STOP)" icon={PlayCircle} />
                  </div>
                )}
                
                {/* TS 내부 감시 시작 조건 설정 (TS 선택 시에만 표시) */}
                {activeStrategy === 'TRAILING_STOP' && (
                  <div className="mt-3 p-4 rounded-2xl border border-amber-100 bg-amber-50/20 space-y-3 animate-in slide-in-from-top-1">
                    <div className="flex items-center justify-between">
                      <div 
                        onClick={() => setTriggerEnabled(!triggerEnabled)}
                        className="flex items-center gap-2 cursor-pointer group"
                      >
                        {triggerEnabled ? <CheckSquare size={16} className="text-amber-600" /> : <Square size={16} className="text-slate-300" />}
                        <span className="text-[11px] font-black text-amber-700/80 uppercase tracking-widest">목표가 설정</span>
                      </div>
                    </div>

                    {triggerEnabled && (
                      <div className="flex items-center gap-1.5 bg-white/70 p-2 rounded-xl border border-amber-100 shadow-sm overflow-hidden">
                        <select 
                          value={triggerType} 
                          onChange={(e) => {
                            const newType = e.target.value as any;
                            setTriggerType(newType);
                            applyAutoCondition(newType, isBuyMode);
                            if (newType === 'VOLUME') {
                              setTriggerValue(100000);
                            } else {
                              setTriggerValue(stock.price);
                            }
                          }} 
                          className="bg-white p-2 rounded-lg font-black text-[10px] outline-none text-slate-700 w-32 border border-slate-100 shadow-sm shrink-0"
                        >
                          <option value="CURRENT">현재가(\)</option>
                          <option value="HIGH">고가(\)</option>
                          <option value="LOW">저가(\)</option>
                          <option value="VOLUME">거래량(주)</option>
                        </select>
                        <input 
                          type="number" 
                          className="flex-1 min-w-0 p-2 rounded-lg font-black text-[14px] text-center outline-none bg-white border border-slate-100 focus:border-amber-300 transition-all shadow-sm" 
                          value={triggerValue} 
                          onChange={(e) => setTriggerValue(Number(e.target.value))} 
                        />
                        <select 
                          value={monCondition}
                          onChange={(e) => setMonCondition(e.target.value as any)}
                          className={`p-2 rounded-lg font-black text-[10px] outline-none border border-slate-100 shadow-sm w-16 shrink-0 transition-colors ${monCondition === 'ABOVE' ? 'bg-blue-50 text-blue-600' : 'bg-rose-50 text-rose-500'}`}
                        >
                          <option value="ABOVE">이상</option>
                          <option value="BELOW">이하</option>
                        </select>
                      </div>
                    )}
                    
                    {!triggerEnabled && (
                      <p className="text-[10px] font-bold text-amber-600/60 pl-1 italic">※ 조건 미설정 시 현재 시점부터 즉시 반등 감시를 시작합니다.</p>
                    )}
                  </div>
                )}

                <div className="flex items-center gap-4 pt-4 border-t border-slate-100">
                  <span className="text-[11px] font-black text-slate-400 uppercase tracking-widest whitespace-nowrap">유효기간</span>
                  <div className="flex flex-1 gap-2">
                    {[1, 5, 30].map(d => (
                      <button key={d} onClick={() => setExpiryDays(d)} className={`flex-1 py-2 rounded-xl text-[11px] font-black transition-all ${expiryDays === d ? 'bg-slate-900 text-white shadow-md' : 'bg-slate-100 border border-slate-200 text-slate-400 hover:border-slate-300'}`}>
                        {d}일
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="bg-white p-5 space-y-5">
              <h4 className="text-[13px] font-black text-slate-800 uppercase tracking-tight flex items-center gap-2">
                 <Zap size={16} className="text-blue-500" />
                 2. 매매 실행 조건
              </h4>
              
              <div className="space-y-6">
                <div className="space-y-3">
                  <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest pl-1">주문 가격 유형</label>
                  <div className="grid grid-cols-4 gap-2 bg-slate-50 p-1 rounded-2xl border border-slate-100">
                    {['CURRENT', 'MARKET', 'HIGH', 'LOW'].map((method) => (
                      <button key={method} onClick={() => { setPriceMethod(method as any); if (method === 'MARKET') setTickOffset(0); }} className={`py-2 rounded-xl text-[11px] font-black transition-all border ${priceMethod === method ? 'bg-white text-slate-900 border-slate-200 shadow-md' : 'bg-transparent text-slate-400 border-transparent hover:text-slate-600'}`}>
                        {method === 'CURRENT' ? '현재' : method === 'MARKET' ? '시장' : method === 'HIGH' ? '고가' : '저가'}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="space-y-6">
                  <div className="space-y-3">
                    <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest pl-1">가격 조정 (틱)</label>
                    <div className="flex items-center gap-4 bg-slate-50 p-1.5 rounded-2xl border border-slate-100">
                      <button disabled={priceMethod === 'MARKET'} onClick={() => setTickOffset(prev => prev - 1)} className="p-2.5 bg-white rounded-xl text-slate-400 hover:text-blue-500 disabled:opacity-20 shadow-sm transition-all"><Minus size={18} /></button>
                      <div className="flex-1 text-center font-black font-mono text-[18px] text-slate-800">{tickOffset > 0 ? `+${tickOffset}` : tickOffset}</div>
                      <button disabled={priceMethod === 'MARKET'} onClick={() => setTickOffset(prev => prev + 1)} className="p-2.5 bg-white rounded-xl text-slate-400 hover:text-blue-500 disabled:opacity-20 shadow-sm transition-all"><Plus size={18} /></button>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <div className="flex items-center justify-between pl-1">
                       <label className="text-[11px] font-black text-slate-400 uppercase tracking-widest">주문 수량</label>
                       <span className="text-[9px] font-bold text-blue-500 bg-blue-50 px-2 py-0.5 rounded-full">
                          {isBuyMode ? `예수금` : `보유수량`}
                       </span>
                    </div>
                    <div className="bg-slate-50 p-3 rounded-2xl border border-slate-100 space-y-4">
                       <div className="flex items-center gap-1.5 bg-white/60 p-1 rounded-xl border border-slate-100 shadow-inner">
                          <button onClick={() => setQuantityMode('DIRECT')} className={`flex-1 py-2 rounded-lg text-[10px] font-black transition-all ${quantityMode === 'DIRECT' ? 'bg-white text-slate-900 shadow-sm border border-slate-200' : 'text-slate-400 hover:text-slate-600'}`}>직접입력</button>
                          <button onClick={() => setQuantityMode('RATIO')} className={`flex-1 py-2 rounded-lg text-[10px] font-black transition-all ${quantityMode === 'RATIO' ? 'bg-white text-slate-900 shadow-sm border border-slate-200' : 'text-slate-400 hover:text-slate-600'}`}>비중(%)</button>
                       </div>
                       <div className="flex items-center gap-3 px-2 pb-1 relative">
                          {quantityMode === 'DIRECT' ? (
                             <div className="flex items-center w-full gap-2 group">
                                <input type="number" min="1" className="flex-1 bg-transparent text-center font-black text-[24px] outline-none placeholder:text-slate-200 text-slate-900 min-w-0" placeholder="0" value={quantity} onChange={e => setQuantity(Math.max(1, parseInt(e.target.value) || 0))} />
                                <div className="flex flex-col items-center gap-1">
                                   <button onClick={handleMaxQuantity} className="px-3 py-1 bg-blue-600 text-white rounded-lg font-black text-[9px] uppercase tracking-tighter hover:bg-blue-700 transition-all shadow-md">MAX</button>
                                   <div className="px-2 py-1 bg-slate-900 text-white rounded-lg font-black text-[9px] uppercase tracking-wider shrink-0">EA / UNIT</div>
                                </div>
                             </div>
                          ) : (
                             <div className="flex items-center w-full gap-2">
                                <input type="number" min="0" max="100" className="flex-1 bg-transparent text-center font-black text-[24px] outline-none text-slate-900 min-w-0" value={quantityRatio} onChange={e => setQuantityRatio(Math.min(100, Math.max(0, parseInt(e.target.value) || 0)))} />
                                <div className="flex flex-col items-center gap-1">
                                   <button onClick={handleMaxQuantity} className="px-3 py-1 bg-blue-600 text-white rounded-lg font-black text-[9px] uppercase tracking-tighter hover:bg-blue-700 transition-all shadow-md">MAX</button>
                                   <div className={`px-2 py-1 text-white rounded-lg font-black text-[9px] uppercase tracking-wider flex items-center gap-1 shrink-0 ${isBuyMode ? 'bg-rose-500' : 'bg-blue-600'}`}>
                                      <BadgePercent size={12} /> PERCENT
                                   </div>
                                </div>
                             </div>
                          )}
                       </div>
                    </div>
                  </div>
                </div>

                <div className="p-3 bg-slate-900/5 rounded-2xl border border-slate-100 text-center">
                   <p className="text-[12px] font-black text-slate-600 leading-tight">
                     {summaryMessage}
                   </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 푸터 */}
        <div className="px-6 py-4 bg-white border-t border-slate-100 flex items-center justify-between shrink-0 gap-4">
          {monitoringEnabled && (
            <div className="flex items-center gap-3 bg-slate-50 px-4 py-2 rounded-2xl border border-slate-200 shadow-sm">
               <div className="flex flex-col">
                  <span className="text-[10px] font-black text-slate-800 uppercase tracking-tight leading-none">즉시 실행</span>
                  <span className="text-[8px] text-slate-400 font-bold leading-none mt-1">엔진 자동 가동</span>
               </div>
               <button 
                onClick={() => setImmediateStart(!immediateStart)}
                className={`relative inline-flex h-6 w-10 items-center rounded-full transition-all focus:outline-none shadow-inner ${immediateStart ? 'bg-emerald-500' : 'bg-slate-300'}`}
               >
                 <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform shadow-md ${immediateStart ? 'translate-x-5' : 'translate-x-1'}`} />
               </button>
            </div>
          )}
          
          <button 
            onClick={handleExecute} 
            className={`flex-1 py-4 rounded-2xl font-black text-[16px] text-white shadow-xl transition-all active:scale-[0.98] flex items-center justify-center gap-3 ${monitoringEnabled ? (isBuyMode ? 'bg-rose-500' : 'bg-blue-600') : 'bg-slate-900 hover:bg-slate-800'}`}
          >
            {monitoringEnabled ? <><Save className="w-5 h-5" /> 전략 저장 및 {immediateStart ? '즉시 활성화' : '대기 저장'}</> : <><Zap size={22} fill="currentColor" /> {isBuyMode ? '매수' : '매도'} 주문 즉시 전송</>}
          </button>
        </div>

        {isSearchOpen && (
          <StockSearchModal 
            currentMarket={localStock.market}
            onClose={() => setIsSearchOpen(false)}
            onSelect={(newStock) => {
              setLocalStock(newStock);
              setIsSearchOpen(false);
              // 초기화 로직 (트리거 등 새 종목 가격 연동)
              setTriggerValue(newStock.price);
              setProfitValue(newStock.price * 1.1);
              setLossValue(newStock.price * 0.9);
            }}
          />
        )}
      </div>
    </div>
  );
};

export default TradeModal;
