
import React, { useState } from 'react';
import { Cpu, Plus, Calendar, Zap, Trash2, Activity, Clock, LayoutGrid, Layers, X } from 'lucide-react';
import { StockItem, AutoTradeConfig, MarketType, WatchlistGroup } from '../types';

interface AutoTradingProps {
  marketMode: MarketType;
  stocks: StockItem[];
  configs: AutoTradeConfig[];
  groups: WatchlistGroup[];
  onAddConfig: (config: Omit<AutoTradeConfig, 'id' | 'active'>) => void;
  onToggleConfig: (id: string) => void;
  onDeleteConfig: (id: string) => void;
}

const AutoTrading: React.FC<AutoTradingProps> = ({ marketMode, stocks, configs, groups, onAddConfig, onToggleConfig, onDeleteConfig }) => {
  const [showAddModal, setShowAddModal] = useState(false);
  const [targetType, setTargetType] = useState<'SINGLE' | 'GROUP'>('SINGLE');
  const [newConfig, setNewConfig] = useState<Partial<AutoTradeConfig>>({
    type: 'ACCUMULATION',
    frequency: 'DAILY',
    quantity: 1,
    executionTime: '09:00',
    specificDay: 1
  });

  const handleAdd = () => {
    if (newConfig.type) {
      if (targetType === 'SINGLE' && !newConfig.stockCode) return;
      if (targetType === 'GROUP' && !newConfig.groupId) return;

      const stockName = targetType === 'SINGLE' 
        ? stocks.find(s => s.code === newConfig.stockCode)?.name || '알 수 없음'
        : groups.find(g => g.id === newConfig.groupId)?.name || '알 수 없는 그룹';

      onAddConfig({
        stockCode: targetType === 'SINGLE' ? newConfig.stockCode : undefined,
        groupId: targetType === 'GROUP' ? newConfig.groupId : undefined,
        stockName: stockName,
        type: newConfig.type as 'ACCUMULATION' | 'TRAILING_STOP',
        quantity: newConfig.quantity || 1,
        frequency: newConfig.frequency as 'DAILY' | 'WEEKLY' | 'MONTHLY',
        specificDay: newConfig.specificDay,
        executionTime: newConfig.executionTime || '09:00',
        trailingPercent: newConfig.trailingPercent,
        market: marketMode
      });
      setShowAddModal(false);
    }
  };

  const getDayLabel = (config: AutoTradeConfig) => {
    if (config.frequency === 'DAILY') return '매일';
    if (config.frequency === 'WEEKLY') {
      const days = ['일', '월', '화', '수', '목', '금', '토'];
      return `매주 ${days[config.specificDay || 0]}요일`;
    }
    if (config.frequency === 'MONTHLY') return `매월 ${config.specificDay}일`;
    return '';
  };

  const filteredStocks = stocks.filter(s => s.market === marketMode);
  const filteredGroups = groups.filter(g => g.codes.some(code => stocks.find(s => s.code === code)?.market === marketMode));

  return (
    <div className="space-y-12 animate-in slide-in-from-bottom-6 duration-500 pb-24">
      <div className="flex justify-between items-center bg-white p-12 rounded-[4rem] shadow-sm border border-slate-100">
        <div>
           <h3 className="text-3xl font-black text-slate-800 uppercase tracking-tight flex items-center gap-5">
             <Cpu className="text-emerald-500" size={36} /> {marketMode === MarketType.DOMESTIC ? '국내' : '해외'} 매매 엔진
           </h3>
           <p className="text-base font-bold text-slate-400 uppercase tracking-widest mt-3 flex items-center gap-3">
             <span className="relative flex h-3 w-3">
                <span className={`animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 ${configs.filter(c => c.active && c.market === marketMode).length > 0 ? 'bg-emerald-400' : 'bg-slate-300'}`}></span>
                <span className={`relative inline-flex rounded-full h-3 w-3 ${configs.filter(c => c.active && c.market === marketMode).length > 0 ? 'bg-emerald-500' : 'bg-slate-400'}`}></span>
             </span>
             현재 {configs.filter(c => c.active && c.market === marketMode).length}개의 로봇 에이전트 활성화됨
           </p>
        </div>
        <button 
          onClick={() => { setShowAddModal(true); setTargetType('SINGLE'); }}
          className="bg-slate-900 text-white px-12 py-6 rounded-[2.5rem] font-black text-base uppercase tracking-widest flex items-center gap-4 hover:bg-slate-800 transition-all shadow-2xl shadow-slate-300 active:scale-95"
        >
          <Plus size={24} /> 새 매매 전략 배포
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
        {configs.filter(c => c.market === marketMode).map(config => (
          <div key={config.id} className={`bg-white p-12 rounded-[4rem] shadow-sm border transition-all relative overflow-hidden group hover:shadow-2xl ${config.active ? 'border-emerald-200' : 'border-slate-100 grayscale-[0.5]'}`}>
            <div className={`absolute top-0 left-0 w-full h-2.5 transition-colors ${config.active ? (config.groupId ? 'bg-indigo-500' : (config.type === 'ACCUMULATION' ? 'bg-blue-500' : 'bg-orange-500')) : 'bg-slate-300'}`}></div>
            
            <div className="flex justify-between items-start mb-10">
               <div className="flex items-center gap-6">
                  <div className={`p-5 rounded-3xl shadow-sm transition-colors ${config.active ? (config.groupId ? 'bg-indigo-50 text-indigo-600' : (config.type === 'ACCUMULATION' ? 'bg-blue-50 text-blue-600' : 'bg-orange-50 text-orange-600')) : 'bg-slate-100 text-slate-400'}`}>
                    {config.groupId ? <Layers size={32} /> : <Activity size={32} />}
                  </div>
                  <div>
                    <h4 className={`font-black text-2xl leading-none mb-2 transition-colors ${config.active ? 'text-slate-900' : 'text-slate-400'}`}>{config.stockName}</h4>
                    <p className="text-[12px] text-slate-400 font-mono font-bold tracking-widest uppercase">{config.groupId ? 'GROUP AGENT' : config.stockCode}</p>
                  </div>
               </div>
               
               {/* 활성화 토글 스위치 */}
               <button 
                onClick={() => onToggleConfig(config.id)}
                className={`relative inline-flex h-8 w-14 items-center rounded-full transition-all focus:outline-none ${config.active ? 'bg-emerald-500' : 'bg-slate-200'}`}
               >
                 <span className={`inline-block h-5 w-5 transform rounded-full bg-white transition-transform ${config.active ? 'translate-x-7' : 'translate-x-2'}`} />
               </button>
            </div>

            <div className="space-y-6">
               <div className={`p-8 rounded-[3rem] space-y-5 border transition-colors ${config.active ? 'bg-slate-50/80 border-slate-100' : 'bg-slate-50/30 border-transparent'}`}>
                  <div className="flex justify-between items-center text-[12px] font-black uppercase tracking-[0.2em]">
                    <span className="text-slate-400">오퍼레이션</span>
                    <span className={config.active ? (config.groupId ? 'text-indigo-600' : 'text-slate-600') : 'text-slate-300'}>{config.groupId ? '그룹 일괄' : '개별 자산'}</span>
                  </div>
                  <div className="flex justify-between items-center text-[12px] font-black uppercase tracking-[0.2em]">
                    <span className="text-slate-400">코어 전략</span>
                    <span className={`px-3 py-1 rounded-lg transition-colors ${config.active ? (config.type === 'ACCUMULATION' ? 'bg-blue-100 text-blue-600' : 'bg-orange-100 text-orange-600') : 'bg-slate-100 text-slate-300'}`}>
                      {config.type === 'ACCUMULATION' ? '적립식 매수' : 'TS 자동매매'}
                    </span>
                  </div>
                  <div className="flex justify-between items-center text-base font-bold">
                    <span className="text-slate-400 uppercase tracking-widest text-[12px]">스케줄링</span>
                    <span className={`flex items-center gap-3 transition-colors ${config.active ? 'text-slate-700' : 'text-slate-300'}`}><Calendar size={20} className="text-slate-400" /> {getDayLabel(config)}</span>
                  </div>
                  <div className="flex justify-between items-center text-base font-bold">
                    <span className="text-slate-400 uppercase tracking-widest text-[12px]">실행정보</span>
                    <span className={`flex items-center gap-3 transition-colors ${config.active ? 'text-slate-700' : 'text-slate-300'}`}><Clock size={20} className="text-slate-400" /> {config.executionTime} / {config.quantity}주</span>
                  </div>
               </div>

               <div className="pt-8 border-t border-slate-100 flex justify-between items-center">
                  <div className="flex items-center gap-3">
                    <span className={`w-3 h-3 rounded-full transition-colors ${config.active ? 'bg-emerald-500' : 'bg-slate-300'}`}></span>
                    <span className="text-[12px] font-black text-slate-400 uppercase tracking-widest">{config.active ? '에이전트 운용 중' : '일시 중단됨'}</span>
                  </div>
                  <button 
                    onClick={() => onDeleteConfig(config.id)}
                    className="p-4 text-slate-300 hover:text-rose-500 hover:bg-rose-50 rounded-[1.5rem] transition-all"
                  >
                    <Trash2 size={24} />
                  </button>
               </div>
            </div>
          </div>
        ))}
      </div>

      {/* 전략 추가 모달 (기존 동일) */}
      {showAddModal && (
        <div className="fixed inset-0 z-[100] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-6">
          <div className="bg-white w-full max-w-2xl rounded-[4rem] p-16 shadow-2xl animate-in zoom-in-95 duration-300 border border-slate-100 overflow-hidden">
            <div className="flex justify-between items-center mb-12">
              <h3 className="text-4xl font-black text-slate-900 uppercase tracking-tight flex items-center gap-5">
                <Zap className="text-yellow-400 fill-yellow-400" /> 로봇 전략 설계
              </h3>
              <button onClick={() => setShowAddModal(false)} className="p-4 hover:bg-slate-100 rounded-full transition-colors"><X size={32} className="text-slate-400" /></button>
            </div>
            
            <div className="space-y-10">
              <div className="space-y-5">
                <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">타겟 유형</label>
                <div className="flex bg-slate-100 p-2.5 rounded-[2.5rem] shadow-inner">
                  <button 
                    onClick={() => setTargetType('SINGLE')}
                    className={`flex-1 py-5 rounded-[2rem] text-[12px] font-black transition-all ${targetType === 'SINGLE' ? 'bg-white text-slate-900 shadow-xl' : 'text-slate-400 hover:text-slate-600'}`}
                  >
                    개별 자산
                  </button>
                  <button 
                    onClick={() => setTargetType('GROUP')}
                    className={`flex-1 py-5 rounded-[2rem] text-[12px] font-black transition-all ${targetType === 'GROUP' ? 'bg-white text-slate-900 shadow-xl' : 'text-slate-400 hover:text-slate-600'}`}
                  >
                    자산 그룹
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-8">
                <div className="space-y-4">
                  <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">
                    {targetType === 'SINGLE' ? '자산 선택' : '그룹 선택'}
                  </label>
                  {targetType === 'SINGLE' ? (
                    <select 
                      className="w-full p-6 bg-slate-50 rounded-[2rem] border-2 border-transparent focus:border-blue-500 outline-none font-bold text-slate-800 text-base shadow-sm"
                      onChange={(e) => setNewConfig({...newConfig, stockCode: e.target.value})}
                      value={newConfig.stockCode || ''}
                    >
                      <option value="">대상 선택</option>
                      {filteredStocks.map(s => <option key={s.code} value={s.code}>{s.name}</option>)}
                    </select>
                  ) : (
                    <select 
                      className="w-full p-6 bg-slate-50 rounded-[2rem] border-2 border-transparent focus:border-blue-500 outline-none font-bold text-slate-800 text-base shadow-sm"
                      onChange={(e) => setNewConfig({...newConfig, groupId: e.target.value})}
                      value={newConfig.groupId || ''}
                    >
                      <option value="">그룹 선택</option>
                      {filteredGroups.map(g => <option key={g.id} value={g.id}>{g.name}</option>)}
                    </select>
                  )}
                </div>
                <div className="space-y-4">
                  <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">단위 수량</label>
                  <input 
                    type="number" 
                    className="w-full p-6 bg-slate-50 rounded-[2rem] border-2 border-transparent focus:border-blue-500 outline-none font-black text-slate-800 text-center text-2xl shadow-sm"
                    value={newConfig.quantity}
                    onChange={(e) => setNewConfig({...newConfig, quantity: parseInt(e.target.value)})}
                  />
                </div>
              </div>

              <div className="space-y-5">
                <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">실행 주파수</label>
                <div className="grid grid-cols-3 gap-4">
                  {[
                    { val: 'DAILY', label: '매일' },
                    { val: 'WEEKLY', label: '매주' },
                    { val: 'MONTHLY', label: '매월' }
                  ].map(freq => (
                    <button 
                      key={freq.val}
                      onClick={() => setNewConfig({...newConfig, frequency: freq.val as any, specificDay: freq.val === 'DAILY' ? undefined : 1})}
                      className={`py-5 rounded-[2rem] text-[12px] font-black transition-all border-2 ${newConfig.frequency === freq.val ? 'bg-slate-900 text-white border-slate-900 shadow-2xl' : 'bg-white text-slate-400 border-slate-100 hover:border-slate-300'}`}
                    >
                      {freq.label}
                    </button>
                  ))}
                </div>
              </div>

              <div className="grid grid-cols-2 gap-8">
                {newConfig.frequency !== 'DAILY' && (
                  <div className="space-y-4">
                    <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">
                      {newConfig.frequency === 'WEEKLY' ? '요일' : '날짜'}
                    </label>
                    <select 
                      className="w-full p-6 bg-slate-50 rounded-[2rem] border-2 border-transparent focus:border-blue-500 outline-none font-bold text-slate-800 shadow-sm"
                      value={newConfig.specificDay}
                      onChange={(e) => setNewConfig({...newConfig, specificDay: parseInt(e.target.value)})}
                    >
                      {newConfig.frequency === 'WEEKLY' ? (
                        ['일', '월', '화', '수', '목', '금', '토'].map((d, i) => <option key={d} value={i}>{d}요일</option>)
                      ) : (
                        Array.from({length: 31}, (_, i) => i + 1).map(d => <option key={d} value={d}>{d}일</option>)
                      )}
                    </select>
                  </div>
                )}
                <div className="space-y-4">
                  <label className="text-[12px] font-black text-slate-400 uppercase tracking-[0.2em] ml-3">시퀀스 타임</label>
                  <input 
                    type="time" 
                    className="w-full p-6 bg-slate-50 rounded-[2rem] border-2 border-transparent focus:border-blue-500 outline-none font-bold text-slate-800 shadow-sm"
                    value={newConfig.executionTime}
                    onChange={(e) => setNewConfig({...newConfig, executionTime: e.target.value})}
                  />
                </div>
              </div>

              <div className="flex gap-8 pt-10">
                <button 
                  onClick={() => setShowAddModal(false)}
                  className="flex-1 py-6 bg-slate-100 text-slate-400 rounded-[2.5rem] font-black uppercase text-[12px] tracking-widest hover:bg-slate-200 transition-all"
                >
                  취소
                </button>
                <button 
                  onClick={handleAdd}
                  className="flex-1 py-6 bg-blue-600 text-white rounded-[2.5rem] font-black uppercase text-[12px] tracking-widest hover:bg-blue-700 transition-all shadow-2xl shadow-blue-100"
                >
                  전략 추가
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default AutoTrading;
