import React, { useState, useEffect } from 'react';
import { View, Text, RichText } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro';
import { getArticleDetail, getPublicArticleDetail, Article } from '../../../services/article';
import { trackEvent } from '@/services/analytics';
import { useElderClass } from '../../../hooks/useElderClass';
import { useAuthStore } from '../../../stores/auth';
import './index.scss';

export default function ArticleDetail() {
  const modeClass = useElderClass();
  const router = useRouter();
  const id = router.params.id || '';

  const [article, setArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(true);

  useShareAppMessage(() => {
    trackEvent('article_share', { article_id: id });
    return {
      title: article?.title || '健康资讯',
      path: `/pages/article/detail/index?id=${id}`,
    };
  });

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    const user = useAuthStore.getState().user;
    const fetcher = user ? getArticleDetail(id) : getPublicArticleDetail(id);
    fetcher
      .then((data) => setArticle(data))
      .catch(() => Taro.showToast({ title: '加载失败', icon: 'none' }))
      .finally(() => setLoading(false));
  }, [id]);

  if (loading) {
    return (
      <View className={`article-detail-page ${modeClass}`}>
        <View className='loading-state'>
          <Text className='loading-text'>加载中...</Text>
        </View>
      </View>
    );
  }

  if (!article) {
    return (
      <View className={`article-detail-page ${modeClass}`}>
        <View className='empty-state'>
          <Text className='empty-text'>文章不存在</Text>
        </View>
      </View>
    );
  }

  return (
    <View className={`article-detail-page ${modeClass}`}>
      {/* 文章头部 */}
      <View className='article-header'>
        <Text className='article-title'>{article.title}</Text>
        <View className='article-meta'>
          {article.category && (
            <Text className='article-category'>{article.category}</Text>
          )}
          {article.author && (
            <Text className='article-author'>{article.author}</Text>
          )}
          {article.published_at && (
            <Text className='article-date'>{article.published_at.slice(0, 10)}</Text>
          )}
        </View>
      </View>

      {/* 摘要 */}
      {article.summary && (
        <View className='article-summary'>
          <Text className='summary-text'>{article.summary}</Text>
        </View>
      )}

      {/* 正文 */}
      <View className='article-content'>
        <RichText
          nodes={article.content || ''}
        />
      </View>
    </View>
  );
}
