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

function App() {
  const [deals, setDeals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [timeframe, setTimeframe] = useState<'month' | 'quarter' | 'year'>('month');

  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 })
      });
      const data = await response.json();
      setDeals(data.data || []);
    } catch (error) {
      console.error('Failed to load deals:', error);
    } finally {
      setLoading(false);
    }
  };

  const calculateMetrics = () => {
    const won = deals.filter(d => d.status === 'won');
    const open = deals.filter(d => d.status === 'open');
    
    const revenue = won.reduce((sum, d) => sum + (d.value || 0), 0);
    const pipeline = open.reduce((sum, d) => sum + (d.value || 0), 0);
    
    const avgDealSize = won.length > 0 ? revenue / won.length : 0;
    const forecast = pipeline * 0.3; // Simple 30% forecast
    
    return { revenue, pipeline, avgDealSize, forecast, wonCount: won.length };
  };

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

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

  const metrics = calculateMetrics();

  return (
    <div className="app">
      <header className="header">
        <h1>💰 Revenue Dashboard</h1>
        <div className="timeframe-selector">
          <button className={timeframe === 'month' ? 'active' : ''} onClick={() => setTimeframe('month')}>Month</button>
          <button className={timeframe === 'quarter' ? 'active' : ''} onClick={() => setTimeframe('quarter')}>Quarter</button>
          <button className={timeframe === 'year' ? 'active' : ''} onClick={() => setTimeframe('year')}>Year</button>
        </div>
      </header>

      <div className="metrics-grid">
        <div className="metric-card primary">
          <div className="label">Total Revenue</div>
          <div className="value">{formatCurrency(metrics.revenue)}</div>
          <div className="sublabel">{metrics.wonCount} won deals</div>
        </div>
        <div className="metric-card">
          <div className="label">Pipeline Value</div>
          <div className="value">{formatCurrency(metrics.pipeline)}</div>
        </div>
        <div className="metric-card">
          <div className="label">Avg Deal Size</div>
          <div className="value">{formatCurrency(metrics.avgDealSize)}</div>
        </div>
        <div className="metric-card">
          <div className="label">Forecast</div>
          <div className="value">{formatCurrency(metrics.forecast)}</div>
          <div className="sublabel">30% pipeline conversion</div>
        </div>
      </div>

      <div className="chart-section">
        <h2>Revenue Trend</h2>
        <div className="chart-placeholder">
          <div className="bar" style={{ height: '60%' }}></div>
          <div className="bar" style={{ height: '75%' }}></div>
          <div className="bar" style={{ height: '85%' }}></div>
          <div className="bar" style={{ height: '100%' }}></div>
        </div>
      </div>
    </div>
  );
}

export default App;
