import React, { useState, useEffect } from 'react';

function App() {
  const [deals, setDeals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadDeals = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_deals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'all_not_deleted', limit: 500, sort: 'update_time' })
      });
      const data = await response.json();
      setDeals(data.data || []);
    } catch (error) {
      console.error('Failed to load deals:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 0 }).format(amount);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'won': return '🏆';
      case 'lost': return '❌';
      case 'open': return '🔄';
      default: return '📋';
    }
  };

  if (loading) {
    return <div className="loading">Loading timeline...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>📅 Deals Timeline</h1>
        <button onClick={loadDeals} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="timeline">
        {deals.map((deal, index) => (
          <div key={deal.id} className="timeline-item">
            <div className="timeline-marker">
              <div className={`timeline-dot ${deal.status}`}>{getStatusIcon(deal.status)}</div>
              {index < deals.length - 1 && <div className="timeline-line"></div>}
            </div>
            <div className="timeline-content">
              <div className="deal-header">
                <div className="deal-title">{deal.title}</div>
                <div className="deal-value">{formatCurrency(deal.value || 0)}</div>
              </div>
              <div className="deal-meta">
                {deal.person_name && <span>👤 {deal.person_name}</span>}
                {deal.org_name && <span>🏢 {deal.org_name}</span>}
                <span className={`status-badge ${deal.status}`}>{deal.status}</span>
              </div>
              <div className="deal-date">Updated: {formatDate(deal.update_time)}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
