import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import LanguageSwitcher from './components/LanguageSwitcher';
import SiteFooter from './components/SiteFooter';
import { dashboardAPI, authAPI } from './services/api';

function Dashboard() {
  const navigate = useNavigate();
  const { t } = useTranslation();
  
  const [merchantId, setMerchantId] = useState('');
  const [balance, setBalance] = useState(0);
  const [incomingTransactions, setIncomingTransactions] = useState([]);
  const [outgoingTransactions, setOutgoingTransactions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);
        const [merchantResponse, balanceResponse, incomingResponse, outgoingResponse] = await Promise.all([
          dashboardAPI.getMerchantInfo(),
          dashboardAPI.getBalance(),
          dashboardAPI.getTransactions({ type: 'incoming', limit: 5 }),
          dashboardAPI.getTransactions({ type: 'outgoing', limit: 5 })
        ]);
        
        setMerchantId(merchantResponse.data.merchantId);
        setBalance(balanceResponse.data.balance);
        setIncomingTransactions(incomingResponse.data.transactions);
        setOutgoingTransactions(outgoingResponse.data.transactions);
      } catch (err) {
        console.error('Failed to fetch dashboard data:', err);
        setError('Failed to load dashboard data. Please try again.');
        // Fallback to mock data for demo
        setMerchantId('MER-123456');
        setBalance(12543.78);
        setIncomingTransactions([
          { id: 'IN-1001', date: '2025-09-01', amount: 120.0, method: 'Card', customer: 'Alice' },
          { id: 'IN-1002', date: '2025-09-02', amount: 250.5, method: 'Crypto', customer: 'Bob' },
          { id: 'IN-1003', date: '2025-09-03', amount: 75.25, method: 'Bank Transfer', customer: 'Charlie' },
        ]);
        setOutgoingTransactions([
          { orderId: 'OUT-2001', orderType: 'Single', coin: 'USDT', wallet: 'TRX', amount: 300.0, status: 'Completed' },
          { orderId: 'OUT-2002', orderType: 'Batch', coin: 'USDC', wallet: 'ETH', amount: 1500.0, status: 'Pending' },
        ]);
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  const handleLogout = async () => {
    try {
      await authAPI.logout();
    } catch (err) {
      console.error('Logout error:', err);
    } finally {
      localStorage.removeItem('authToken');
      navigate('/login');
    }
  };

  const handleWithdraw = () => {
    navigate('/withdrawal');
  };

  const handleTopUp = () => {
    navigate('/withdrawal');
  };

  const handleViewAllIncoming = () => {
    alert('Viewing all incoming transactions. This is a placeholder action.');
  };

  const handleViewAllOutgoing = () => {
    alert('Viewing all outgoing transactions. This is a placeholder action.');
  };

  return (
    <>
      <div className="container" style={{ padding: '2rem', maxWidth: '1400px', margin: '0 auto' }}>
        <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
          <div>
            <h2>{t('dashboard.title')}</h2>
            <div style={{ color: '#718096', fontSize: '0.9rem', marginTop: '0.25rem' }}>
              {t('dashboard.merchantId')}: <span style={{ color: '#1A202C', fontWeight: 600 }}>{merchantId}</span>
            </div>
          </div>
          <nav style={{ display: 'flex', gap: '0.75rem' }}>
            <LanguageSwitcher />
            <Link to="/api-docs" className="btn-outline">
              {t('navigation.apiDocs')}
            </Link>
            <button className="btn-outline" onClick={() => navigate('/settings')}>
              {t('common.settings')}
            </button>
            <button onClick={handleLogout} className="btn-secondary">
              {t('common.logout')}
            </button>
          </nav>
        </header>

        {loading && (
          <div style={{ textAlign: 'center', padding: '2rem' }}>
            <p>{t('common.loading')}...</p>
          </div>
        )}

        {error && (
          <div style={{ textAlign: 'center', padding: '1rem', color: '#DC192C', backgroundColor: '#FED7D7', borderRadius: '6px', marginBottom: '1rem' }}>
            {error}
          </div>
        )}

        {!loading && (
          <>
            {/* Balance Summary */}
            <section style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '1rem', marginBottom: '1.5rem' }}>
          <div style={{ background: 'white', borderRadius: '12px', padding: '1.5rem', boxShadow: '0 10px 25px rgba(0,0,0,0.1)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '1rem' }}>
              <div>
                <h3 style={{ marginBottom: '0.25rem' }}>Current Balance</h3>
                <div style={{ fontSize: '2rem', fontWeight: 700, color: '#DC192C' }}>
                  $ {balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </div>
                <p style={{ color: '#718096', marginTop: '0.25rem' }}>Total funds received via HicoinPay.</p>
              </div>
              <div style={{ display: 'flex', gap: '0.5rem' }}>
                <button className="btn-secondary" onClick={handleTopUp}>
                  Top Up
                </button>
                <button className="btn-primary" onClick={handleWithdraw}>
                  Withdraw
                </button>
              </div>
            </div>
          </div>
        </section>

        {/* Transactions */}
        <section style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '1.5rem' }}>
          <div style={{ background: 'white', borderRadius: '12px', padding: '1rem', boxShadow: '0 10px 25px rgba(0,0,0,0.08)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem' }}>
              <h4 style={{ margin: 0 }}>Incoming Transactions</h4>
              <button className="btn-outline" onClick={handleViewAllIncoming}>
                View All
              </button>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ textAlign: 'left', color: '#718096' }}>
                    <th style={{ padding: '0.5rem 0' }}>ID</th>
                    <th style={{ padding: '0.5rem 0' }}>Date</th>
                    <th style={{ padding: '0.5rem 0' }}>Amount</th>
                    <th style={{ padding: '0.5rem 0' }}>Method</th>
                    <th style={{ padding: '0.5rem 0' }}>Customer</th>
                  </tr>
                </thead>
                <tbody>
                  {incomingTransactions.map((tx) => (
                    <tr key={tx.id}>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.id}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.date}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7', color: '#2F855A' }}>+${tx.amount.toFixed(2)}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.method}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.customer}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div style={{ background: 'white', borderRadius: '12px', padding: '1rem', boxShadow: '0 10px 25px rgba(0,0,0,0.08)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.75rem' }}>
              <h4 style={{ margin: 0 }}>Outgoing Transactions</h4>
              <button className="btn-outline" onClick={handleViewAllOutgoing}>
                View All
              </button>
            </div>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ textAlign: 'left', color: '#718096' }}>
                    <th style={{ padding: '0.5rem 0' }}>Order ID</th>
                    <th style={{ padding: '0.5rem 0' }}>Order Type</th>
                    <th style={{ padding: '0.5rem 0' }}>Coin</th>
                    <th style={{ padding: '0.5rem 0' }}>Wallet</th>
                    <th style={{ padding: '0.5rem 0' }}>Amount</th>
                    <th style={{ padding: '0.5rem 0' }}>Status</th>
                  </tr>
                </thead>
                <tbody>
                  {outgoingTransactions.map((tx) => (
                    <tr key={tx.orderId}>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.orderId}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.orderType}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.coin}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.wallet}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7', color: '#C53030' }}>-${tx.amount.toFixed(2)}</td>
                      <td style={{ padding: '0.5rem 0', borderTop: '1px solid #EDF2F7' }}>{tx.status}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </section>
          </>
        )}
      </div>

      <SiteFooter />
    </>
  );
}

export default Dashboard; 