/**
 * SDK 下载中心
 */
import { useState, useEffect } from 'react';
import { View, Text, Image, Input, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { pageSDK, listSDKCategories, recordDownload } from '../../api/sdk';
import type { SDK, SDKCategory } from '../../types/sdk';
import './index.scss';

export default function SDKCenter() {
  const [categories, setCategories] = useState<SDKCategory[]>([]);
  const [sdks, setSDKs] = useState<SDK[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState('all');
  const [keyword, setKeyword] = useState('');
  const [selectedSDK, setSelectedSDK] = useState<SDK | null>(null);

  useEffect(() => {
    loadCategories();
    loadSDKs();
  }, []);

  // 加载分类
  const loadCategories = async () => {
    try {
      const data = await listSDKCategories();
      setCategories(data);
    } catch (e) {
      console.error('加载分类失败', e);
    }
  };

  // 加载 SDK 列表
  const loadSDKs = async (category = activeCategory, kw = keyword) => {
    setLoading(true);
    try {
      const params: any = { page: 1, pageSize: 20 };
      if (category !== 'all') params.category = category;
      if (kw) params.keyword = kw;
      
      const data = await pageSDK(params);
      setSDKs(data.list);
      setTotal(data.total);
    } catch (e) {
      console.error('加载 SDK 失败', e);
    } finally {
      setLoading(false);
    }
  };

  // 搜索
  const handleSearch = () => {
    loadSDKs(activeCategory, keyword);
  };

  // 切换分类
  const handleCategoryChange = (categoryId: string) => {
    setActiveCategory(categoryId);
    loadSDKs(categoryId, keyword);
  };

  // 查看详情
  const handleViewDetail = (sdk: SDK) => {
    setSelectedSDK(sdk);
  };

  // 下载 SDK
  const handleDownload = async (sdk: SDK) => {
    try {
      await recordDownload(sdk.id, sdk.version);
      
      if (sdk.npmPackage) {
        Taro.setClipboardData({
          data: `npm install ${sdk.npmPackage}`,
          success: () => {
            Taro.showToast({ title: '安装命令已复制', icon: 'success' });
          }
        });
      } else {
        Taro.showToast({ title: '开始下载...', icon: 'loading' });
      }
    } catch (e) {
      Taro.showToast({ title: '下载失败', icon: 'none' });
    }
  };

  // 访问文档
  const handleViewDocs = (sdk: SDK) => {
    Taro.navigateTo({ url: `/developer/docs/sdk-detail?id=${sdk.id}` });
  };

  // 获取语言图标
  const getLanguageIcon = (language: string) => {
    const icons: Record<string, string> = {
      'JavaScript': '🟨',
      'TypeScript': '🔷',
      'Python': '🐍',
      'Java': '☕',
      'Go': '🔵',
      'Swift': '🍎',
      'Flutter': '🎨',
      'React Native': '⚛️',
      '.NET': '🔷',
      'PHP': '🐘',
      'Ruby': '💎',
      'Kotlin': '🟣'
    };
    return icons[language] || '📦';
  };

  // 获取分类图标
  const getCategoryIcon = (icon: string) => {
    const icons: Record<string, string> = {
      'globe': '🌐',
      'mobile': '📱',
      'server': '🖥️',
      'wechat': '💬'
    };
    return icons[icon] || '📦';
  };

  return (
    <View className="sdk-center">
      {/* 搜索栏 */}
      <View className="search-bar">
        <Input
          className="search-input"
          placeholder="搜索 SDK 名称或描述..."
          value={keyword}
          onInput={(e) => setKeyword(e.detail.value)}
          onConfirm={handleSearch}
        />
        <Button className="search-btn" onClick={handleSearch}>搜索</Button>
      </View>

      {/* 分类标签 */}
      <ScrollView className="category-scroll" scrollX enableFlex>
        <View className="category-tabs">
          <View 
            className={`category-tab ${activeCategory === 'all' ? 'active' : ''}`}
            onClick={() => handleCategoryChange('all')}
          >
            全部
          </View>
          {categories.map(cat => (
            <View 
              key={cat.id}
              className={`category-tab ${activeCategory === cat.id ? 'active' : ''}`}
              onClick={() => handleCategoryChange(cat.id)}
            >
              {getCategoryIcon(cat.icon)} {cat.name}
            </View>
          ))}
        </View>
      </ScrollView>

      {/* 统计信息 */}
      <View className="stats-bar">
        <Text className="stats-text">共 {total} 个 SDK</Text>
      </View>

      {/* SDK 列表 */}
      <ScrollView className="sdk-list" scrollY>
        {loading ? (
          <View className="loading">
            <Text>加载中...</Text>
          </View>
        ) : sdks.length === 0 ? (
          <View className="empty">
            <Text>未找到相关 SDK</Text>
          </View>
        ) : (
          sdks.map(sdk => (
            <View key={sdk.id} className="sdk-card" onClick={() => handleViewDetail(sdk)}>
              <View className="sdk-header">
                <View className="sdk-icon-wrap">
                  <Text className="sdk-icon">{getLanguageIcon(sdk.language)}</Text>
                </View>
                <View className="sdk-info">
                  <Text className="sdk-name">{sdk.name}</Text>
                  <Text className="sdk-version">v{sdk.version}</Text>
                </View>
                <View className="sdk-actions">
                  <Button 
                    className="action-btn primary"
                    onClick={(e) => { e.stopPropagation(); handleDownload(sdk); }}
                  >
                    下载
                  </Button>
                </View>
              </View>
              
              <Text className="sdk-desc">{sdk.description}</Text>
              
              <View className="sdk-footer">
                <View className="sdk-tags">
                  <Text className="tag">{sdk.language}</Text>
                  <Text className="tag">{sdk.category === 'web' ? 'Web' : sdk.category === 'mobile' ? '移动' : sdk.category === 'server' ? '服务端' : '小程序'}</Text>
                </View>
                <View className="sdk-stats">
                  <Text className="stat">⬇️ {sdk.downloadCount > 1000 ? (sdk.downloadCount / 1000).toFixed(1) + 'k' : sdk.downloadCount}</Text>
                  <Text className="stat">⭐ {sdk.stars > 1000 ? (sdk.stars / 1000).toFixed(1) + 'k' : sdk.stars}</Text>
                </View>
              </View>
            </View>
          ))
        )}
      </ScrollView>

      {/* SDK 详情弹窗 */}
      {selectedSDK && (
        <View className="sdk-modal" onClick={() => setSelectedSDK(null)}>
          <View className="sdk-modal-content" onClick={(e) => e.stopPropagation()}>
            <View className="modal-header">
              <Text className="modal-title">{selectedSDK.name}</Text>
              <Text className="modal-close" onClick={() => setSelectedSDK(null)}>✕</Text>
            </View>
            
            <ScrollView className="modal-body" scrollY>
              <View className="modal-section">
                <Text className="section-title">基本信息</Text>
                <View className="info-grid">
                  <View className="info-item">
                    <Text className="info-label">最新版本</Text>
                    <Text className="info-value">{selectedSDK.version}</Text>
                  </View>
                  <View className="info-item">
                    <Text className="info-label">语言</Text>
                    <Text className="info-value">{selectedSDK.language}</Text>
                  </View>
                  <View className="info-item">
                    <Text className="info-label">下载量</Text>
                    <Text className="info-value">{selectedSDK.downloadCount.toLocaleString()}</Text>
                  </View>
                  <View className="info-item">
                    <Text className="info-label">更新时间</Text>
                    <Text className="info-value">{selectedSDK.lastUpdated}</Text>
                  </View>
                </View>
              </View>
              
              <View className="modal-section">
                <Text className="section-title">描述</Text>
                <Text className="section-content">{selectedSDK.description}</Text>
              </View>
              
              {selectedSDK.npmPackage && (
                <View className="modal-section">
                  <Text className="section-title">NPM 包名</Text>
                  <View className="code-block">
                    <Text className="code-text">npm install {selectedSDK.npmPackage}</Text>
                  </View>
                </View>
              )}
              
              {selectedSDK.dependencies.length > 0 && (
                <View className="modal-section">
                  <Text className="section-title">依赖</Text>
                  <View className="deps-list">
                    {selectedSDK.dependencies.map(dep => (
                      <Text key={dep} className="dep-tag">{dep}</Text>
                    ))}
                  </View>
                </View>
              )}
              
              <View className="modal-section">
                <Text className="section-title">更新日志</Text>
                <Text className="section-content changelog">{selectedSDK.changelog}</Text>
              </View>
            </ScrollView>
            
            <View className="modal-footer">
              <Button className="modal-btn" onClick={() => handleViewDocs(selectedSDK)}>查看文档</Button>
              <Button className="modal-btn primary" onClick={() => handleDownload(selectedSDK)}>立即下载</Button>
            </View>
          </View>
        </View>
      )}
    </View>
  );
}
