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

interface Engagement {
  id: string;
  type: 'call' | 'note' | 'meeting' | 'task' | 'email';
  contact: string;
  subject: string;
  timestamp: string;
  owner: string;
}

const mockEngagements: Engagement[] = [
  { id: '1', type: 'call', contact: 'John Doe', subject: 'Discovery call', timestamp: '2024-02-13 14:30', owner: 'Sarah Johnson' },
  { id: '2', type: 'note', contact: 'Jane Smith', subject: 'Follow-up notes', timestamp: '2024-02-13 13:15', owner: 'Mike Chen' },
  { id: '3', type: 'meeting', contact: 'Bob Wilson', subject: 'Product demo', timestamp: '2024-02-13 11:00', owner: 'Sarah Johnson' },
  { id: '4', type: 'task', contact: 'Alice Johnson', subject: 'Send proposal', timestamp: '2024-02-13 10:00', owner: 'Tom Brown' },
  { id: '5', type: 'email', contact: 'Charlie Brown', subject: 'Pricing inquiry', timestamp: '2024-02-13 09:30', owner: 'Sarah Johnson' },
  { id: '6', type: 'call', contact: 'David Lee', subject: 'Support call', timestamp: '2024-02-12 16:45', owner: 'Mike Chen' },
  { id: '7', type: 'meeting', contact: 'Emma Davis', subject: 'Contract review', timestamp: '2024-02-12 15:00', owner: 'Tom Brown' },
];

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 [selectedEngagement, setSelectedEngagement] = useState<Engagement | null>(null);
  const [isPending, startTransition] = useTransition();
  const { toasts, addToast } = useToast();

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredEngagements = useMemo(() => {
    let filtered = mockEngagements;
    
    if (debouncedSearch) {
      const term = debouncedSearch.toLowerCase();
      filtered = filtered.filter(e =>
        e.contact.toLowerCase().includes(term) ||
        e.subject.toLowerCase().includes(term) ||
        e.owner.toLowerCase().includes(term)
      );
    }
    
    if (typeFilter !== 'all') {
      filtered = filtered.filter(e => e.type === typeFilter);
    }
    
    return filtered;
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => ({
    total: mockEngagements.length,
    calls: mockEngagements.filter(e => e.type === 'call').length,
    meetings: mockEngagements.filter(e => e.type === 'meeting').length,
    tasks: mockEngagements.filter(e => e.type === 'task').length,
  }), []);

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

  const handleSelectEngagement = (engagement: Engagement) => {
    setSelectedEngagement(engagement);
    addToast(`Viewing ${engagement.type}: ${engagement.subject}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Engagement Feed</h1>
        <p>Activity timeline: calls, notes, meetings, and tasks</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Activities</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Calls</div>
          <div className="stat-value">{stats.calls}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Meetings</div>
          <div className="stat-value">{stats.meetings}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Tasks</div>
          <div className="stat-value">{stats.tasks}</div>
        </div>
      </div>

      <div className="filter-bar">
        <input
          type="text"
          placeholder="Search engagements..."
          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="call">Calls</option>
          <option value="note">Notes</option>
          <option value="meeting">Meetings</option>
          <option value="task">Tasks</option>
          <option value="email">Emails</option>
        </select>
        {isPending && <span className="search-loading">Filtering...</span>}
      </div>

      {filteredEngagements.length === 0 ? (
        <div className="empty-state">
          <h3>No engagements found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="timeline">
          {filteredEngagements.map(engagement => (
            <div
              key={engagement.id}
              className={`timeline-item ${selectedEngagement?.id === engagement.id ? 'selected' : ''}`}
              onClick={() => handleSelectEngagement(engagement)}
            >
              <div className={`timeline-icon timeline-icon-${engagement.type}`}>
                {engagement.type.charAt(0).toUpperCase()}
              </div>
              <div className="timeline-content">
                <div className="timeline-header">
                  <span className="timeline-type">{engagement.type}</span>
                  <span className="timeline-time">{engagement.timestamp}</span>
                </div>
                <div className="timeline-subject">{engagement.subject}</div>
                <div className="timeline-meta">
                  <span>Contact: {engagement.contact}</span>
                  <span>Owner: {engagement.owner}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {selectedEngagement && (
        <div className="detail-panel">
          <h3>Engagement Details</h3>
          <div className="detail-grid">
            <div><strong>Type:</strong> {selectedEngagement.type}</div>
            <div><strong>Subject:</strong> {selectedEngagement.subject}</div>
            <div><strong>Contact:</strong> {selectedEngagement.contact}</div>
            <div><strong>Owner:</strong> {selectedEngagement.owner}</div>
            <div><strong>Timestamp:</strong> {selectedEngagement.timestamp}</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;
