import React, { useState, useEffect } from 'react';
import { Newspaper, MessageCircle, ExternalLink, Clock, User, TrendingUp, Calendar, RefreshCw } from 'lucide-react';
import { stockApi, NewsSocialRequest, NewsSocialResponse, NewsArticle, SocialPost, formatDate } from '@/lib/api';

interface NewsSocialDisplayProps {
  ticker: string;
}

const NewsSocialDisplay: React.FC<NewsSocialDisplayProps> = ({ ticker }) => {
  const [data, setData] = useState<NewsSocialResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<'all' | 'news' | 'social'>('all');
  const [settings, setSettings] = useState<NewsSocialRequest>({
    ticker: ticker,
    days_back: 7,
    max_articles: 15,
    max_social_posts: 10,
    include_social: true,
  });

  // Update ticker when prop changes and clear previous data
  useEffect(() => {
    // Clear previous data immediately when ticker changes
    if (settings.ticker !== ticker) {
      setData(null);
      setError(null);
      setLoading(false);
      setSettings(prev => ({ ...prev, ticker: ticker }));
    }
  }, [ticker, settings.ticker]);

  // Auto-fetch when settings change (but not on initial ticker update)
  useEffect(() => {
    if (ticker && ticker.length > 0 && settings.ticker === ticker) {
      fetchNewsSocialData();
    }
  }, [settings.ticker, settings.days_back, settings.max_articles, settings.max_social_posts, settings.include_social]);

  const fetchNewsSocialData = async () => {
    if (!ticker) return;

    setLoading(true);
    setError(null);
    // Clear previous data when starting new fetch
    setData(null);

    try {
      const result = await stockApi.getNewsSocialData(settings);
      setData(result);
    } catch (err) {
      console.error('News/Social data fetch error:', err);
      setError(err instanceof Error ? err.message : '뉴스 및 소셜 미디어 데이터를 가져오는데 실패했습니다.');
    } finally {
      setLoading(false);
    }
  };

  const formatTimeAgo = (publishedAt?: string) => {
    if (!publishedAt) return '';
    const now = new Date();
    const published = new Date(publishedAt);
    const diffInHours = Math.floor((now.getTime() - published.getTime()) / (1000 * 60 * 60));
    
    if (diffInHours < 1) return '방금 전';
    if (diffInHours < 24) return `${diffInHours}시간 전`;
    const diffInDays = Math.floor(diffInHours / 24);
    if (diffInDays < 7) return `${diffInDays}일 전`;
    return formatDate(publishedAt);
  };

  const NewsCard: React.FC<{ article: NewsArticle }> = ({ article }) => (
    <div className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between mb-2">
        <div className="flex items-center text-sm text-gray-500 mb-2">
          <Newspaper className="w-4 h-4 mr-1" />
          <span className="font-medium text-blue-600">{article.source}</span>
          {article.published_at && (
            <>
              <Clock className="w-3 h-3 mx-2" />
              <span>{formatTimeAgo(article.published_at)}</span>
            </>
          )}
        </div>
      </div>
      
      <h3 className="font-semibold text-gray-900 mb-2 leading-tight">
        <a 
          href={article.url} 
          target="_blank" 
          rel="noopener noreferrer"
          className="hover:text-blue-600 transition-colors"
        >
          {article.title}
        </a>
      </h3>
      
      {article.summary && (
        <p className="text-gray-600 text-sm mb-3 overflow-hidden" style={{
          display: '-webkit-box',
          WebkitLineClamp: 3,
          WebkitBoxOrient: 'vertical'
        }}>
          {article.summary}
        </p>
      )}
      
      <div className="flex items-center justify-between">
        <div className="flex items-center text-xs text-gray-500">
          {article.author && (
            <>
              <User className="w-3 h-3 mr-1" />
              <span>{article.author}</span>
            </>
          )}
        </div>
        <a 
          href={article.url}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center text-blue-600 hover:text-blue-800 text-sm font-medium"
        >
          읽기
          <ExternalLink className="w-3 h-3 ml-1" />
        </a>
      </div>
    </div>
  );

  const SocialCard: React.FC<{ post: SocialPost }> = ({ post }) => (
    <div className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center text-sm text-gray-500">
          <MessageCircle className="w-4 h-4 mr-1" />
          <span className="font-medium text-orange-600">{post.platform}</span>
          {post.subreddit && (
            <span className="ml-1 text-gray-400">r/{post.subreddit}</span>
          )}
          {post.published_at && (
            <>
              <Clock className="w-3 h-3 mx-2" />
              <span>{formatTimeAgo(post.published_at)}</span>
            </>
          )}
        </div>
        {typeof post.score === 'number' && (
          <div className="flex items-center text-sm">
            <TrendingUp className="w-3 h-3 mr-1 text-green-500" />
            <span className="font-medium text-green-600">{post.score}</span>
          </div>
        )}
      </div>
      
      <h3 className="font-semibold text-gray-900 mb-2">
        <a 
          href={post.url} 
          target="_blank" 
          rel="noopener noreferrer"
          className="hover:text-blue-600 transition-colors"
        >
          {post.title}
        </a>
      </h3>
      
      {post.content && post.content.length > 0 && (
        <p className="text-gray-600 text-sm mb-3 overflow-hidden" style={{
          display: '-webkit-box',
          WebkitLineClamp: 3,
          WebkitBoxOrient: 'vertical'
        }}>
          {post.content}
        </p>
      )}
      
      <div className="flex items-center justify-between">
        <div className="flex items-center text-xs text-gray-500">
          <User className="w-3 h-3 mr-1" />
          <span>{post.author}</span>
          {typeof post.comments_count === 'number' && post.comments_count > 0 && (
            <>
              <MessageCircle className="w-3 h-3 ml-3 mr-1" />
              <span>{post.comments_count} 댓글</span>
            </>
          )}
        </div>
        <a 
          href={post.url}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center text-blue-600 hover:text-blue-800 text-sm font-medium"
        >
          보기
          <ExternalLink className="w-3 h-3 ml-1" />
        </a>
      </div>
    </div>
  );

  if (!ticker) {
    return (
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-6 text-center">
        <Newspaper className="w-12 h-12 text-gray-400 mx-auto mb-2" />
        <p className="text-gray-600">종목을 선택하면 관련 뉴스와 소셜 미디어 데이터를 확인할 수 있습니다.</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 헤더 및 설정 */}
      <div className="bg-white border border-gray-200 rounded-lg p-4">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900">
            뉴스 & 소셜 미디어 ({ticker})
          </h2>
          <button
            onClick={() => {
              setData(null);  // Clear data immediately on refresh
              fetchNewsSocialData();
            }}
            disabled={loading}
            className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 mr-1 ${loading ? 'animate-spin' : ''}`} />
            새로고침
          </button>
        </div>

        {/* 설정 옵션 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-3 mb-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">기간</label>
            <select
              value={settings.days_back}
              onChange={(e) => setSettings(prev => ({ ...prev, days_back: parseInt(e.target.value) }))}
              className="w-full border border-gray-300 rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
            >
              <option value={1}>1일</option>
              <option value={3}>3일</option>
              <option value={7}>1주</option>
              <option value={14}>2주</option>
              <option value={30}>1개월</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">뉴스 수</label>
            <select
              value={settings.max_articles}
              onChange={(e) => setSettings(prev => ({ ...prev, max_articles: parseInt(e.target.value) }))}
              className="w-full border border-gray-300 rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
            >
              <option value={5}>5개</option>
              <option value={10}>10개</option>
              <option value={15}>15개</option>
              <option value={20}>20개</option>
              <option value={30}>30개</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">소셜 수</label>
            <select
              value={settings.max_social_posts}
              onChange={(e) => setSettings(prev => ({ ...prev, max_social_posts: parseInt(e.target.value) }))}
              className="w-full border border-gray-300 rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
            >
              <option value={0}>0개</option>
              <option value={5}>5개</option>
              <option value={10}>10개</option>
              <option value={15}>15개</option>
              <option value={20}>20개</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">소셜 미디어</label>
            <select
              value={settings.include_social ? 'true' : 'false'}
              onChange={(e) => setSettings(prev => ({ ...prev, include_social: e.target.value === 'true' }))}
              className="w-full border border-gray-300 rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
            >
              <option value="true">포함</option>
              <option value="false">제외</option>
            </select>
          </div>
        </div>

        {/* 탭 */}
        <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg">
          <button
            onClick={() => setActiveTab('all')}
            className={`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'all' 
                ? 'bg-white text-blue-600 shadow-sm' 
                : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            전체
          </button>
          <button
            onClick={() => setActiveTab('news')}
            className={`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'news' 
                ? 'bg-white text-blue-600 shadow-sm' 
                : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            뉴스만
          </button>
          <button
            onClick={() => setActiveTab('social')}
            className={`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${
              activeTab === 'social' 
                ? 'bg-white text-blue-600 shadow-sm' 
                : 'text-gray-600 hover:text-gray-900'
            }`}
          >
            소셜만
          </button>
        </div>
      </div>

      {/* 로딩 상태 */}
      {loading && (
        <div className="bg-white border border-gray-200 rounded-lg p-8 text-center">
          <RefreshCw className="w-8 h-8 text-gray-400 mx-auto mb-2 animate-spin" />
          <p className="text-gray-600">데이터를 불러오는 중...</p>
        </div>
      )}

      {/* 오류 상태 */}
      {error && !loading && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <p className="text-red-800">{error}</p>
        </div>
      )}

      {/* 데이터 표시 - 로딩 중이 아니고 에러도 없을 때만 */}
      {!loading && !error && data && (
        <>
          {/* 요약 정보 - 데이터가 있을 때만 표시 */}
          {data.summary.total_items > 0 && (
            <div className="bg-white border border-gray-200 rounded-lg p-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="text-center">
                  <div className="text-2xl font-bold text-blue-600">{data.news.total_articles}</div>
                  <div className="text-sm text-gray-600">뉴스 기사</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-orange-600">{data.social_media.total_posts}</div>
                  <div className="text-sm text-gray-600">소셜 포스트</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-600">{data.summary.total_items}</div>
                  <div className="text-sm text-gray-600">전체 항목</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-purple-600">{data.summary.time_range_days}</div>
                  <div className="text-sm text-gray-600">조회 일수</div>
                </div>
              </div>
            </div>
          )}

          {/* 콘텐츠 표시 */}
          {(activeTab === 'all' || activeTab === 'news') && data.news.articles.length > 0 && (
            <div className="space-y-4">
              {activeTab === 'all' && <h3 className="font-semibold text-gray-900">뉴스 기사</h3>}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {data.news.articles.map((article, index) => (
                  <NewsCard key={index} article={article} />
                ))}
              </div>
            </div>
          )}

          {(activeTab === 'all' || activeTab === 'social') && data.social_media.posts.length > 0 && (
            <div className="space-y-4">
              {activeTab === 'all' && <h3 className="font-semibold text-gray-900">소셜 미디어</h3>}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {data.social_media.posts.map((post, index) => (
                  <SocialCard key={index} post={post} />
                ))}
              </div>
            </div>
          )}

          {/* 데이터 없음 메시지 */}
          {data.summary.total_items === 0 && (
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-8 text-center">
              <Calendar className="w-12 h-12 text-gray-400 mx-auto mb-2" />
              <p className="text-gray-600">{ticker}에 대한 뉴스가 없습니다.</p>
              <p className="text-gray-500 text-sm mt-1">다른 기간을 선택하거나 다른 종목을 검색해 보세요.</p>
            </div>
          )}
        </>
      )}
    </div>
  );
};

export default NewsSocialDisplay;