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

interface Meeting {
  id: string;
  title: string;
  type: 'sales-call' | 'demo' | 'consultation' | 'follow-up';
  attendees: string[];
  scheduledDate: string;
  duration: number;
  status: 'scheduled' | 'completed' | 'cancelled';
  meetingLink: string;
}

const mockMeetings: Meeting[] = [
  { id: '1', title: 'Product Demo', type: 'demo', attendees: ['John Doe', 'Sarah Johnson'], scheduledDate: '2024-02-14 10:00', duration: 60, status: 'scheduled', meetingLink: 'meet.hubspot.com/demo123' },
  { id: '2', title: 'Discovery Call', type: 'sales-call', attendees: ['Jane Smith', 'Mike Chen'], scheduledDate: '2024-02-14 14:00', duration: 30, status: 'scheduled', meetingLink: 'meet.hubspot.com/disc456' },
  { id: '3', title: 'Technical Consultation', type: 'consultation', attendees: ['Bob Wilson', 'Tom Brown'], scheduledDate: '2024-02-13 11:00', duration: 45, status: 'completed', meetingLink: 'meet.hubspot.com/tech789' },
  { id: '4', title: 'Follow-up Discussion', type: 'follow-up', attendees: ['Alice Johnson', 'Sarah Johnson'], scheduledDate: '2024-02-15 15:00', duration: 30, status: 'scheduled', meetingLink: 'meet.hubspot.com/fup012' },
  { id: '5', title: 'Quarterly Review', type: 'consultation', attendees: ['Charlie Brown', 'Mike Chen'], scheduledDate: '2024-02-12 13:00', duration: 90, status: 'completed', meetingLink: 'meet.hubspot.com/qtr345' },
];

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

  const debouncedSearch = useDebounce(searchTerm, 300);

  const filteredMeetings = useMemo(() => {
    if (!debouncedSearch) return mockMeetings;
    const term = debouncedSearch.toLowerCase();
    return mockMeetings.filter(m => m.title.toLowerCase().includes(term));
  }, [debouncedSearch]);

  const stats = useMemo(() => ({
    total: mockMeetings.length,
    scheduled: mockMeetings.filter(m => m.status === 'scheduled').length,
    completed: mockMeetings.filter(m => m.status === 'completed').length,
    totalHours: (mockMeetings.reduce((sum, m) => sum + m.duration, 0) / 60).toFixed(1),
  }), []);

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

  const handleSelectMeeting = (meeting: Meeting) => {
    setSelectedMeeting(meeting);
    addToast(`Viewing ${meeting.title}`, 'info');
  };

  return (
    <div className="app">
      <header className="app-header">
        <h1>Meeting Scheduler</h1>
        <p>Meeting links, upcoming, history</p>
      </header>

      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-label">Total Meetings</div>
          <div className="stat-value">{stats.total}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Scheduled</div>
          <div className="stat-value">{stats.scheduled}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Completed</div>
          <div className="stat-value">{stats.completed}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">Total Hours</div>
          <div className="stat-value">{stats.totalHours}</div>
        </div>
      </div>

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

      {filteredMeetings.length === 0 ? (
        <div className="empty-state">
          <h3>No meetings found</h3>
          <p>Try adjusting your search criteria</p>
        </div>
      ) : (
        <div className="data-grid">
          <table className="data-table">
            <thead>
              <tr>
                <th>Title</th>
                <th>Type</th>
                <th>Attendees</th>
                <th>Date/Time</th>
                <th>Duration</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filteredMeetings.map(meeting => (
                <tr
                  key={meeting.id}
                  onClick={() => handleSelectMeeting(meeting)}
                  className={selectedMeeting?.id === meeting.id ? 'selected' : ''}
                >
                  <td>{meeting.title}</td>
                  <td>{meeting.type}</td>
                  <td>{meeting.attendees.join(', ')}</td>
                  <td>{meeting.scheduledDate}</td>
                  <td>{meeting.duration}min</td>
                  <td>
                    <span className={`status-badge status-${meeting.status}`}>
                      {meeting.status}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {selectedMeeting && (
        <div className="detail-panel">
          <h3>Meeting Details</h3>
          <div className="detail-grid">
            <div><strong>Title:</strong> {selectedMeeting.title}</div>
            <div><strong>Type:</strong> {selectedMeeting.type}</div>
            <div><strong>Attendees:</strong> {selectedMeeting.attendees.join(', ')}</div>
            <div><strong>Date/Time:</strong> {selectedMeeting.scheduledDate}</div>
            <div><strong>Duration:</strong> {selectedMeeting.duration} minutes</div>
            <div><strong>Status:</strong> {selectedMeeting.status}</div>
            <div><strong>Meeting Link:</strong> {selectedMeeting.meetingLink}</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;
