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

function App() {
  const [leads, setLeads] = useState<any[]>([]);
  const [filtered, setFiltered] = useState<any[]>([]);
  const [labelFilter, setLabelFilter] = useState<string>('all');
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    if (labelFilter === 'all') setFiltered(leads);
    else setFiltered(leads.filter(l => l.label_ids?.includes(labelFilter)));
  }, [labelFilter, leads]);

  const loadLeads = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_leads_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ limit: 500 })
      });
      const data = await response.json();
      setLeads(data.data || []);
    } catch (error) {
      console.error('Failed to load leads:', error);
    } finally {
      setLoading(false);
    }
  };

  const convertToDeal = async (leadId: string) => {
    try {
      await fetch('/mcp/pipedrive_lead_convert', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: leadId })
      });
      loadLeads();
    } catch (error) {
      console.error('Failed to convert lead:', error);
    }
  };

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

  return (
    <div className="app">
      <header className="header">
        <h1>📬 Lead Inbox</h1>
        <button onClick={loadLeads} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="filters">
        <button className={labelFilter === 'all' ? 'active' : ''} onClick={() => setLabelFilter('all')}>All ({leads.length})</button>
        <button className={labelFilter === 'hot' ? 'active' : ''} onClick={() => setLabelFilter('hot')}>Hot</button>
        <button className={labelFilter === 'warm' ? 'active' : ''} onClick={() => setLabelFilter('warm')}>Warm</button>
        <button className={labelFilter === 'cold' ? 'active' : ''} onClick={() => setLabelFilter('cold')}>Cold</button>
      </div>

      <div className="leads-list">
        {filtered.map(lead => (
          <div key={lead.id} className="lead-card">
            <div className="lead-header">
              <div className="lead-title">{lead.title}</div>
              <div className="lead-value">{lead.value ? `$${lead.value}` : '—'}</div>
            </div>
            {lead.person_name && <div className="lead-contact">👤 {lead.person_name}</div>}
            {lead.organization_name && <div className="lead-org">🏢 {lead.organization_name}</div>}
            <div className="lead-actions">
              <button onClick={() => convertToDeal(lead.id)} className="convert-btn">Convert to Deal</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
