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

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

interface Deal {
  id: number;
  title: string;
  value: number;
  currency: string;
  stage_id: number;
  person_name?: string;
  org_name?: string;
}

interface Pipeline {
  id: number;
  name: string;
  stages: Stage[];
}

function App() {
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  const [selectedPipeline, setSelectedPipeline] = useState<number | null>(null);
  const [stages, setStages] = useState<Stage[]>([]);
  const [dealsByStage, setDealsByStage] = useState<Record<number, Deal[]>>({});
  const [draggedDeal, setDraggedDeal] = useState<Deal | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  const loadPipelines = async () => {
    try {
      const response = await fetch('/mcp/pipedrive_pipelines_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({})
      });
      const data = await response.json();
      const pipelinesData = data.data || [];
      setPipelines(pipelinesData);
      if (pipelinesData.length > 0) {
        setSelectedPipeline(pipelinesData[0].id);
      }
    } catch (error) {
      console.error('Failed to load pipelines:', error);
    }
  };

  const loadStages = async () => {
    try {
      const response = await fetch('/mcp/pipedrive_stages_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pipeline_id: selectedPipeline })
      });
      const data = await response.json();
      const stagesData = (data.data || []).sort((a: Stage, b: Stage) => a.order_nr - b.order_nr);
      setStages(stagesData);
    } catch (error) {
      console.error('Failed to load stages:', error);
    }
  };

  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: 'open', limit: 500 })
      });
      const data = await response.json();
      const dealsData = data.data || [];
      
      // Group deals by stage
      const grouped: Record<number, Deal[]> = {};
      stages.forEach(stage => {
        grouped[stage.id] = dealsData.filter((d: Deal) => d.stage_id === stage.id);
      });
      
      setDealsByStage(grouped);
    } catch (error) {
      console.error('Failed to load deals:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleDragStart = (deal: Deal) => {
    setDraggedDeal(deal);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  const handleDrop = async (stageId: number) => {
    if (!draggedDeal || draggedDeal.stage_id === stageId) {
      setDraggedDeal(null);
      return;
    }

    try {
      // Update deal stage via MCP
      await fetch('/mcp/pipedrive_deal_update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: draggedDeal.id, stage_id: stageId })
      });

      // Update local state
      const newDealsByStage = { ...dealsByStage };
      newDealsByStage[draggedDeal.stage_id] = newDealsByStage[draggedDeal.stage_id].filter(d => d.id !== draggedDeal.id);
      const updatedDeal = { ...draggedDeal, stage_id: stageId };
      newDealsByStage[stageId] = [...(newDealsByStage[stageId] || []), updatedDeal];
      setDealsByStage(newDealsByStage);
    } catch (error) {
      console.error('Failed to update deal:', error);
    } finally {
      setDraggedDeal(null);
    }
  };

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

  const calculateStageValue = (stageId: number) => {
    const deals = dealsByStage[stageId] || [];
    return deals.reduce((sum, deal) => sum + (deal.value || 0), 0);
  };

  if (loading && stages.length === 0) {
    return <div className="loading">Loading pipeline...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>🎯 Pipeline Kanban</h1>
        <div className="header-controls">
          <select
            value={selectedPipeline || ''}
            onChange={(e) => setSelectedPipeline(Number(e.target.value))}
            className="pipeline-select"
          >
            {pipelines.map(pipeline => (
              <option key={pipeline.id} value={pipeline.id}>{pipeline.name}</option>
            ))}
          </select>
          <button onClick={loadDeals} className="refresh-btn">↻ Refresh</button>
        </div>
      </header>

      <div className="kanban-board">
        {stages.map(stage => {
          const stageDeals = dealsByStage[stage.id] || [];
          const stageValue = calculateStageValue(stage.id);

          return (
            <div
              key={stage.id}
              className="kanban-column"
              onDragOver={handleDragOver}
              onDrop={() => handleDrop(stage.id)}
            >
              <div className="column-header">
                <div className="column-title">{stage.name}</div>
                <div className="column-meta">
                  <span className="deal-count">{stageDeals.length} deals</span>
                  <span className="stage-value">{formatCurrency(stageValue)}</span>
                  <span className="probability">{stage.deal_probability}%</span>
                </div>
              </div>

              <div className="column-deals">
                {stageDeals.map(deal => (
                  <div
                    key={deal.id}
                    className="deal-card"
                    draggable
                    onDragStart={() => handleDragStart(deal)}
                  >
                    <div className="deal-title">{deal.title}</div>
                    <div className="deal-value">{formatCurrency(deal.value, deal.currency)}</div>
                    {deal.person_name && (
                      <div className="deal-contact">👤 {deal.person_name}</div>
                    )}
                    {deal.org_name && (
                      <div className="deal-org">🏢 {deal.org_name}</div>
                    )}
                  </div>
                ))}
                {stageDeals.length === 0 && (
                  <div className="empty-column">Drop deals here</div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;
