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

function App() {
  const [activities, setActivities] = useState<any[]>([]);
  const [currentDate, setCurrentDate] = useState(new Date());
  const [loading, setLoading] = useState(true);

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

  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 getDaysInMonth = () => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const days = [];
    
    for (let i = 0; i < firstDay; i++) {
      days.push(null);
    }
    
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(i);
    }
    
    return days;
  };

  const getActivitiesForDay = (day: number) => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    return activities.filter(a => a.due_date?.startsWith(dateStr));
  };

  const prevMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1));
  };

  const nextMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1));
  };

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

  const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  const days = getDaysInMonth();

  return (
    <div className="app">
      <header className="header">
        <h1>📅 Activity Calendar</h1>
        <div className="nav">
          <button onClick={prevMonth}>←</button>
          <span>{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}</span>
          <button onClick={nextMonth}>→</button>
        </div>
      </header>

      <div className="calendar">
        <div className="calendar-header">
          {dayNames.map(day => (
            <div key={day} className="day-name">{day}</div>
          ))}
        </div>
        <div className="calendar-grid">
          {days.map((day, index) => {
            const dayActivities = day ? getActivitiesForDay(day) : [];
            return (
              <div key={index} className={`calendar-day ${!day ? 'empty' : ''}`}>
                {day && (
                  <>
                    <div className="day-number">{day}</div>
                    <div className="day-activities">
                      {dayActivities.slice(0, 3).map(activity => (
                        <div key={activity.id} className={`activity-dot ${activity.done ? 'done' : ''}`} title={activity.subject}></div>
                      ))}
                      {dayActivities.length > 3 && <div className="more">+{dayActivities.length - 3}</div>}
                    </div>
                  </>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

export default App;
