import { useState, useEffect } from 'react';
import apiClient from '../api/client';

export default function BalanceHistory({ token, mnemonic }) {
  const [history, setHistory] = useState([]);
  const [withdrawals, setWithdrawals] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchHistory = async () => {
      if (!token || !mnemonic) return;
      
      setLoading(true);
      setError(null);
      
      try {
        const [historyRes, withdrawalsRes] = await Promise.all([
          apiClient.get(`/api/balance-history/${token}`, { params: { phrase: mnemonic } }),
          apiClient.get('/api/withdraw/history', { params: { phrase: mnemonic } }),
        ]);
        
        if (historyRes.data.success) {
          // Исключаем withdrawal/withdrawal_refund — они отображаются отдельно из таблицы withdrawals
          setHistory(historyRes.data.data.filter(
            h => h.operation_type !== 'withdrawal' && h.operation_type !== 'withdrawal_refund'
          ));
        }
        if (withdrawalsRes.data.success) {
          // Фильтруем только выводы по текущему токену
          const sym = token.toUpperCase();
          setWithdrawals(withdrawalsRes.data.data.filter(w => w.token_symbol === sym));
        }
      } catch (err) {
        console.error('Error loading balance history:', err);
        setError('Ошибка при загрузке истории');
      } finally {
        setLoading(false);
      }
    };

    fetchHistory();
  }, [token, mnemonic]);

  const getOperationColor = (type) => {
    switch (type) {
      case 'stake':
      case 'swap_freeze':
      case 'withdrawal':
        return 'text-red-400';
      case 'unstake':
      case 'claim_reward':
      case 'swap_release':
      case 'withdrawal_refund':
        return 'text-green-400';
      default:
        return 'text-gray-400';
    }
  };

  const getOperationName = (type) => {
    switch (type) {
      case 'stake': return 'Стейкинг';
      case 'unstake': return 'Разблокирован';
      case 'claim_reward': return 'Награда';
      case 'swap_freeze': return 'Swap freeze';
      case 'swap_release': return 'Swap release';
      case 'withdrawal': return 'Вывод';
      case 'withdrawal_refund': return 'Возврат';
      default: return 'Операция';
    }
  };

  const isNegativeOperation = (type) => ['stake', 'swap_freeze', 'withdrawal'].includes(type);

  const getWithdrawalStatusBadge = (status) => {
    switch (status) {
      case 'pending':
        return <span className="text-xs bg-yellow-500/15 text-yellow-400 px-2 py-0.5 rounded-full border border-yellow-500/20">в обработке</span>;
      case 'success':
        return <span className="text-xs bg-green-500/15 text-green-400 px-2 py-0.5 rounded-full border border-green-500/20">успешно</span>;
      case 'error':
        return <span className="text-xs bg-red-500/15 text-red-400 px-2 py-0.5 rounded-full border border-red-500/20">ошибка</span>;
      default:
        return null;
    }
  };

  // Форматирование даты с учетом часового пояса
  const formatDate = (dateString) => {
    // SQLite сохраняет время в UTC, добавляем 'Z' если его нет
    const utcDateString = dateString.endsWith('Z') ? dateString : dateString + 'Z';
    const date = new Date(utcDateString);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return 'Только что';
    if (minutes < 60) return `${minutes} мин назад`;
    if (hours < 24) return `${hours} ч назад`;
    if (days < 7) return `${days} дн назад`;
    
    return date.toLocaleDateString('ru-RU', { 
      day: 'numeric', 
      month: 'short', 
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  if (loading) {
    return (
      <div className="bg-gray-800/30 rounded-xl p-4 mt-4">
        <h2 className="text-lg font-semibold text-white mb-3">История операций</h2>
        <div className="flex justify-center items-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-white"></div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-gray-800/30 rounded-xl p-4 mt-4">
        <h2 className="text-lg font-semibold text-white mb-3">История операций</h2>
        <p className="text-red-400 text-center">{error}</p>
      </div>
    );
  }

  const hasAny = history.length > 0 || withdrawals.length > 0;

  if (!hasAny) {
    return (
      <div className="bg-gray-800/30 rounded-xl p-4 mt-4">
        <h2 className="text-lg font-semibold text-white mb-3">История операций</h2>
        <p className="text-gray-400 text-center">
          История операций пуста. Начните стейкинг, чтобы увидеть здесь операции.
        </p>
      </div>
    );
  }

  // Объединяем и сортируем по дате (новые сверху)
  const allItems = [
    ...history.map(h => ({ ...h, _type: 'history' })),
    ...withdrawals.map(w => ({ ...w, _type: 'withdrawal' })),
  ].sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

  return (
    <div className="bg-gray-800/30 rounded-xl p-4 mt-4">
      <h2 className="text-lg font-semibold text-white mb-3">История операций</h2>
      <div className="space-y-0">
        {allItems.map((item) => {
          if (item._type === 'withdrawal') {
            return (
              <div
                key={`w-${item.id}`}
                className="border-t border-b border-gray-700/30 py-4 first:border-t-0 last:border-b-0"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                      <span className="font-semibold text-red-400">Вывод</span>
                      {getWithdrawalStatusBadge(item.status)}
                    </div>
                    <p className="text-xs text-gray-500 mb-2 break-all">
                      → {item.to_address}
                    </p>
                    {/* Изменение баланса */}
                    {item.balance_before != null && item.balance_after != null && (
                      <div className="flex items-center space-x-2 text-xs text-gray-500">
                        <span>{parseFloat(item.balance_before).toFixed(6)} {token}</span>
                        <span>→</span>
                        <span>{parseFloat(item.balance_after).toFixed(6)} {token}</span>
                      </div>
                    )}
                  </div>
                  <div className="text-right ml-4 shrink-0">
                    <div className="font-bold text-lg text-red-400">
                      -{parseFloat(item.amount).toFixed(6)}
                    </div>
                    {item.amount_usd > 0 && (
                      <div className="text-xs text-gray-500">${parseFloat(item.amount_usd).toFixed(2)}</div>
                    )}
                    <div className="text-xs text-gray-500 mt-1">
                      {formatDate(item.created_at)}
                    </div>
                  </div>
                </div>
              </div>
            );
          }

          return (
            <div
              key={`h-${item.id}`}
              className="border-t border-b border-gray-700/30 py-4 first:border-t-0 last:border-b-0"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center space-x-2 mb-1">
                    <span className={`font-semibold ${getOperationColor(item.operation_type)}`}>
                      {getOperationName(item.operation_type)}
                    </span>
                  </div>
                  {item.description && (
                    <p className="text-sm text-gray-400 mb-2 break-words">
                      {item.description}
                    </p>
                  )}
                  <div className="flex items-center space-x-2 text-xs text-gray-500">
                    <span>{item.balance_before.toFixed(6)} {token}</span>
                    <span>→</span>
                    <span>{item.balance_after.toFixed(6)} {token}</span>
                  </div>
                </div>
                <div className="text-right ml-4">
                  <div className={`font-bold text-lg ${getOperationColor(item.operation_type)}`}>
                    {isNegativeOperation(item.operation_type) ? '-' : '+'}
                    {Math.abs(item.amount).toFixed(6)}
                  </div>
                  <div className="text-xs text-gray-500 mt-1">
                    {formatDate(item.created_at)}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
