const { useState, useEffect } = React;

function ContactsList({ onSelectContact }) {
  const [contacts, setContacts] = useState([]);
  const [filteredContacts, setFilteredContacts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [tierFilter, setTierFilter] = useState('');
  const [warmthFilter, setWarmthFilter] = useState('');
  const [searchTerm, setSearchTerm] = useState('');

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

  useEffect(() => {
    filterContacts();
  }, [contacts, tierFilter, warmthFilter, searchTerm]);

  const loadContacts = async () => {
    try {
      const res = await fetch('/api/contacts');
      const data = await res.json();
      setContacts(data);
      setLoading(false);
    } catch (err) {
      console.error('Error loading contacts:', err);
      setLoading(false);
    }
  };

  const filterContacts = () => {
    let filtered = contacts;

    if (tierFilter) {
      filtered = filtered.filter(c => c.tier === tierFilter);
    }

    if (warmthFilter) {
      filtered = filtered.filter(c => c.warmth_status === warmthFilter);
    }

    if (searchTerm) {
      filtered = filtered.filter(c =>
        c.full_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        c.organisation?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    setFilteredContacts(filtered);
  };

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

  return (
    <div>
      <div className="page-header">
        <h1>Contacts ({filteredContacts.length})</h1>
      </div>

      {/* Filters */}
      <div className="card">
        <input
          type="text"
          placeholder="Search name or organisation..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ width: '100%', padding: '8px', marginBottom: '10px', border: '1px solid #ddd', borderRadius: '4px' }}
        />
        <div style={{ display: 'flex', gap: '10px' }}>
          <select value={tierFilter} onChange={(e) => setTierFilter(e.target.value)} style={{ flex: 1 }}>
            <option value="">All Tiers</option>
            <option value="VVIP">VVIP</option>
            <option value="VIP">VIP</option>
            <option value="CIP">CIP</option>
            <option value="Friend">Friend</option>
            <option value="Prospect">Prospect</option>
            <option value="Network">Network</option>
            <option value="Dormant">Dormant</option>
          </select>
          <select value={warmthFilter} onChange={(e) => setWarmthFilter(e.target.value)} style={{ flex: 1 }}>
            <option value="">All Warmth</option>
            <option value="warm">Warm</option>
            <option value="cooling">Cooling</option>
            <option value="cold">Cold</option>
          </select>
        </div>
      </div>

      {/* Contacts List */}
      <div className="card">
        {filteredContacts.length === 0 ? (
          <p style={{ color: '#999' }}>No contacts found</p>
        ) : (
          filteredContacts.map(contact => (
            <div
              key={contact.id}
              className="contact-row"
              onClick={() => onSelectContact(contact.id)}
              style={{ cursor: 'pointer' }}
            >
              <div className="contact-info">
                <div className="contact-name">{contact.full_name}</div>
                <div className="contact-subtitle">
                  {contact.current_title && `${contact.current_title} at `}
                  {contact.organisation} • {contact.location}
                </div>
                <div className="contact-subtitle" style={{ marginTop: '4px' }}>
                  Last contacted: {contact.last_contacted ? new Date(contact.last_contacted).toLocaleDateString() : 'Never'}
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <span className={`tier-badge ${contact.tier.toLowerCase()}`}>{contact.tier}</span>
                <div style={{ fontSize: '11px', color: '#999', marginTop: '5px' }}>
                  {contact.warmth_status}
                </div>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

