const { useState, useEffect } = React;

function Dashboard() {
  const [dashboard, setDashboard] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/api/dashboard')
      .then(res => res.json())
      .then(data => {
        setDashboard(data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) return <div className="card">Loading dashboard...</div>;
  if (error) return <div className="card" style={{ color: 'red' }}>Error: {error}</div>;
  if (!dashboard) return null;

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

      {/* Key Metrics */}
      <div className="grid">
        {Object.entries(dashboard.by_tier).map(([tier, count]) => (
          <div className="stat-box" key={tier}>
            <div className="stat-number">{count}</div>
            <div className="stat-label">{tier}</div>
          </div>
        ))}
      </div>

      {/* Due for Contact */}
      <div className="card">
        <div className="card-title">Due for Contact</div>
        {dashboard.due_contacts.length === 0 ? (
          <p style={{ color: '#999', fontSize: '13px' }}>No contacts due today</p>
        ) : (
          <div>
            {dashboard.due_contacts.map(contact => (
              <div key={contact.id} className="contact-row">
                <div className="contact-info">
                  <div className="contact-name">{contact.full_name}</div>
                  <div className="contact-subtitle">
                    {contact.organisation} • {contact.next_due_date ? new Date(contact.next_due_date).toLocaleDateString() : 'No date'}
                  </div>
                </div>
                <span className={`tier-badge ${contact.tier.toLowerCase()}`}>{contact.tier}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Cooling Relationships */}
      {dashboard.cooling_relationships.length > 0 && (
        <div className="card">
          <div className="card-title">Cooling Relationships ⚠️</div>
          {dashboard.cooling_relationships.map(contact => (
            <div key={contact.id} className="contact-row">
              <div className="contact-info">
                <div className="contact-name">{contact.full_name}</div>
                <div className="contact-subtitle">
                  Last contacted: {contact.last_contacted ? new Date(contact.last_contacted).toLocaleDateString() : 'Never'}
                </div>
              </div>
              <span className={`tier-badge ${contact.tier.toLowerCase()}`}>{contact.tier}</span>
            </div>
          ))}
        </div>
      )}

      {/* Pending Email Approvals (Principal only) */}
      {dashboard.pending_approvals.length > 0 && (
        <div className="card">
          <div className="card-title">Pending Email Approvals</div>
          {dashboard.pending_approvals.map(approval => (
            <div key={approval.id} className="contact-row">
              <div className="contact-info">
                <div className="contact-name">{approval.subject}</div>
                <div className="contact-subtitle">From: {approval.created_by}</div>
              </div>
              <button className="btn btn-secondary" onClick={() => console.log('Approve:', approval.id)}>
                Review
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

