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

function App() {
  const [threads, setThreads] = useState<any[]>([]);
  const [selectedThread, setSelectedThread] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadThreads();
  }, []);

  const loadThreads = async () => {
    setLoading(true);
    try {
      const response = await fetch('/mcp/pipedrive_mail_threads_list', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ limit: 100 })
      });
      const data = await response.json();
      setThreads(data.data || []);
    } catch (error) {
      console.error('Failed to load mail threads:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  if (loading) {
    return <div className="loading">Loading inbox...</div>;
  }

  return (
    <div className="app">
      <header className="header">
        <h1>📧 Email Inbox</h1>
        <button onClick={loadThreads} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="inbox-layout">
        <div className="thread-list">
          {threads.map(thread => (
            <div
              key={thread.id}
              className={`thread-item ${selectedThread?.id === thread.id ? 'active' : ''}`}
              onClick={() => setSelectedThread(thread)}
            >
              <div className="thread-subject">{thread.subject || '(No subject)'}</div>
              <div className="thread-snippet">{thread.snippet || ''}</div>
              <div className="thread-meta">
                <span>{thread.message_count} messages</span>
                <span>{formatDate(thread.last_message_timestamp)}</span>
              </div>
            </div>
          ))}
        </div>

        <div className="thread-detail">
          {selectedThread ? (
            <>
              <h2>{selectedThread.subject || '(No subject)'}</h2>
              <div className="detail-meta">
                <span>Messages: {selectedThread.message_count}</span>
                <span>Last: {formatDate(selectedThread.last_message_timestamp)}</span>
              </div>
              <div className="message-preview">
                {selectedThread.snippet || 'No preview available'}
              </div>
            </>
          ) : (
            <div className="empty-detail">Select a thread to view details</div>
          )}
        </div>
      </div>
    </div>
  );
}

export default App;
