/**
 * FAQ 常见问题页面
 */
import { useState, useEffect } from 'react';
import { View, Text, Input, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { pageFAQ, feedbackFAQ } from '../../api/ticket';
import type { FAQ } from '../../types/ticket';
import './faq.scss';

const CATEGORY_MAP: Record<string, { label: string; icon: string }> = {
  api: { label: 'API 相关', icon: '🔌' },
  billing: { label: '账单财务', icon: '💰' },
  account: { label: '账户安全', icon: '🔐' },
  sdk: { label: 'SDK 问题', icon: '📦' },
  payment: { label: '支付问题', icon: '💳' },
  other: { label: '其他', icon: '📝' }
};

export default function FAQPage() {
  const [faqs, setFaqs] = useState<FAQ[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [keyword, setKeyword] = useState('');
  const [category, setCategory] = useState('all');
  const [expandedId, setExpandedId] = useState<string | null>(null);

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

  const loadFAQs = async () => {
    setLoading(true);
    try {
      const params: any = { page: 1, pageSize: 50 };
      if (category !== 'all') params.category = category;
      if (keyword) params.keyword = keyword;
      
      const data = await pageFAQ(params);
      setFaqs(data.list);
      setTotal(data.total);
    } catch (e) {
      console.error('加载失败', e);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = () => {
    loadFAQs();
  };

  const handleCategoryChange = (cat: string) => {
    setCategory(cat);
    loadFAQs();
  };

  const toggleExpand = (id: string) => {
    setExpandedId(expandedId === id ? null : id);
  };

  const handleFeedback = async (faq: FAQ, helpful: boolean) => {
    await feedbackFAQ(faq.id, helpful);
    Taro.showToast({ title: helpful ? '感谢您的好评' : '我们会改进', icon: 'success' });
    loadFAQs();
  };

  return (
    <View className="faq-page">
      {/* 搜索栏 */}
      <View className="search-bar">
        <Input
          className="search-input"
          placeholder="搜索问题..."
          value={keyword}
          onInput={(e) => setKeyword(e.detail.value)}
          onConfirm={handleSearch}
        />
        <Button className="search-btn" onClick={handleSearch}>搜索</Button>
      </View>

      {/* 分类标签 */}
      <ScrollView className="category-scroll" scrollX>
        <View className="category-tabs">
          <View 
            className={`category-tab ${category === 'all' ? 'active' : ''}`}
            onClick={() => handleCategoryChange('all')}
          >
            全部
          </View>
          {Object.entries(CATEGORY_MAP).map(([key, { label, icon }]) => (
            <View 
              key={key}
              className={`category-tab ${category === key ? 'active' : ''}`}
              onClick={() => handleCategoryChange(key)}
            >
              {icon} {label}
            </View>
          ))}
        </View>
      </ScrollView>

      {/* 统计 */}
      <View className="stats-bar">
        <Text className="stats-text">共 {total} 个常见问题</Text>
      </View>

      {/* FAQ 列表 */}
      <ScrollView className="faq-list" scrollY>
        {loading ? (
          <View className="loading"><Text>加载中...</Text></View>
        ) : faqs.length === 0 ? (
          <View className="empty">
            <Text>未找到相关问题</Text>
          </View>
        ) : (
          faqs.map(faq => (
            <View 
              key={faq.id} 
              className={`faq-item ${expandedId === faq.id ? 'expanded' : ''}`}
            >
              <View className="faq-question" onClick={() => toggleExpand(faq.id)}>
                <Text className="question-icon">Q</Text>
                <Text className="question-text">{faq.question}</Text>
                <Text className="expand-icon">{expandedId === faq.id ? '−' : '+'}</Text>
              </View>
              
              {expandedId === faq.id && (
                <View className="faq-answer">
                  <View className="answer-header">
                    <Text className="answer-icon">A</Text>
                    <Text className="answer-label">回答</Text>
                  </View>
                  <Text className="answer-text">{faq.answer}</Text>
                  
                  {faq.tags.length > 0 && (
                    <View className="answer-tags">
                      {faq.tags.map(tag => (
                        <Text key={tag} className="tag">{tag}</Text>
                      ))}
                    </View>
                  )}
                  
                  <View className="answer-footer">
                    <View className="helpful-info">
                      <Text className="helpful-text">
                        有帮助 ({faq.helpful})
                      </Text>
                      <Text className="unhelpful-text">
                        没帮助 ({faq.notHelpful})
                      </Text>
                    </View>
                    <View className="helpful-actions">
                      <Button 
                        className="helpful-btn"
                        onClick={(e) => { e.stopPropagation(); handleFeedback(faq, true); }}
                      >
                        👍 有帮助
                      </Button>
                      <Button 
                        className="helpful-btn"
                        onClick={(e) => { e.stopPropagation(); handleFeedback(faq, false); }}
                      >
                        👎 没帮助
                      </Button>
                    </View>
                  </View>
                </View>
              )}
            </View>
          ))
        )}
      </ScrollView>

      {/* 底部提示 */}
      <View className="footer-tip">
        <Text className="tip-text">没有找到答案？</Text>
        <Button 
          className="ticket-btn"
          onClick={() => Taro.navigateTo({ url: '/developer/ticket/index' })}
        >
          提交工单
        </Button>
      </View>
    </View>
  );
}
