import { useState, useEffect } from 'react';

export default function ScheduleOverview() {
  const [appointments, setAppointments] = useState<any[]>([]);
  const [calendars, setCalendars] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    const nextWeek = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
    
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_list_appointments', params: { minDate: today, maxDate: nextWeek } }, '*');
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_list_calendars', params: {} }, '*');
  }, []);

  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data.type === 'mcp-result') {
        const result = JSON.parse(e.data.result);
        if (Array.isArray(result) && result[0]?.datetime) {
          setAppointments(result);
          setLoading(false);
        } else if (Array.isArray(result) && result[0]?.name) {
          setCalendars(result);
        }
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  const groupByDate = (apts: any[]) => {
    const grouped: Record<string, any[]> = {};
    apts.forEach(apt => {
      const date = apt.datetime.split('T')[0];
      if (!grouped[date]) grouped[date] = [];
      grouped[date].push(apt);
    });
    return grouped;
  };

  if (loading) return <div style={{ padding: '20px' }}>Loading...</div>;

  const grouped = groupByDate(appointments);

  return (
    <div style={{ padding: '20px', fontFamily: 'system-ui, sans-serif' }}>
      <header style={{ marginBottom: '20px' }}>
        <h1 style={{ margin: 0, fontSize: '24px' }}>Schedule Overview</h1>
        <div style={{ marginTop: '10px', fontSize: '14px', color: '#666' }}>Next 7 days</div>
      </header>

      <section style={{ marginBottom: '30px' }}>
        <h2 style={{ fontSize: '18px', marginBottom: '10px' }}>Summary</h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '15px' }}>
          <div style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px', textAlign: 'center' }}>
            <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#007bff' }}>{appointments.length}</div>
            <div style={{ fontSize: '14px', color: '#666' }}>Total Appointments</div>
          </div>
          <div style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px', textAlign: 'center' }}>
            <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#28a745' }}>{calendars.length}</div>
            <div style={{ fontSize: '14px', color: '#666' }}>Active Calendars</div>
          </div>
          <div style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px', textAlign: 'center' }}>
            <div style={{ fontSize: '32px', fontWeight: 'bold', color: '#ffc107' }}>{Object.keys(grouped).length}</div>
            <div style={{ fontSize: '14px', color: '#666' }}>Busy Days</div>
          </div>
        </div>
      </section>

      <section>
        <h2 style={{ fontSize: '18px', marginBottom: '15px' }}>Daily Schedule</h2>
        {Object.entries(grouped).sort().map(([date, apts]) => (
          <div key={date} style={{ marginBottom: '20px' }}>
            <h3 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '10px', color: '#007bff' }}>
              {new Date(date + 'T00:00:00').toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}
            </h3>
            <div style={{ display: 'grid', gap: '10px' }}>
              {apts.map((apt: any) => (
                <div key={apt.id} style={{ border: '1px solid #ddd', padding: '12px', borderRadius: '8px', background: '#f8f9fa' }}>
                  <div style={{ marginBottom: '5px' }}><strong>{apt.time}</strong> - {apt.type}</div>
                  <div style={{ fontSize: '14px', color: '#666' }}>{apt.firstName} {apt.lastName}</div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </section>
    </div>
  );
}
