import React, { useState } from 'react';

function App() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<any>({ deals: [], persons: [], organizations: [] });
  const [loading, setLoading] = useState(false);

  const handleSearch = async () => {
    if (!query.trim()) return;
    
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_search', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ term: query, item_types: 'deal,person,organization' })
      });
      const data = await response.json();
      
      const grouped = {
        deals: (data.data || []).filter((r: any) => r.type === 'deal'),
        persons: (data.data || []).filter((r: any) => r.type === 'person'),
        organizations: (data.data || []).filter((r: any) => r.type === 'organization')
      };
      
      setResults(grouped);
    } catch (error) {
      console.error('Search failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const totalResults = results.deals.length + results.persons.length + results.organizations.length;

  return (
    <div className="app">
      <header className="header">
        <h1>🔍 Universal Search</h1>
      </header>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search deals, contacts, organizations..."
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
          className="search-input"
        />
        <button onClick={handleSearch} className="search-btn" disabled={loading}>
          {loading ? 'Searching...' : 'Search'}
        </button>
      </div>

      {totalResults > 0 && (
        <div className="results-summary">
          Found {totalResults} results: {results.deals.length} deals, {results.persons.length} contacts, {results.organizations.length} organizations
        </div>
      )}

      <div className="results-container">
        {results.deals.length > 0 && (
          <div className="results-section">
            <h2>💼 Deals ({results.deals.length})</h2>
            <div className="results-list">
              {results.deals.map((item: any) => (
                <div key={item.id} className="result-item">
                  <div className="result-title">{item.title}</div>
                  {item.custom_fields && <div className="result-meta">{item.custom_fields}</div>}
                </div>
              ))}
            </div>
          </div>
        )}

        {results.persons.length > 0 && (
          <div className="results-section">
            <h2>👤 Contacts ({results.persons.length})</h2>
            <div className="results-list">
              {results.persons.map((item: any) => (
                <div key={item.id} className="result-item">
                  <div className="result-title">{item.title}</div>
                  {item.custom_fields && <div className="result-meta">{item.custom_fields}</div>}
                </div>
              ))}
            </div>
          </div>
        )}

        {results.organizations.length > 0 && (
          <div className="results-section">
            <h2>🏢 Organizations ({results.organizations.length})</h2>
            <div className="results-list">
              {results.organizations.map((item: any) => (
                <div key={item.id} className="result-item">
                  <div className="result-title">{item.title}</div>
                  {item.custom_fields && <div className="result-meta">{item.custom_fields}</div>}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
