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

interface StageMetrics {
  id: number;
  name: string;
  count: number;
  value: number;
  percentage: number;
}

function App() {
  const [stages, setStages] = useState<StageMetrics[]>([]);
  const [loading, setLoading] = useState(true);

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

  const loadFunnelData = async () => {
    setLoading(true);
    try {
      const stagesResponse = await fetch('/mcp/pipedrive_stages_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({})
      });
      const stagesData = await stagesResponse.json();
      const sortedStages = (stagesData.data || []).sort((a: any, b: any) => a.order_nr - b.order_nr);

      const dealsResponse = await fetch('/mcp/pipedrive_deals_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ status: 'open', limit: 500 })
      });
      const dealsData = await dealsResponse.json();
      const deals = dealsData.data || [];

      const maxDeals = Math.max(...sortedStages.map((s: any) => 
        deals.filter((d: any) => d.stage_id === s.id).length
      ));

      const stageMetrics: StageMetrics[] = sortedStages.map((stage: any) => {
        const stageDeals = deals.filter((d: any) => d.stage_id === stage.id);
        const stageValue = stageDeals.reduce((sum: number, d: any) => sum + (d.value || 0), 0);
        
        return {
          id: stage.id,
          name: stage.name,
          count: stageDeals.length,
          value: stageValue,
          percentage: maxDeals > 0 ? (stageDeals.length / maxDeals * 100) : 0
        };
      });

      setStages(stageMetrics);
    } catch (error) {
      console.error('Failed to load funnel data:', error);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <div className="app">
      <header className="header">
        <h1>🎯 Pipeline Funnel</h1>
        <button onClick={loadFunnelData} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="funnel-container">
        {stages.map((stage, index) => (
          <div key={stage.id} className="funnel-stage" style={{ width: `${stage.percentage}%` }}>
            <div className="funnel-content">
              <div className="stage-name">{stage.name}</div>
              <div className="stage-count">{stage.count} deals</div>
              <div className="stage-value">{formatCurrency(stage.value)}</div>
              {index > 0 && stages[index - 1] && (
                <div className="drop-off">
                  {((stages[index - 1].count - stage.count) / stages[index - 1].count * 100).toFixed(1)}% drop-off
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      <div className="metrics-grid">
        {stages.map((stage) => (
          <div key={stage.id} className="metric-card">
            <h3>{stage.name}</h3>
            <div className="metric-value">{stage.count} deals</div>
            <div className="metric-sub">{formatCurrency(stage.value)}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
