import React, { useState, useEffect } from 'react';
import { Download, Smartphone, Monitor, Apple, ChevronRight, Cpu } from 'lucide-react';
import apiClient from '../utils/apiClient';
import { buildApiUrl, API_ENDPOINTS } from '../config/api';
import './ClientDownloads.css';

const ClientDownloads = () => {
  const [clients, setClients] = useState({
    mobile: [],
    desktop: [],
    terminal: []
  });
  const [loading, setLoading] = useState(true);

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

  const fetchLatestClients = async () => {
    setLoading(true);
    try {
      const response = await apiClient.get(buildApiUrl(API_ENDPOINTS.CLIENT_DOWNLOADS.LATEST));
      console.log('Latest clients response:', response);
      setClients(response.data || { mobile: [], desktop: [], terminal: [] });
    } catch (error) {
      console.error('获取客户端下载失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getPlatformIcon = (platformCode) => {
    const code = (platformCode || '').toUpperCase();

    // 根据 platform_code 判断图标
    if (code.includes('IOS') || code.includes('MAC')) {
      return <Apple size={32} />;
    } else if (code.includes('ANDROID')) {
      return <Smartphone size={32} />;
    } else if (code.includes('TERM') || code.includes('MCU')) {
      return <Cpu size={32} />;
    } else {
      return <Monitor size={32} />;
    }
  };

  const getPlatformLabel = (client) => {
    // 优先使用 dict_data 的中文标签
    return client.label_cn || client.platform_code || '未知平台';
  };

  const formatFileSize = (bytes) => {
    if (!bytes) return '';
    const mb = bytes / (1024 * 1024);
    return `${mb.toFixed(0)} MB`;
  };

  if (loading) {
    return (
      <div className="client-downloads-section">
        <div className="section-header">
          <h2>下载客户端</h2>
        </div>
        <div className="loading-message">加载中...</div>
      </div>
    );
  }

  return (
    <div className="client-downloads-section">
      <div className="section-header">
        <h2>下载客户端</h2>
        <p>选择适合您设备的版本</p>
      </div>

      <div className="downloads-container">
        {/* 移动端 */}
        {clients.mobile && clients.mobile.length > 0 && (
          <div className="platform-group">
            <div className="group-header">
              <Smartphone size={24} />
              <h3>移动端</h3>
            </div>
            <div className="clients-list">
              {clients.mobile.map(client => (
                <a
                  key={client.id}
                  href={client.download_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="client-download-card"
                >
                  <div className="card-icon">
                    {getPlatformIcon(client.platform_code)}
                  </div>
                  <div className="card-info">
                    <h4>{getPlatformLabel(client)}</h4>
                    <div className="version-info">
                      <span className="version">v{client.version}</span>
                      {client.file_size && (
                        <span className="file-size">{formatFileSize(client.file_size)}</span>
                      )}
                    </div>
                    {client.min_system_version && (
                      <p className="system-req">需要 {client.min_system_version} 或更高版本</p>
                    )}
                  </div>
                  <div className="download-icon">
                    <ChevronRight size={20} />
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}

        {/* 桌面端 */}
        {clients.desktop && clients.desktop.length > 0 && (
          <div className="platform-group">
            <div className="group-header">
              <Monitor size={24} />
              <h3>桌面端</h3>
            </div>
            <div className="clients-list">
              {clients.desktop.map(client => (
                <a
                  key={client.id}
                  href={client.download_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="client-download-card"
                >
                  <div className="card-icon">
                    {getPlatformIcon(client.platform_code)}
                  </div>
                  <div className="card-info">
                    <h4>{getPlatformLabel(client)}</h4>
                    <div className="version-info">
                      <span className="version">v{client.version}</span>
                      {client.file_size && (
                        <span className="file-size">{formatFileSize(client.file_size)}</span>
                      )}
                    </div>
                    {client.min_system_version && (
                      <p className="system-req">需要 {client.min_system_version} 或更高版本</p>
                    )}
                  </div>
                  <div className="download-icon">
                    <Download size={20} />
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}

        {/* 专用终端 */}
        {clients.terminal && clients.terminal.length > 0 && (
          <div className="platform-group">
            <div className="group-header">
              <Cpu size={24} />
              <h3>专用终端</h3>
            </div>
            <div className="clients-list">
              {clients.terminal.map(client => (
                <a
                  key={client.id}
                  href={client.download_url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="client-download-card"
                >
                  <div className="card-icon">
                    {getPlatformIcon(client.platform_code)}
                  </div>
                  <div className="card-info">
                    <h4>{getPlatformLabel(client)}</h4>
                    <div className="version-info">
                      <span className="version">v{client.version}</span>
                      {client.file_size && (
                        <span className="file-size">{formatFileSize(client.file_size)}</span>
                      )}
                    </div>
                    {client.min_system_version && (
                      <p className="system-req">需要 {client.min_system_version} 或更高版本</p>
                    )}
                  </div>
                  <div className="download-icon">
                    <Download size={20} />
                  </div>
                </a>
              ))}
            </div>
          </div>
        )}
      </div>

      {!clients.mobile?.length && !clients.desktop?.length && !clients.terminal?.length && (
        <div className="empty-message">暂无可用的客户端下载</div>
      )}
    </div>
  );
};

export default ClientDownloads;
