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

interface Contact {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  company: string;
  lastActivity: string;
  status: 'active' | 'inactive';
}

const mockContacts: Contact[] = [
  { id: '1', firstName: 'John', lastName: 'Doe', email: 'john@example.com', phone: '555-0101', company: 'Acme Corp', lastActivity: '2024-02-10', status: 'active' },
  { id: '2', firstName: 'Jane', lastName: 'Smith', email: 'jane@example.com', phone: '555-0102', company: 'TechCo', lastActivity: '2024-02-12', status: 'active' },
  { id: '3', firstName: 'Bob', lastName: 'Wilson', email: 'bob@example.com', phone: '555-0103', company: 'StartupXYZ', lastActivity: '2024-01-15', status: 'inactive' },
  { id: '4', firstName: 'Alice', lastName: 'Johnson', email: 'alice@example.com', phone: '555-0104', company: 'BigCorp', lastActivity: '2024-02-13', status: 'active' },
  { id: '5', firstName: 'Charlie', lastName: 'Brown', email: 'charlie@example.com', phone: '555-0105', company: 'MediumBiz', lastActivity: '2024-02-11', status: 'active' },
];

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;
};

interface Toast {
  id: number;
  message: string;
  type: 'success' | 'error' | 'info';
}

const useToast = () => {
  const [toasts, setToasts] = useState<Toast[]>([]);
  const addToast = useCallback((message: string, type: Toast['type'] = 'info') => {
    const id = Date.now();
    setToasts(prev => [...prev, { id, message, type }]);
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  }, []);
  return { toasts, addToast };
};

const App = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedContact, setSelectedContact] = useState<Contact | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredContacts = useMemo(() => {
    if (!debouncedSearch) return mockContacts;
    const term = debouncedSearch.toLowerCase();
    return mockContacts.filter(c =>
      c.firstName.toLowerCase().includes(term) ||
      c.lastName.toLowerCase().includes(term) ||
      c.email.toLowerCase().includes(term) ||
      c.company.toLowerCase().includes(term)
    );
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockContacts.length,
    active: mockContacts.filter(c => c.status === 'active').length,
    inactive: mockContacts.filter(c => c.status === 'inactive').length,
    thisWeek: mockContacts.filter(c => new Date(c.lastActivity) > new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)).length,
  }), []);

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

  const handleSelectContact = (contact: Contact) => {
    setSelectedContact(contact);
    addToast(`Viewing ${contact.firstName} ${contact.lastName}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Contact Manager</h1>
        <p>Manage and track all your HubSpot contacts</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">Active</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Inactive</div>
          <div className="stat-value">{stats.inactive}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active This Week</div>
          <div className="stat-value">{stats.thisWeek}</div>
        </div>
      </div>

      <div className="search-bar">
        <input
          type="text"
          placeholder="Search contacts..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        {isPending && <span className="search-loading">Searching...</span>}
      </div>

      {filteredContacts.length === 0 ? (
        <div className="empty-state">
          <h3>No contacts found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Company</th>
                <th>Last Activity</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredContacts.map(contact => (
                <tr
                  key={contact.id}
                  onClick={() => handleSelectContact(contact)}
                  className={selectedContact?.id === contact.id ? 'selected' : ''}
                >
                  <td>{contact.firstName} {contact.lastName}</td>
                  <td>{contact.email}</td>
                  <td>{contact.phone}</td>
                  <td>{contact.company}</td>
                  <td>{contact.lastActivity}</td>
                  <td>
                    <span className={`status-badge status-${contact.status}`}>
                      {contact.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedContact && (
        <div className="detail-panel">
          <h3>Contact Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedContact.firstName} {selectedContact.lastName}</div>
            <div><strong>Email:</strong> {selectedContact.email}</div>
            <div><strong>Phone:</strong> {selectedContact.phone}</div>
            <div><strong>Company:</strong> {selectedContact.company}</div>
            <div><strong>Last Activity:</strong> {selectedContact.lastActivity}</div>
            <div><strong>Status:</strong> {selectedContact.status}</div>
          </div>
        </div>
      )}

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

export default App;
