
import React, { useState, useEffect } from 'react';
import { Newspaper, ExternalLink, RefreshCw, Bookmark, Search, AlertCircle, Sparkles, X, MessageSquareQuote } from 'lucide-react';
import { NewsItem, ApiSettings } from '../types';
import { NaverService } from '../services/naverService';
import { AiService } from '../services/aiService';

interface NewsProps {
  settings: ApiSettings;
}

const MOCK_NEWS: NewsItem[] = [
  {
    title: "BatchuKis 마켓 브리핑: AI 트레이딩의 미래",
    description: "딥러닝 알고리즘을 활용한 자동매매 시장이 국내에서도 빠르게 성장하고 있습니다. 개인 투자자들의 접근성이 확대되며...",
    link: "#",
    pubDate: new Date().toISOString()
  },
  {
    title: "KIS API 연동 가이드: 보안 설정과 데이터 암호화",
    description: "한국투자증권 오픈 API를 활용한 안전한 트레이딩 환경 구축을 위해 사용자는 반드시 앱키 노출에 주의해야 하며...",
    link: "#",
    pubDate: new Date().toISOString()
  }
];

const News: React.FC<NewsProps> = ({ settings }) => {
  const [loading, setLoading] = useState(false);
  const [news, setNews] = useState<NewsItem[]>(MOCK_NEWS);
  const [filter, setFilter] = useState('');
  
  // AI 분석 관련 상태
  const [analysisResult, setAnalysisResult] = useState<string | null>(null);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  
  const naverService = new NaverService(settings);

  useEffect(() => {
    if (settings.useNaverNews) {
      handleRefresh();
    }
  }, [settings.useNaverNews]);

  const handleRefresh = async () => {
    setLoading(true);
    if (settings.useNaverNews) {
      const fetchedNews = await naverService.fetchNews();
      if (fetchedNews.length > 0) {
        setNews([...fetchedNews, ...MOCK_NEWS]);
      }
    }
    setTimeout(() => setLoading(false), 800);
  };

  const handleAnalyze = async () => {
    const aiId = settings.preferredNewsAiId;
    if (!aiId) {
      alert("설정 페이지에서 '뉴스 분석 엔진'을 먼저 지정해주세요.");
      return;
    }
    
    const config = settings.aiConfigs.find(c => c.id === aiId);
    if (!config) {
      alert("지정된 AI 엔진 설정을 찾을 수 없습니다.");
      return;
    }

    setIsAnalyzing(true);
    setAnalysisResult(null);
    
    const headlines = news.slice(0, 10).map(n => n.title);
    
    try {
      const fullResult = await AiService.analyzeNewsSentiment(config, headlines);
      const [report, metadataStr] = fullResult.split('---METADATA---');
      
      setAnalysisResult(report.trim());

      if (metadataStr) {
        try {
          const metadata = JSON.parse(metadataStr.trim());
          if (Array.isArray(metadata)) {
            setNews(prev => {
              const updated = [...prev];
              metadata.forEach(item => {
                if (updated[item.index]) {
                  updated[item.index] = {
                    ...updated[item.index],
                    relatedThemes: item.themes,
                    relatedStocks: item.stocks,
                    sentiment: item.sentiment
                  };
                }
              });
              return updated;
            });
          }
        } catch (e) {
          console.error("메타데이터 파싱 실패:", e);
        }
      }
    } catch (e) {
      setAnalysisResult("AI 분석 중 오류가 발생했습니다. 설정을 확인해 주세요.");
    } finally {
      setIsAnalyzing(false);
    }
  };

  const filteredNews = news.filter(n => 
    n.title.toLowerCase().includes(filter.toLowerCase()) || 
    n.description.toLowerCase().includes(filter.toLowerCase())
  );

  return (
    <div className="space-y-6 w-full animate-in slide-in-from-right-4 duration-500 pb-20 pr-4">
      
      {/* 뉴스 스크랩 비활성 알림 */}
      {!settings.useNaverNews && (
        <div className="bg-amber-50 border border-amber-100 p-5 rounded-2xl flex items-start gap-3 shadow-sm">
          <AlertCircle className="text-amber-500 shrink-0" size={20} />
          <div>
            <h5 className="font-black text-amber-900 mb-1 text-sm uppercase tracking-tight">뉴스 스크랩 비활성</h5>
            <p className="text-[14px] text-amber-700 font-medium">네이버 뉴스 연동이 꺼져 있습니다. 설정 메뉴에서 Naver Client ID를 입력하세요.</p>
          </div>
        </div>
      )}

      {/* 분석 결과 리포트 */}
      {analysisResult && (
        <div className="bg-white p-6 rounded-2xl shadow-lg border-l-4 border-l-blue-600 animate-in fade-in zoom-in duration-300 relative group">
          <button onClick={() => setAnalysisResult(null)} className="absolute top-4 right-4 p-1.5 hover:bg-slate-50 rounded-lg text-slate-300 hover:text-slate-600 transition-all"><X size={16}/></button>
          <div className="flex items-start gap-4">
            <div className="p-3 bg-blue-50 text-blue-600 rounded-xl">
              <MessageSquareQuote size={20} />
            </div>
            <div className="space-y-2 pr-6">
               <h4 className="text-[10px] font-black text-blue-600 uppercase tracking-[0.2em]">AI Intelligence Report</h4>
               <div className="text-slate-800 text-[15px] font-bold leading-relaxed whitespace-pre-wrap">
                  {analysisResult}
               </div>
            </div>
          </div>
        </div>
      )}

      {/* 툴바: 검색 및 실행 버튼 */}
      <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
         <div className="relative w-full md:flex-1">
            <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" size={18} />
            <input 
              type="text" 
              placeholder="뉴스 검색..."
              className="w-full pl-12 pr-4 py-2.5 bg-white border border-slate-200 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-100 outline-none text-[14px] font-black text-slate-800"
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
            />
         </div>
         <div className="flex gap-2 w-full md:w-auto">
            <button 
              onClick={handleAnalyze}
              disabled={isAnalyzing || news.length === 0}
              className={`flex-1 md:shrink-0 px-5 py-2.5 bg-blue-600 text-white rounded-xl shadow-md font-black text-[12px] uppercase tracking-wider hover:bg-blue-700 flex items-center justify-center gap-2 transition-all active:scale-95 disabled:opacity-50`}
            >
              <Sparkles size={16} className={isAnalyzing ? 'animate-pulse' : ''} />
              {isAnalyzing ? '분석 중...' : 'AI 브리핑'}
            </button>
            <button 
              onClick={handleRefresh}
              disabled={loading}
              className={`flex-1 md:shrink-0 px-5 py-2.5 bg-slate-900 text-white rounded-xl shadow-md font-black text-[12px] uppercase tracking-wider hover:bg-slate-800 flex items-center justify-center gap-2 transition-all active:scale-95 ${loading ? 'opacity-50' : ''}`}
            >
              <RefreshCw size={16} className={loading ? 'animate-spin' : ''} />
              새로고침
            </button>
         </div>
      </div>

      {/* 뉴스 리스트 */}
      <div className="grid grid-cols-1 gap-3">
        {filteredNews.map((item, idx) => (
          <article key={idx} className="bg-white p-4 rounded-2xl shadow-sm border border-slate-100 flex items-start gap-4 hover:border-blue-200 hover:shadow-md transition-all group">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 transition-all ${
              item.sentiment === 'POSITIVE' ? 'bg-rose-50 text-rose-500' : 
              item.sentiment === 'NEGATIVE' ? 'bg-blue-50 text-blue-500' : 
              'bg-slate-50 text-slate-400 group-hover:bg-slate-900 group-hover:text-white'
            }`}>
               <Newspaper size={18} />
            </div>
            <div className="flex-1 min-w-0">
               <div className="flex justify-between items-center mb-1">
                  <span className="text-[10px] font-black text-blue-500 uppercase tracking-widest">Financial Market</span>
                  <span className="text-[11px] text-slate-400 font-bold">{new Date(item.pubDate).toLocaleDateString('ko-KR')}</span>
               </div>
               <h3 className="text-[16px] font-black text-slate-900 leading-tight mb-1 group-hover:text-blue-600 transition-colors truncate">
                  {item.title}
               </h3>
               <p className="text-slate-500 text-[13px] font-medium leading-normal line-clamp-1 opacity-70">
                  {item.description}
               </p>
               
               {/* AI 분석 인사이트 태그 */}
               {(item.relatedThemes || item.relatedStocks) && (
                 <div className="mt-2 flex flex-wrap gap-1.5">
                    {item.relatedThemes?.map(theme => (
                      <span key={theme} className="text-[10px] font-black text-blue-600 bg-blue-50/50 px-1.5 py-0.5 rounded-md leading-none border border-blue-100/50">#{theme}</span>
                    ))}
                    {item.relatedStocks?.map(stock => (
                      <span key={stock} className="text-[10px] font-black text-slate-500 bg-slate-50 px-1.5 py-0.5 rounded-md leading-none border border-slate-200/50">{stock}</span>
                    ))}
                 </div>
               )}

               <div className="mt-2 flex items-center gap-4">
                  <a href={item.link} target="_blank" rel="noopener noreferrer" className="text-[11px] font-black uppercase text-blue-600 hover:underline flex items-center gap-1.5 tracking-tight transition-colors">
                    기사보기 <ExternalLink size={12} />
                  </a>
                  <button className="text-slate-300 hover:text-amber-500 transition-colors">
                    <Bookmark size={14} />
                  </button>
               </div>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
};

export default News;
