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

interface ContactList {
  id: string;
  name: string;
  type: 'static' | 'active';
  memberCount: number;
  createdDate: string;
  lastUpdated: string;
}

const mockLists: ContactList[] = [
  { id: '1', name: 'Newsletter Subscribers', type: 'active', memberCount: 5420, createdDate: '2024-01-01', lastUpdated: '2024-02-13' },
  { id: '2', name: 'Enterprise Leads', type: 'static', memberCount: 234, createdDate: '2024-01-15', lastUpdated: '2024-02-10' },
  { id: '3', name: 'Product Users', type: 'active', memberCount: 8750, createdDate: '2024-01-20', lastUpdated: '2024-02-13' },
  { id: '4', name: 'Webinar Attendees', type: 'static', memberCount: 1450, createdDate: '2024-02-01', lastUpdated: '2024-02-11' },
  { id: '5', name: 'Trial Users', type: 'active', memberCount: 920, createdDate: '2024-02-05', lastUpdated: '2024-02-13' },
];

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 [typeFilter, setTypeFilter] = useState<string>('all');
  const [selectedList, setSelectedList] = useState<ContactList | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredLists = useMemo(() => {
    let filtered = mockLists;
    if (debouncedSearch) {
      const term = debouncedSearch.toLowerCase();
      filtered = filtered.filter(l => l.name.toLowerCase().includes(term));
    }
    if (typeFilter !== 'all') {
      filtered = filtered.filter(l => l.type === typeFilter);
    }
    return filtered;
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => ({
    total: mockLists.length,
    static: mockLists.filter(l => l.type === 'static').length,
    active: mockLists.filter(l => l.type === 'active').length,
    totalMembers: mockLists.reduce((sum, l) => sum + l.memberCount, 0),
  }), []);

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

  const handleSelectList = (list: ContactList) => {
    setSelectedList(list);
    addToast(`Viewing ${list.name}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>List Manager</h1>
        <p>Contact lists (static + active) with member counts</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Lists</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Static Lists</div>
          <div className="stat-value">{stats.static}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Active Lists</div>
          <div className="stat-value">{stats.active}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Members</div>
          <div className="stat-value">{(stats.totalMembers / 1000).toFixed(1)}K</div>
        </div>
      </div>

      <div className="filter-bar">
        <input
          type="text"
          placeholder="Search lists..."
          value={searchTerm}
          onChange={handleSearch}
          className="search-input"
        />
        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="filter-select"
        >
          <option value="all">All Types</option>
          <option value="static">Static</option>
          <option value="active">Active</option>
        </select>
        {isPending && <span className="search-loading">Filtering...</span>}
      </div>

      {filteredLists.length === 0 ? (
        <div className="empty-state">
          <h3>No lists found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>Type</th>
                <th>Members</th>
                <th>Created</th>
                <th>Last Updated</th>
              </tr>
            </thead>
            <tbody>
              {filteredLists.map(list => (
                <tr
                  key={list.id}
                  onClick={() => handleSelectList(list)}
                  className={selectedList?.id === list.id ? 'selected' : ''}
                >
                  <td>{list.name}</td>
                  <td>
                    <span className={`status-badge status-${list.type}`}>
                      {list.type}
                    </span>
                  </td>
                  <td>{list.memberCount.toLocaleString()}</td>
                  <td>{list.createdDate}</td>
                  <td>{list.lastUpdated}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedList && (
        <div className="detail-panel">
          <h3>List Details</h3>
          <div className="detail-grid">
            <div><strong>Name:</strong> {selectedList.name}</div>
            <div><strong>Type:</strong> {selectedList.type}</div>
            <div><strong>Members:</strong> {selectedList.memberCount.toLocaleString()}</div>
            <div><strong>Created:</strong> {selectedList.createdDate}</div>
            <div><strong>Last Updated:</strong> {selectedList.lastUpdated}</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;
