const { useState, useEffect } = React;

function EmailQueue({ user }) {
  const [drafts, setDrafts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('pending_approval');

  const isPrincipal = user.role === 'principal';

  useEffect(() => {
    loadDrafts();
    // Refresh every 30 seconds
    const interval = setInterval(loadDrafts, 30000);
    return () => clearInterval(interval);
  }, [filter]);

  const loadDrafts = async () => {
    try {
      const url = filter ? `/api/email-drafts?status=${filter}` : '/api/email-drafts';
      const res = await fetch(url);
      const data = await res.json();
      setDrafts(data);
      setLoading(false);
    } catch (err) {
      console.error('Error loading drafts:', err);
      setLoading(false);
    }
  };

  const approveDraft = async (draftId) => {
    try {
      const res = await fetch(`/api/email-drafts/${draftId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ new_status: 'approved' }),
      });
      alert('Email approved. Now ready to send.');
      loadDrafts();
    } catch (err) {
      alert('Error approving draft: ' + err.message);
    }
  };

  const sendDraft = async (draftId) => {
    try {
      // In a real implementation, this would call Gmail API to send
      const res = await fetch(`/api/email-drafts/${draftId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ new_status: 'sent' }),
      });
      alert('Email sent and logged.');
      loadDrafts();
    } catch (err) {
      alert('Error sending draft: ' + err.message);
    }
  };

  if (loading) return <div className="card">Loading email queue...</div>;

  return (
    <div>
      <div className="page-header">
        <h1>Email Queue</h1>
      </div>

      {/* Filter Tabs */}
      <div className="card" style={{ paddingBottom: 0 }}>
        <div style={{ display: 'flex', borderBottom: '1px solid #e9ecef' }}>
          <button
            onClick={() => setFilter('pending_approval')}
            style={{
              padding: '12px 16px',
              background: filter === 'pending_approval' ? '#4d96ff' : 'transparent',
              color: filter === 'pending_approval' ? 'white' : '#666',
              border: 'none',
              borderBottom: filter === 'pending_approval' ? '3px solid #4d96ff' : 'none',
              cursor: 'pointer',
              fontSize: '13px',
              fontWeight: 500,
            }}
          >
            Pending Approval ({drafts.filter(d => d.status === 'pending_approval').length})
          </button>
          <button
            onClick={() => setFilter('approved')}
            style={{
              padding: '12px 16px',
              background: filter === 'approved' ? '#4d96ff' : 'transparent',
              color: filter === 'approved' ? 'white' : '#666',
              border: 'none',
              borderBottom: filter === 'approved' ? '3px solid #4d96ff' : 'none',
              cursor: 'pointer',
              fontSize: '13px',
              fontWeight: 500,
            }}
          >
            Ready to Send ({drafts.filter(d => d.status === 'approved').length})
          </button>
          <button
            onClick={() => setFilter('sent')}
            style={{
              padding: '12px 16px',
              background: filter === 'sent' ? '#4d96ff' : 'transparent',
              color: filter === 'sent' ? 'white' : '#666',
              border: 'none',
              borderBottom: filter === 'sent' ? '3px solid #4d96ff' : 'none',
              cursor: 'pointer',
              fontSize: '13px',
              fontWeight: 500,
            }}
          >
            Sent
          </button>
        </div>
      </div>

      {/* Drafts List */}
      <div className="card" style={{ paddingTop: 0 }}>
        {drafts.length === 0 ? (
          <p style={{ color: '#999', fontSize: '13px', paddingTop: '20px' }}>No drafts in this status</p>
        ) : (
          drafts.map(draft => (
            <div
              key={draft.id}
              style={{
                padding: '15px',
                borderBottom: '1px solid #f0f0f0',
                display: 'grid',
                gridTemplateColumns: '1fr auto',
                gap: '20px',
                alignItems: 'start',
              }}
            >
              <div>
                <div style={{ fontWeight: 500, marginBottom: '5px' }}>
                  {draft.subject}
                </div>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '10px' }}>
                  To: {draft.full_name} • Draft by {draft.created_by}
                </div>
                <div style={{
                  fontSize: '13px',
                  lineHeight: '1.5',
                  color: '#333',
                  backgroundColor: '#f8f9fa',
                  padding: '10px',
                  borderRadius: '4px',
                  maxHeight: '100px',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}>
                  {draft.body}
                </div>
              </div>
              <div style={{ textAlign: 'right', minWidth: '150px' }}>
                <span className="tier-badge" style={{ background: '#95E1D3', color: '#333', marginBottom: '10px', display: 'block' }}>
                  {draft.status}
                </span>
                {draft.status === 'pending_approval' && isPrincipal && (
                  <div style={{ display: 'flex', gap: '5px', flexDirection: 'column' }}>
                    <button onClick={() => approveDraft(draft.id)} className="btn btn-success" style={{ fontSize: '11px' }}>
                      Approve
                    </button>
                    <button className="btn btn-danger" style={{ fontSize: '11px' }}>
                      Reject
                    </button>
                  </div>
                )}
                {draft.status === 'approved' && isPrincipal && (
                  <button onClick={() => sendDraft(draft.id)} className="btn btn-primary" style={{ fontSize: '11px' }}>
                    Send Now
                  </button>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}

