import React, { useCallback, useEffect, useState } from 'react';
import { ScrollView, Text, View } from '@tarojs/components';
import Taro, { usePullDownRefresh } from '@tarojs/taro';
import styles from './index.module.scss';
import {
  listAIGuides,
  listDiseases,
  type Disease,
  type KnowledgeArticle,
} from '@/api/knowledge';

const CATEGORY_LABELS: Record<string, string> = {
  viral: '病毒性',
  fungal: '真菌性',
  bacterial: '细菌性',
  protozoan: '原虫性',
  other: '其他',
};

const KnowledgePage: React.FC = () => {
  const [diseases, setDiseases] = useState<Disease[]>([]);
  const [guides, setGuides] = useState<KnowledgeArticle[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    try {
      const [diseaseRes, guideRes] = await Promise.all([
        listDiseases().catch(() => [] as Disease[]),
        listAIGuides().catch(() => [] as KnowledgeArticle[]),
      ]);
      setDiseases(diseaseRes);
      setGuides(guideRes);
    } catch (err) {
      console.error('[Knowledge] 数据加载失败:', err);
      Taro.showToast({
        title: err instanceof Error ? err.message : '数据加载失败',
        icon: 'none',
      });
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  usePullDownRefresh(() => {
    fetchData().then(() => Taro.stopPullDownRefresh());
  });

  const openGuide = (a: KnowledgeArticle) => {
    Taro.navigateTo({ url: `/pages/knowledge/detail/index?kind=ai_guide&id=${a.id}` });
  };

  const openDisease = (d: Disease) => {
    Taro.navigateTo({ url: `/pages/knowledge/detail/index?kind=disease&id=${d.id}` });
  };

  return (
    <ScrollView className={styles.knowledgePage} scrollY>
      {guides.map((a) => (
        <View key={a.id} className={styles.guideCard} onClick={() => openGuide(a)}>
          <View className={styles.guideHeader}>
            <Text className={styles.guideBadge}>AI 解读</Text>
            <Text className={styles.guideArrow}>›</Text>
          </View>
          <Text className={styles.guideTitle}>{a.title}</Text>
          {a.summary ? <Text className={styles.guideSummary}>{a.summary}</Text> : null}
        </View>
      ))}

      <Text className={styles.sectionTitle}>蚕病百科</Text>
      <View className={styles.diseaseList}>
        {diseases.map((d) => (
          <View key={d.id} className={styles.diseaseCard} onClick={() => openDisease(d)}>
            <View className={styles.diseaseHeader}>
              <Text className={styles.diseaseName}>{d.name}</Text>
              <Text className={styles.diseaseTag}>{CATEGORY_LABELS[d.category] || d.category}</Text>
            </View>
            <Text className={styles.diseaseBrief}>{d.symptoms || '暂无症状描述'}</Text>
          </View>
        ))}
        {!loading && diseases.length === 0 ? (
          <Text className={styles.emptyText}>暂无蚕病百科内容</Text>
        ) : null}
      </View>
    </ScrollView>
  );
};

export default KnowledgePage;
