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

function App() {
  const [orgs, setOrgs] = useState<any[]>([]);
  const [filtered, setFiltered] = useState<any[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    setFiltered(orgs.filter(o => o.name.toLowerCase().includes(search.toLowerCase())));
  }, [search, orgs]);

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

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

  return (
    <div className="app">
      <header className="header">
        <h1>🏢 Organization Directory</h1>
        <button onClick={loadOrgs} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="controls">
        <input
          type="text"
          placeholder="Search organizations..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="search-input"
        />
        <div className="count-badge">{filtered.length} organizations</div>
      </div>

      <div className="grid">
        {filtered.map(org => (
          <div key={org.id} className="org-card">
            <div className="org-name">{org.name}</div>
            {org.address && <div className="org-address">📍 {org.address}</div>}
            <div className="org-stats">
              <span>👥 {org.people_count || 0} people</span>
              <span>🔄 {org.open_deals_count || 0} open</span>
              <span>✅ {org.won_deals_count || 0} won</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
