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

interface Contact {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  title: string;
  accountName: string;
  accountId: string;
}

const useDebounce = <T,>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);
  return debouncedValue;
};

const useToast = () => {
  const [toasts, setToasts] = useState<Array<{ id: number; message: string }>>([]);
  const show = (message: string) => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  };
  return { toasts, show };
};

const mockContacts: Contact[] = [
  { id: 'c001', firstName: 'Sarah', lastName: 'Connor', email: 'sconnor@acme.com', phone: '555-0101', title: 'VP of Sales', accountName: 'Acme Corporation', accountId: '001' },
  { id: 'c002', firstName: 'Michael', lastName: 'Scott', email: 'mscott@global.com', phone: '555-0102', title: 'Regional Manager', accountName: 'Global Industries', accountId: '002' },
  { id: 'c003', firstName: 'Pam', lastName: 'Beesly', email: 'pbeesly@global.com', phone: '555-0103', title: 'Office Administrator', accountName: 'Global Industries', accountId: '002' },
  { id: 'c004', firstName: 'Jim', lastName: 'Halpert', email: 'jhalpert@tech.com', phone: '555-0104', title: 'Sales Rep', accountName: 'Tech Innovations Inc', accountId: '003' },
  { id: 'c005', firstName: 'Dwight', lastName: 'Schrute', email: 'dschrute@premier.com', phone: '555-0105', title: 'Assistant Regional Manager', accountName: 'Premier Services LLC', accountId: '004' },
  { id: 'c006', firstName: 'Angela', lastName: 'Martin', email: 'amartin@enterprise.com', phone: '555-0106', title: 'Head of Accounting', accountName: 'Enterprise Solutions', accountId: '005' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedContact, setSelectedContact] = useState<Contact | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredContacts = useMemo(() => {
    return mockContacts.filter(contact =>
      `${contact.firstName} ${contact.lastName}`.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      contact.email.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
      contact.accountName.toLowerCase().includes(debouncedSearch.toLowerCase())
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockContacts.length,
    accounts: new Set(mockContacts.map(c => c.accountId)).size,
    withPhone: mockContacts.filter(c => c.phone).length,
  }), []);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    startTransition(() => {
      setSearchQuery(e.target.value);
    });
  };

  const handleViewContact = (contact: Contact) => {
    setSelectedContact(contact);
    show(`Viewing ${contact.firstName} ${contact.lastName}`);
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Contact Directory</h1>
        <p>Search contacts, view account associations</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Contacts</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Associated Accounts</div>
          <div className="stat-value">{stats.accounts}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">With Phone</div>
          <div className="stat-value">{stats.withPhone}</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search by name, email, or account..."
          value={searchQuery}
          onChange={handleSearch}
          className="search-input"
        />
      </div>

      {filteredContacts.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">👥</div>
          <h3>No contacts found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Title</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Account</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredContacts.map(contact => (
                <tr key={contact.id}>
                  <td><strong>{contact.firstName} {contact.lastName}</strong></td>
                  <td>{contact.title}</td>
                  <td>{contact.email}</td>
                  <td>{contact.phone}</td>
                  <td>{contact.accountName}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewContact(contact)}
                    >
                      View
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedContact && (
        <div className="modal-overlay" onClick={() => setSelectedContact(null)}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <h2>{selectedContact.firstName} {selectedContact.lastName}</h2>
            <div className="detail-grid">
              <div><strong>Title:</strong> {selectedContact.title}</div>
              <div><strong>Email:</strong> {selectedContact.email}</div>
              <div><strong>Phone:</strong> {selectedContact.phone}</div>
              <div><strong>Account:</strong> {selectedContact.accountName}</div>
            </div>
            <button className="btn-secondary" onClick={() => setSelectedContact(null)}>Close</button>
          </div>
        </div>
      )}

      <div className="toast-container">
        {toasts.map(toast => (
          <div key={toast.id} className="toast">{toast.message}</div>
        ))}
      </div>
    </div>
  );
};

export default App;
