// frontend/src/components/SideBarLeft/tabs/TokenUsage/TokenUsage.jsx
import React, { useEffect } from 'react';
import useTokenUsageStore from '../../../../Store/SideBarLeft/TokenUsageSlice';
import './TokenUsage.css';

const TokenUsage = () => {
  const {
    months,
    currentMonth,
    stats,
    roles,
    chats,
    selectedRole,
    selectedChat,
    loading,
    error,
    fetchMonths,
    setCurrentMonth,
    setSelectedRole,
    setSelectedChat,
    resetFilters
  } = useTokenUsageStore();

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

  if (loading && !stats) {
    return <div className="token-usage-loading">加载中...</div>;
  }

  if (error) {
    return <div className="token-usage-error">错误: {error}</div>;
  }

  if (!stats) {
    return <div className="token-usage-empty">暂无数据</div>;
  }

  // 格式化数字
  const formatNumber = (num) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(2) + 'M';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(2) + 'K';
    }
    return num.toString();
  };

  return (
    <div className="token-usage-container">
      {/* 月份选择器 */}
      <div className="token-usage-header">
        <h3>📊 Token 使用统计</h3>
        <select
          className="month-selector"
          value={currentMonth ? `${currentMonth.year}-${currentMonth.month}` : ''}
          onChange={(e) => {
            const [year, month] = e.target.value.split('-').map(Number);
            setCurrentMonth(year, month);
          }}
        >
          {months.map((m) => (
            <option key={`${m.year}-${m.month}`} value={`${m.year}-${m.month}`}>
              {m.year}年{m.month}月
            </option>
          ))}
        </select>
      </div>

      {/* 筛选器 */}
      <div className="token-usage-filters">
        <select
          className="filter-select"
          value={selectedRole || ''}
          onChange={(e) => setSelectedRole(e.target.value || null)}
        >
          <option value="">所有角色</option>
          {roles.map((role) => (
            <option key={role} value={role}>{role}</option>
          ))}
        </select>

        <select
          className="filter-select"
          value={selectedChat || ''}
          onChange={(e) => setSelectedChat(e.target.value || null)}
        >
          <option value="">所有聊天</option>
          {chats.map((chat) => (
            <option key={chat} value={chat}>{chat}</option>
          ))}
        </select>

        <button className="btn-reset" onClick={resetFilters}>
          重置
        </button>
      </div>

      {/* 统计卡片 */}
      <div className="stats-cards">
        <div className="stat-card total">
          <div className="stat-label">总 Token</div>
          <div className="stat-value">{formatNumber(stats.totalTokens)}</div>
        </div>
        <div className="stat-card prompt">
          <div className="stat-label">输入 Token</div>
          <div className="stat-value">{formatNumber(stats.totalPromptTokens)}</div>
        </div>
        <div className="stat-card completion">
          <div className="stat-label">输出 Token</div>
          <div className="stat-value">{formatNumber(stats.totalCompletionTokens)}</div>
        </div>
      </div>

      {/* 请求统计 */}
      <div className="request-stats">
        <div className="stat-item">
          <span className="stat-name">总请求数:</span>
          <span className="stat-number">{stats.totalRecords}</span>
        </div>
        <div className="stat-item success">
          <span className="stat-name">✅ 成功:</span>
          <span className="stat-number">{stats.completedCount}</span>
        </div>
        <div className="stat-item interrupted">
          <span className="stat-name">⏸️ 中断:</span>
          <span className="stat-number">{stats.interruptedCount}</span>
        </div>
        <div className="stat-item failed">
          <span className="stat-name">❌ 失败:</span>
          <span className="stat-number">{stats.failedCount}</span>
        </div>
      </div>

      {/* 日统计 */}
      {stats.dailyStats && Object.keys(stats.dailyStats).length > 0 && (
        <div className="daily-stats-section">
          <h4>📅 每日统计</h4>
          <div className="daily-stats-list">
            {Object.entries(stats.dailyStats)
              .sort(([a], [b]) => b.localeCompare(a))
              .slice(0, 10)
              .map(([day, data]) => (
                <div key={day} className="daily-stat-item">
                  <span className="day-label">{day}</span>
                  <span className="day-tokens">{formatNumber(data.totalTokens)} tokens</span>
                  <span className="day-count">{data.count} 次</span>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* 角色统计 */}
      {stats.roleStats && Object.keys(stats.roleStats).length > 0 && (
        <div className="role-stats-section">
          <h4>👤 角色统计</h4>
          <div className="role-stats-list">
            {Object.entries(stats.roleStats)
              .sort(([, a], [, b]) => b.totalTokens - a.totalTokens)
              .map(([role, data]) => (
                <div key={role} className="role-stat-item">
                  <span className="role-name">{role}</span>
                  <span className="role-tokens">{formatNumber(data.totalTokens)} tokens</span>
                  <span className="role-count">{data.count} 次</span>
                </div>
              ))}
          </div>
        </div>
      )}

      {/* 聊天统计 */}
      {stats.chatStats && Object.keys(stats.chatStats).length > 0 && (
        <div className="chat-stats-section">
          <h4>💬 聊天统计</h4>
          <div className="chat-stats-list">
            {Object.entries(stats.chatStats)
              .sort(([, a], [, b]) => b.totalTokens - a.totalTokens)
              .slice(0, 10)
              .map(([chat, data]) => (
                <div key={chat} className="chat-stat-item">
                  <span className="chat-name">{chat}</span>
                  <span className="chat-tokens">{formatNumber(data.totalTokens)} tokens</span>
                  <span className="chat-count">{data.count} 次</span>
                </div>
              ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default TokenUsage;
