import { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useWalletStore } from '../store/wallet';
import { fromSomas, toSomas } from '../lib/transaction';

export default function DashboardPage() {
  const { address, balance, transactions, refreshBalance, refreshTransactions } =
    useWalletStore();

  useEffect(() => {
    refreshBalance();
    refreshTransactions();

    // Refresh every 30 seconds
    const interval = setInterval(() => {
      refreshBalance();
    }, 30000);

    return () => clearInterval(interval);
  }, [refreshBalance, refreshTransactions]);

  const formatBalance = (amount: string | undefined) => {
    if (!amount) return '0';
    try {
      return fromSomas(toSomas(amount));
    } catch {
      return amount;
    }
  };

  return (
    <div className="space-y-8">
      {/* Balance Card */}
      <div className="card">
        <div className="text-sm text-slate-400 mb-2">Total Balance</div>
        <div className="text-4xl font-bold mb-1">
          {formatBalance(balance?.total)} <span className="text-xl text-slate-400">SYNOR</span>
        </div>
        <div className="text-sm text-slate-500">
          {balance?.pending !== '0' && (
            <span className="text-yellow-400">
              +{formatBalance(balance?.pending)} pending
            </span>
          )}
        </div>

        <div className="flex gap-4 mt-6">
          <Link to="/wallet/send" className="btn btn-primary flex-1 text-center">
            Send
          </Link>
          <Link to="/wallet/receive" className="btn btn-secondary flex-1 text-center">
            Receive
          </Link>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-3 gap-4">
        <div className="card">
          <div className="text-sm text-slate-400 mb-1">Confirmed</div>
          <div className="text-xl font-semibold">
            {formatBalance(balance?.confirmed)}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-slate-400 mb-1">Pending</div>
          <div className="text-xl font-semibold text-yellow-400">
            {formatBalance(balance?.pending)}
          </div>
        </div>
        <div className="card">
          <div className="text-sm text-slate-400 mb-1">Transactions</div>
          <div className="text-xl font-semibold">{transactions.length}</div>
        </div>
      </div>

      {/* Recent Transactions */}
      <div className="card">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold">Recent Transactions</h2>
          <Link
            to="/wallet/history"
            className="text-sm text-synor-400 hover:text-synor-300"
          >
            View All →
          </Link>
        </div>

        {transactions.length === 0 ? (
          <div className="text-center py-8 text-slate-500">
            <div className="text-4xl mb-2">◇</div>
            <div>No transactions yet</div>
          </div>
        ) : (
          <div className="space-y-3">
            {transactions.slice(0, 5).map((tx) => {
              const isReceived = tx.outputs.some((o) => o.address === address);
              const amount = tx.outputs
                .filter((o) => (isReceived ? o.address === address : o.address !== address))
                .reduce((sum, o) => sum + parseFloat(o.amount), 0);

              return (
                <div
                  key={tx.id}
                  className="flex items-center justify-between p-3 bg-slate-900 rounded-lg"
                >
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-8 h-8 rounded-full flex items-center justify-center ${
                        isReceived ? 'bg-green-900/50 text-green-400' : 'bg-red-900/50 text-red-400'
                      }`}
                    >
                      {isReceived ? '↓' : '↑'}
                    </div>
                    <div>
                      <div className="font-medium">
                        {isReceived ? 'Received' : 'Sent'}
                      </div>
                      <div className="text-xs text-slate-500 font-mono">
                        {tx.id.slice(0, 8)}...{tx.id.slice(-8)}
                      </div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div
                      className={`font-semibold ${
                        isReceived ? 'text-green-400' : 'text-red-400'
                      }`}
                    >
                      {isReceived ? '+' : '-'}{amount.toFixed(4)} SYNOR
                    </div>
                    <div className="text-xs text-slate-500">
                      {tx.confirmations > 0
                        ? `${tx.confirmations} confirmations`
                        : 'Pending'}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
