import React, { useState, useEffect } from 'react';
import './styles.css';

interface Appointment {
  id: number;
  firstName: string;
  lastName: string;
  datetime: string;
  type: string;
  appointmentTypeID: number;
  status: 'confirmed' | 'pending' | 'canceled';
  calendarID: number;
}

interface DashboardStats {
  today: number;
  thisWeek: number;
  thisMonth: number;
  total: number;
}

export default function AppointmentDashboard() {
  const [stats, setStats] = useState<DashboardStats>({ today: 0, thisWeek: 0, thisMonth: 0, total: 0 });
  const [upcomingAppointments, setUpcomingAppointments] = useState<Appointment[]>([]);
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState<'today' | 'week' | 'month'>('today');

  useEffect(() => {
    fetchDashboardData();
  }, [dateRange]);

  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      // In production, this would call MCP tools:
      // const appointments = await window.mcp.call('acuity_list_appointments', { minDate, maxDate });
      
      // Mock data for demo
      const mockAppointments: Appointment[] = [
        { id: 1, firstName: 'John', lastName: 'Doe', datetime: '2024-02-15T10:00:00', type: 'Initial Consultation', appointmentTypeID: 1, status: 'confirmed', calendarID: 1 },
        { id: 2, firstName: 'Jane', lastName: 'Smith', datetime: '2024-02-15T14:30:00', type: 'Follow-up Session', appointmentTypeID: 2, status: 'confirmed', calendarID: 1 },
        { id: 3, firstName: 'Bob', lastName: 'Johnson', datetime: '2024-02-16T09:00:00', type: 'Assessment', appointmentTypeID: 3, status: 'pending', calendarID: 2 },
        { id: 4, firstName: 'Alice', lastName: 'Williams', datetime: '2024-02-16T11:30:00', type: 'Check-in', appointmentTypeID: 1, status: 'confirmed', calendarID: 1 },
      ];
      
      setUpcomingAppointments(mockAppointments);
      setStats({ today: 2, thisWeek: 8, thisMonth: 32, total: 156 });
    } catch (error) {
      console.error('Error fetching dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatDateTime = (datetime: string) => {
    const date = new Date(datetime);
    return date.toLocaleString('en-US', { 
      month: 'short', 
      day: 'numeric', 
      hour: 'numeric', 
      minute: '2-digit',
      hour12: true 
    });
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'confirmed': return '#10b981';
      case 'pending': return '#f59e0b';
      case 'canceled': return '#ef4444';
      default: return '#6b7280';
    }
  };

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

  return (
    <div className="dashboard">
      <header className="dashboard-header">
        <h1>Appointment Dashboard</h1>
        <div className="date-range-selector">
          <button 
            className={dateRange === 'today' ? 'active' : ''} 
            onClick={() => setDateRange('today')}
          >
            Today
          </button>
          <button 
            className={dateRange === 'week' ? 'active' : ''} 
            onClick={() => setDateRange('week')}
          >
            This Week
          </button>
          <button 
            className={dateRange === 'month' ? 'active' : ''} 
            onClick={() => setDateRange('month')}
          >
            This Month
          </button>
        </div>
      </header>
      
      <div className="stats-grid">
        <div className="stat-card">
          <div className="stat-icon">📅</div>
          <div className="stat-content">
            <h3>Today</h3>
            <div className="stat-value">{stats.today}</div>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">📆</div>
          <div className="stat-content">
            <h3>This Week</h3>
            <div className="stat-value">{stats.thisWeek}</div>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">🗓️</div>
          <div className="stat-content">
            <h3>This Month</h3>
            <div className="stat-value">{stats.thisMonth}</div>
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-icon">📊</div>
          <div className="stat-content">
            <h3>Total</h3>
            <div className="stat-value">{stats.total}</div>
          </div>
        </div>
      </div>

      <div className="appointments-section">
        <div className="section-header">
          <h2>Upcoming Appointments</h2>
          <button className="refresh-btn" onClick={fetchDashboardData}>
            🔄 Refresh
          </button>
        </div>
        
        <div className="appointments-list">
          {upcomingAppointments.length === 0 ? (
            <div className="empty-state">
              <p>No upcoming appointments</p>
            </div>
          ) : (
            upcomingAppointments.map(apt => (
              <div key={apt.id} className="appointment-card">
                <div className="appointment-info">
                  <h4>{apt.firstName} {apt.lastName}</h4>
                  <p className="appointment-meta">
                    <span className="datetime">🕐 {formatDateTime(apt.datetime)}</span>
                    <span className="type">• {apt.type}</span>
                  </p>
                </div>
                <div className="appointment-actions">
                  <span 
                    className="status-badge" 
                    style={{ backgroundColor: getStatusColor(apt.status) + '20', color: getStatusColor(apt.status) }}
                  >
                    {apt.status.charAt(0).toUpperCase() + apt.status.slice(1)}
                  </span>
                  <button className="view-btn">View →</button>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
