
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 result = await AiService.analyzeNewsSentiment(config, headlines);
      setAnalysisResult(result);
    } 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-12 max-w-6xl mx-auto animate-in slide-in-from-right-4 duration-500 pb-20">
      
      {/* 뉴스 스크랩 비활성 알림 */}
      {!settings.useNaverNews && (
        <div className="bg-amber-50 border border-amber-100 p-8 rounded-[2.5rem] flex items-start gap-5 shadow-sm">
          <AlertCircle className="text-amber-500 shrink-0" size={28} />
          <div>
            <h5 className="font-bold text-amber-900 mb-2 text-lg">뉴스 스크랩 비활성</h5>
            <p className="text-base text-amber-700">네이버 뉴스 연동이 꺼져 있습니다. 설정 메뉴에서 Naver Client ID를 입력하세요.</p>
          </div>
        </div>
      )}

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

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

      {/* 뉴스 리스트 */}
      <div className="space-y-8">
        {filteredNews.map((item, idx) => (
          <article key={idx} className="bg-white p-10 rounded-[3.5rem] shadow-sm border border-slate-100 flex flex-col md:flex-row gap-10 hover:shadow-2xl transition-all group">
            <div className="w-20 h-20 bg-slate-50 rounded-3xl flex items-center justify-center flex-shrink-0 text-slate-900 group-hover:bg-slate-900 group-hover:text-white transition-all shadow-sm">
               <Newspaper size={40} />
            </div>
            <div className="flex-1 space-y-4">
               <div className="flex justify-between items-start">
                  <span className="text-[11px] font-black text-blue-600 uppercase tracking-[0.2em] bg-blue-50 px-4 py-1.5 rounded-full">Financial Market</span>
                  <span className="text-sm text-slate-400 font-bold">{new Date(item.pubDate).toLocaleDateString('ko-KR')}</span>
               </div>
               <h3 className="text-2xl font-black text-slate-900 leading-tight group-hover:text-blue-600 transition-colors">
                  {item.title}
               </h3>
               <p className="text-slate-500 text-base font-medium leading-relaxed line-clamp-2 opacity-80">
                  {item.description}
               </p>
               <div className="pt-6 flex items-center gap-8">
                  <a href={item.link} target="_blank" rel="noopener noreferrer" className="text-[12px] font-black uppercase text-slate-900 hover:text-blue-600 flex items-center gap-2.5 tracking-tighter transition-colors">
                    상세보기 <ExternalLink size={18} />
                  </a>
                  <button className="text-slate-300 hover:text-amber-500 transition-colors">
                    <Bookmark size={22} />
                  </button>
               </div>
            </div>
          </article>
        ))}
      </div>
    </div>
  );
};

export default News;
