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

interface Stage {
  id: number;
  name: string;
  order_nr: number;
  deal_probability: number;
}

interface StageMetrics {
  stage_id: number;
  stage_name: string;
  count: number;
  value: number;
  conversion_rate: number;
  avg_time_in_stage: number;
  avg_deal_value: number;
}

function App() {
  const [stages, setStages] = useState<Stage[]>([]);
  const [metrics, setMetrics] = useState<StageMetrics[]>([]);
  const [loading, setLoading] = useState(true);
  const [totalDeals, setTotalDeals] = useState(0);
  const [totalValue, setTotalValue] = useState(0);
  const [avgVelocity, setAvgVelocity] = useState(0);

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

  const loadAnalytics = async () => {
    setLoading(true);
    try {
      // Load stages
      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: Stage, b: Stage) => a.order_nr - b.order_nr);
      setStages(sortedStages);

      // Load deals
      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 || [];
      
      setTotalDeals(deals.length);
      const totalVal = deals.reduce((sum: number, d: any) => sum + (d.value || 0), 0);
      setTotalValue(totalVal);

      // Calculate metrics per stage
      const stageMetrics: StageMetrics[] = sortedStages.map((stage: Stage, index: number) => {
        const stageDeals = deals.filter((d: any) => d.stage_id === stage.id);
        const stageValue = stageDeals.reduce((sum: number, d: any) => sum + (d.value || 0), 0);
        const prevStage = sortedStages[index - 1];
        const prevStageDeals = prevStage ? deals.filter((d: any) => d.stage_id === prevStage.id) : deals;
        const conversionRate = prevStageDeals.length > 0 ? (stageDeals.length / prevStageDeals.length * 100) : 100;
        
        return {
          stage_id: stage.id,
          stage_name: stage.name,
          count: stageDeals.length,
          value: stageValue,
          conversion_rate: conversionRate,
          avg_time_in_stage: 5 + Math.random() * 10, // Mock data
          avg_deal_value: stageDeals.length > 0 ? stageValue / stageDeals.length : 0
        };
      });

      setMetrics(stageMetrics);
      
      // Calculate average velocity (mock)
      const avgVel = stageMetrics.reduce((sum, m) => sum + m.avg_time_in_stage, 0) / stageMetrics.length;
      setAvgVelocity(avgVel);
    } catch (error) {
      console.error('Failed to load analytics:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const getBottleneck = () => {
    if (metrics.length === 0) return null;
    return metrics.reduce((worst, current) => 
      current.conversion_rate < worst.conversion_rate ? current : worst
    );
  };

  const bottleneck = getBottleneck();

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

  return (
    <div className="app">
      <header className="header">
        <h1>📊 Pipeline Analytics</h1>
        <button onClick={loadAnalytics} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="summary-cards">
        <div className="summary-card">
          <div className="card-label">Total Deals</div>
          <div className="card-value">{totalDeals}</div>
        </div>
        <div className="summary-card">
          <div className="card-label">Pipeline Value</div>
          <div className="card-value">{formatCurrency(totalValue)}</div>
        </div>
        <div className="summary-card">
          <div className="card-label">Avg Velocity</div>
          <div className="card-value">{avgVelocity.toFixed(1)} days</div>
        </div>
        {bottleneck && (
          <div className="summary-card alert">
            <div className="card-label">🚨 Bottleneck</div>
            <div className="card-value">{bottleneck.stage_name}</div>
            <div className="card-sublabel">{bottleneck.conversion_rate.toFixed(1)}% conversion</div>
          </div>
        )}
      </div>

      <div className="funnel-section">
        <h2>Conversion Funnel</h2>
        <div className="funnel">
          {metrics.map((metric, index) => {
            const maxCount = Math.max(...metrics.map(m => m.count));
            const widthPercent = maxCount > 0 ? (metric.count / maxCount * 100) : 0;
            
            return (
              <div key={metric.stage_id} className="funnel-stage">
                <div className="funnel-stage-label">
                  <span className="stage-name">{metric.stage_name}</span>
                  <span className="stage-count">{metric.count} deals</span>
                </div>
                <div className="funnel-bar" style={{ width: `${widthPercent}%` }}>
                  <span className="bar-value">{formatCurrency(metric.value)}</span>
                </div>
                {index > 0 && (
                  <div className="conversion-badge">
                    {metric.conversion_rate.toFixed(1)}% conversion
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div className="metrics-table-section">
        <h2>Stage Metrics</h2>
        <table className="metrics-table">
          <thead>
            <tr>
              <th>Stage</th>
              <th>Deals</th>
              <th>Value</th>
              <th>Avg Deal Value</th>
              <th>Conversion Rate</th>
              <th>Avg Time in Stage</th>
            </tr>
          </thead>
          <tbody>
            {metrics.map(metric => (
              <tr key={metric.stage_id}>
                <td className="stage-name-cell">{metric.stage_name}</td>
                <td>{metric.count}</td>
                <td className="value-cell">{formatCurrency(metric.value)}</td>
                <td className="value-cell">{formatCurrency(metric.avg_deal_value)}</td>
                <td>
                  <div className="conversion-bar">
                    <div 
                      className="conversion-fill" 
                      style={{ width: `${metric.conversion_rate}%` }}
                    ></div>
                    <span className="conversion-text">{metric.conversion_rate.toFixed(1)}%</span>
                  </div>
                </td>
                <td>{metric.avg_time_in_stage.toFixed(1)} days</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

export default App;
