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

interface Event {
  id: string;
  subject: string;
  startDateTime: string;
  endDateTime: string;
  location: string;
  attendees: string[];
  type: 'Meeting' | 'Call' | 'Webinar' | 'Conference';
  relatedTo: 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 mockEvents: Event[] = [
  { id: 'e001', subject: 'Sales Team Sync', startDateTime: '2025-02-14T10:00', endDateTime: '2025-02-14T11:00', location: 'Zoom', attendees: ['Jane Smith', 'John Doe'], type: 'Meeting', relatedTo: 'Internal' },
  { id: 'e002', subject: 'Product Demo with Acme', startDateTime: '2025-02-15T14:00', endDateTime: '2025-02-15T15:00', location: 'Client Office', attendees: ['Alice Johnson', 'Sarah Connor'], type: 'Meeting', relatedTo: 'Acme Corporation' },
  { id: 'e003', subject: 'Quarterly Business Review', startDateTime: '2025-02-16T09:00', endDateTime: '2025-02-16T12:00', location: 'Conference Room A', attendees: ['Jane Smith', 'Bob Wilson', 'John Doe'], type: 'Conference', relatedTo: 'Internal' },
  { id: 'e004', subject: 'Follow-up Call', startDateTime: '2025-02-17T15:00', endDateTime: '2025-02-17T15:30', location: 'Phone', attendees: ['Alice Johnson'], type: 'Call', relatedTo: 'Global Industries' },
  { id: 'e005', subject: 'Product Training Webinar', startDateTime: '2025-02-18T13:00', endDateTime: '2025-02-18T14:30', location: 'Webinar Platform', attendees: ['Jane Smith', 'John Doe', 'Alice Johnson'], type: 'Webinar', relatedTo: 'Internal' },
];

const App: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('All');
  const [isPending, startTransition] = useTransition();
  const { toasts, show } = useToast();
  const debouncedSearch = useDebounce(searchQuery, 300);

  const filteredEvents = useMemo(() => {
    return mockEvents.filter(event => {
      const matchesSearch = event.subject.toLowerCase().includes(debouncedSearch.toLowerCase()) ||
                           event.relatedTo.toLowerCase().includes(debouncedSearch.toLowerCase());
      const matchesType = typeFilter === 'All' || event.type === typeFilter;
      return matchesSearch && matchesType;
    }).sort((a, b) => new Date(a.startDateTime).getTime() - new Date(b.startDateTime).getTime());
  }, [debouncedSearch, typeFilter]);

  const stats = useMemo(() => ({
    total: mockEvents.length,
    meetings: mockEvents.filter(e => e.type === 'Meeting').length,
    calls: mockEvents.filter(e => e.type === 'Call').length,
    upcoming: mockEvents.filter(e => new Date(e.startDateTime) > new Date()).length,
  }), []);

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

  const handleViewEvent = (event: Event) => {
    show(`Viewing ${event.subject}`);
  };

  const formatDateTime = (dateTime: string) => {
    const date = new Date(dateTime);
    return date.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
  };

  return (
    <div className="app-container">
      <header className="app-header">
        <h1>Event Calendar</h1>
        <p>Events by date range and upcoming schedule</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Events</div>
          <div className="stat-value">{stats.total}</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">Calls</div>
          <div className="stat-value">{stats.calls}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Upcoming</div>
          <div className="stat-value">{stats.upcoming}</div>
        </div>
      </div>

      <div className="controls">
        <input
          type="text"
          placeholder="Search events by subject or related to..."
          value={searchQuery}
          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="Meeting">Meeting</option>
          <option value="Call">Call</option>
          <option value="Webinar">Webinar</option>
          <option value="Conference">Conference</option>
        </select>
      </div>

      {filteredEvents.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">📅</div>
          <h3>No events found</h3>
          <p>Try adjusting your filters</p>
        </div>
      ) : (
        <div className="data-grid">
          <table>
            <thead>
              <tr>
                <th>Subject</th>
                <th>Type</th>
                <th>Start</th>
                <th>End</th>
                <th>Location</th>
                <th>Attendees</th>
                <th>Related To</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody className={isPending ? 'loading' : ''}>
              {filteredEvents.map(event => (
                <tr key={event.id}>
                  <td><strong>{event.subject}</strong></td>
                  <td><span className={`type-badge type-${event.type.toLowerCase()}`}>{event.type}</span></td>
                  <td>{formatDateTime(event.startDateTime)}</td>
                  <td>{formatDateTime(event.endDateTime)}</td>
                  <td>{event.location}</td>
                  <td>{event.attendees.length} attendee{event.attendees.length !== 1 ? 's' : ''}</td>
                  <td>{event.relatedTo}</td>
                  <td>
                    <button 
                      className="btn-primary"
                      onClick={() => handleViewEvent(event)}
                    >
                      View
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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

export default App;
