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

interface Person {
  id: number;
  name: string;
  email: string[];
  phone: string[];
  org_name?: string;
  open_deals_count: number;
  won_deals_count: number;
}

function App() {
  const [persons, setPersons] = useState<Person[]>([]);
  const [filtered, setFiltered] = useState<Person[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    setFiltered(persons.filter(p => 
      p.name.toLowerCase().includes(search.toLowerCase()) ||
      p.org_name?.toLowerCase().includes(search.toLowerCase())
    ));
  }, [search, persons]);

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

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

  return (
    <div className="app">
      <header className="header">
        <h1>👥 Contact Directory</h1>
        <button onClick={loadPersons} className="refresh-btn">↻ Refresh</button>
      </header>

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

      <div className="grid">
        {filtered.map(person => (
          <div key={person.id} className="person-card">
            <div className="person-name">{person.name}</div>
            {person.org_name && <div className="person-org">🏢 {person.org_name}</div>}
            {person.email[0] && <div className="person-email">📧 {person.email[0]}</div>}
            {person.phone[0] && <div className="person-phone">📞 {person.phone[0]}</div>}
            <div className="person-stats">
              <span>🔄 {person.open_deals_count} open</span>
              <span>✅ {person.won_deals_count} won</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
