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

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

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

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

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

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

  const totalRevenue = deals.reduce((sum, d) => sum + (d.value || 0), 0);

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

  return (
    <div className="app">
      <header className="header">
        <div className="celebration">
          <h1>🏆 Closed Won Deals</h1>
          <div className="stats">
            <div className="stat">{deals.length} deals won</div>
            <div className="stat revenue">{formatCurrency(totalRevenue)} total revenue</div>
          </div>
        </div>
        <button onClick={loadWonDeals} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="won-grid">
        {deals.map(deal => (
          <div key={deal.id} className="won-card">
            <div className="confetti">🎉</div>
            <div className="deal-title">{deal.title}</div>
            <div className="deal-value">{formatCurrency(deal.value || 0)}</div>
            <div className="deal-meta">
              {deal.person_name && <div>👤 {deal.person_name}</div>}
              {deal.org_name && <div>🏢 {deal.org_name}</div>}
              <div>Won: {deal.won_time ? formatDate(deal.won_time) : 'N/A'}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
