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

interface Deal {
  id: number;
  title: string;
  value: number;
  currency: string;
  status: string;
  stage_id: number;
  person_id?: { name: string; email: string };
  org_id?: { name: string };
  user_id?: { name: string };
  add_time: string;
  update_time: string;
  expected_close_date?: string;
  probability?: number;
  products_count: number;
  activities_count: number;
  participants_count: number;
  notes_count: number;
}

interface Activity {
  id: number;
  subject: string;
  type: string;
  done: boolean;
  due_date: string;
  note: string;
}

interface Product {
  id: number;
  name: string;
  quantity: number;
  item_price: number;
  sum: number;
}

interface Note {
  id: number;
  content: string;
  add_time: string;
  user: { name: string };
}

const TabButton: React.FC<{ active: boolean; onClick: () => void; children: React.ReactNode }> = 
  ({ active, onClick, children }) => (
    <button 
      onClick={onClick}
      className={`tab-btn ${active ? 'active' : ''}`}
    >
      {children}
    </button>
  );

function App() {
  const [dealId, setDealId] = useState<number>(new URLSearchParams(window.location.search).get('id') ? parseInt(new URLSearchParams(window.location.search).get('id')!) : 1);
  const [deal, setDeal] = useState<Deal | null>(null);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [notes, setNotes] = useState<Note[]>([]);
  const [activeTab, setActiveTab] = useState<'overview' | 'activities' | 'products' | 'timeline'>('overview');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadDeal();
  }, [dealId]);

  const loadDeal = async () => {
    setLoading(true);
    try {
      const dealResponse = await fetch('/mcp/pipedrive_deal_get', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: dealId })
      });
      const dealData = await dealResponse.json();
      setDeal(dealData.data);

      // Load activities
      const activitiesResponse = await fetch('/mcp/pipedrive_activities_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ deal_id: dealId, limit: 50 })
      });
      const activitiesData = await activitiesResponse.json();
      setActivities(activitiesData.data || []);

      // Load products
      const productsResponse = await fetch('/mcp/pipedrive_deal_products_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: dealId })
      });
      const productsData = await productsResponse.json();
      setProducts(productsData.data || []);

      // Load notes (mock for now)
      setNotes([]);
    } catch (error) {
      console.error('Failed to load deal:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  };

  if (loading || !deal) {
    return <div className="loading">Loading deal details...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <div>
          <h1>{deal.title}</h1>
          <div className="header-meta">
            <span className={`status-badge ${deal.status}`}>{deal.status}</span>
            <span className="value">{formatCurrency(deal.value, deal.currency)}</span>
            {deal.probability && <span className="probability">{deal.probability}% probability</span>}
          </div>
        </div>
        <button onClick={loadDeal} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="info-cards">
        <div className="info-card">
          <div className="info-label">Person</div>
          <div className="info-value">{deal.person_id?.name || 'N/A'}</div>
          {deal.person_id?.email && <div className="info-sub">{deal.person_id.email}</div>}
        </div>
        <div className="info-card">
          <div className="info-label">Organization</div>
          <div className="info-value">{deal.org_id?.name || 'N/A'}</div>
        </div>
        <div className="info-card">
          <div className="info-label">Owner</div>
          <div className="info-value">{deal.user_id?.name || 'N/A'}</div>
        </div>
        <div className="info-card">
          <div className="info-label">Expected Close</div>
          <div className="info-value">{deal.expected_close_date ? formatDate(deal.expected_close_date) : 'N/A'}</div>
        </div>
      </div>

      <div className="tabs">
        <TabButton active={activeTab === 'overview'} onClick={() => setActiveTab('overview')}>
          📋 Overview
        </TabButton>
        <TabButton active={activeTab === 'activities'} onClick={() => setActiveTab('activities')}>
          📅 Activities ({activities.length})
        </TabButton>
        <TabButton active={activeTab === 'products'} onClick={() => setActiveTab('products')}>
          📦 Products ({products.length})
        </TabButton>
        <TabButton active={activeTab === 'timeline'} onClick={() => setActiveTab('timeline')}>
          🕐 Timeline
        </TabButton>
      </div>

      <div className="tab-content">
        {activeTab === 'overview' && (
          <div className="overview">
            <div className="overview-section">
              <h3>Deal Information</h3>
              <div className="info-row">
                <span>Created:</span>
                <span>{formatDate(deal.add_time)}</span>
              </div>
              <div className="info-row">
                <span>Last Updated:</span>
                <span>{formatDate(deal.update_time)}</span>
              </div>
              <div className="info-row">
                <span>Activities:</span>
                <span>{deal.activities_count}</span>
              </div>
              <div className="info-row">
                <span>Participants:</span>
                <span>{deal.participants_count}</span>
              </div>
              <div className="info-row">
                <span>Notes:</span>
                <span>{deal.notes_count}</span>
              </div>
            </div>
          </div>
        )}

        {activeTab === 'activities' && (
          <div className="activities-list">
            {activities.length === 0 ? (
              <div className="empty-state">No activities found</div>
            ) : (
              activities.map(activity => (
                <div key={activity.id} className={`activity-item ${activity.done ? 'done' : 'pending'}`}>
                  <div className="activity-header">
                    <span className={`activity-type ${activity.type}`}>{activity.type}</span>
                    <span className="activity-date">{formatDate(activity.due_date)}</span>
                  </div>
                  <div className="activity-subject">{activity.subject}</div>
                  {activity.note && <div className="activity-note">{activity.note}</div>}
                  {activity.done && <div className="activity-status">✓ Completed</div>}
                </div>
              ))
            )}
          </div>
        )}

        {activeTab === 'products' && (
          <div className="products-list">
            {products.length === 0 ? (
              <div className="empty-state">No products attached</div>
            ) : (
              <table className="products-table">
                <thead>
                  <tr>
                    <th>Product</th>
                    <th>Quantity</th>
                    <th>Unit Price</th>
                    <th>Total</th>
                  </tr>
                </thead>
                <tbody>
                  {products.map(product => (
                    <tr key={product.id}>
                      <td>{product.name}</td>
                      <td>{product.quantity}</td>
                      <td>{formatCurrency(product.item_price)}</td>
                      <td className="total">{formatCurrency(product.sum)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        )}

        {activeTab === 'timeline' && (
          <div className="timeline">
            <div className="timeline-item">
              <div className="timeline-dot"></div>
              <div className="timeline-content">
                <div className="timeline-date">{formatDate(deal.add_time)}</div>
                <div className="timeline-event">Deal created</div>
              </div>
            </div>
            <div className="timeline-item">
              <div className="timeline-dot"></div>
              <div className="timeline-content">
                <div className="timeline-date">{formatDate(deal.update_time)}</div>
                <div className="timeline-event">Last updated</div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
