import React, { useState, useEffect } from 'react';
import './style.css';

interface MetricCardProps {
  title: string;
  value: string | number;
  change?: string;
  icon: string;
}

const MetricCard: React.FC<MetricCardProps> = ({ title, value, change, icon }) => (
  <div className="metric-card">
    <div className="metric-icon">{icon}</div>
    <div className="metric-content">
      <h3>{title}</h3>
      <div className="metric-value">{value}</div>
      {change && <div className={`metric-change ${change.startsWith('+') ? 'positive' : 'negative'}`}>{change}</div>}
    </div>
  </div>
);

interface Deal {
  id: number;
  title: string;
  value: number;
  status: string;
  stage_id: number;
  expected_close_date?: string;
  add_time: string;
}

function App() {
  const [deals, setDeals] = useState<Deal[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    totalDeals: 0,
    wonDeals: 0,
    lostDeals: 0,
    openDeals: 0,
    totalValue: 0,
    wonValue: 0,
    avgDealValue: 0,
    winRate: 0,
    forecast: 0
  });

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

  const loadDeals = async () => {
    setLoading(true);
    try {
      // Call MCP tool to get deals
      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();
      const dealsData = data.data || [];
      setDeals(dealsData);
      calculateStats(dealsData);
    } catch (error) {
      console.error('Failed to load deals:', error);
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (dealsData: Deal[]) => {
    const won = dealsData.filter(d => d.status === 'won');
    const lost = dealsData.filter(d => d.status === 'lost');
    const open = dealsData.filter(d => d.status === 'open');
    
    const totalValue = dealsData.reduce((sum, d) => sum + (d.value || 0), 0);
    const wonValue = won.reduce((sum, d) => sum + (d.value || 0), 0);
    const openValue = open.reduce((sum, d) => sum + (d.value || 0), 0);
    
    const winRate = won.length + lost.length > 0 
      ? (won.length / (won.length + lost.length) * 100) 
      : 0;
    
    const forecast = wonValue + (openValue * (winRate / 100));

    setStats({
      totalDeals: dealsData.length,
      wonDeals: won.length,
      lostDeals: lost.length,
      openDeals: open.length,
      totalValue,
      wonValue,
      avgDealValue: dealsData.length > 0 ? totalValue / dealsData.length : 0,
      winRate,
      forecast
    });
  };

  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 deal dashboard...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>📊 Deal Dashboard</h1>
        <button onClick={loadDeals} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="metrics-grid">
        <MetricCard 
          title="Total Deals" 
          value={stats.totalDeals} 
          icon="📈"
        />
        <MetricCard 
          title="Won Deals" 
          value={stats.wonDeals} 
          change={`${stats.winRate.toFixed(1)}% win rate`}
          icon="✅"
        />
        <MetricCard 
          title="Lost Deals" 
          value={stats.lostDeals} 
          icon="❌"
        />
        <MetricCard 
          title="Open Deals" 
          value={stats.openDeals} 
          icon="🔄"
        />
        <MetricCard 
          title="Total Value" 
          value={formatCurrency(stats.totalValue)} 
          icon="💰"
        />
        <MetricCard 
          title="Won Value" 
          value={formatCurrency(stats.wonValue)} 
          icon="🏆"
        />
        <MetricCard 
          title="Avg Deal Value" 
          value={formatCurrency(stats.avgDealValue)} 
          icon="📊"
        />
        <MetricCard 
          title="Revenue Forecast" 
          value={formatCurrency(stats.forecast)} 
          icon="🔮"
        />
      </div>

      <div className="chart-section">
        <h2>Win/Loss Ratio</h2>
        <div className="ratio-bars">
          <div className="ratio-bar won" style={{ width: `${stats.winRate}%` }}>
            Won: {stats.wonDeals} ({stats.winRate.toFixed(1)}%)
          </div>
          <div className="ratio-bar lost" style={{ width: `${100 - stats.winRate}%` }}>
            Lost: {stats.lostDeals} ({(100 - stats.winRate).toFixed(1)}%)
          </div>
        </div>
      </div>

      <div className="recent-section">
        <h2>Recent Deals ({deals.slice(0, 10).length})</h2>
        <div className="deals-list">
          {deals.slice(0, 10).map(deal => (
            <div key={deal.id} className={`deal-item status-${deal.status}`}>
              <div className="deal-title">{deal.title}</div>
              <div className="deal-meta">
                <span className="deal-value">{formatCurrency(deal.value || 0)}</span>
                <span className={`deal-status ${deal.status}`}>{deal.status}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

export default App;
