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

function App() {
  const [activities, setActivities] = useState<any[]>([]);
  const [filtered, setFiltered] = useState<any[]>([]);
  const [filter, setFilter] = useState<'all' | 'pending' | 'done'>('all');
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    if (filter === 'all') setFiltered(activities);
    else if (filter === 'pending') setFiltered(activities.filter(a => !a.done));
    else setFiltered(activities.filter(a => a.done));
  }, [filter, activities]);

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

  const toggleDone = async (id: number, done: boolean) => {
    try {
      await fetch('/mcp/pipedrive_activity_update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, done: !done })
      });
      loadActivities();
    } catch (error) {
      console.error('Failed to update activity:', error);
    }
  };

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

  const pendingCount = activities.filter(a => !a.done).length;
  const doneCount = activities.filter(a => a.done).length;

  return (
    <div className="app">
      <header className="header">
        <h1>📅 Activity Dashboard</h1>
        <button onClick={loadActivities} className="refresh-btn">↻ Refresh</button>
      </header>

      <div className="stats">
        <div className="stat-card"><div className="label">Total</div><div className="value">{activities.length}</div></div>
        <div className="stat-card"><div className="label">Pending</div><div className="value">{pendingCount}</div></div>
        <div className="stat-card"><div className="label">Done</div><div className="value">{doneCount}</div></div>
      </div>

      <div className="filters">
        <button className={filter === 'all' ? 'active' : ''} onClick={() => setFilter('all')}>All</button>
        <button className={filter === 'pending' ? 'active' : ''} onClick={() => setFilter('pending')}>Pending</button>
        <button className={filter === 'done' ? 'active' : ''} onClick={() => setFilter('done')}>Done</button>
      </div>

      <div className="list">
        {filtered.map(activity => (
          <div key={activity.id} className={`activity-item ${activity.done ? 'done' : ''}`}>
            <input type="checkbox" checked={activity.done} onChange={() => toggleDone(activity.id, activity.done)} />
            <div className="activity-content">
              <div className="activity-subject">{activity.subject}</div>
              <div className="activity-meta">
                <span className="activity-type">{activity.type}</span>
                <span className="activity-date">{new Date(activity.due_date).toLocaleDateString()}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
