import { storage } from "./storage";
import { sendEmail } from "./email";
import { format, addDays, isBefore } from "date-fns";

interface NotificationConfig {
  reminderHours: number;
  absenceThreshold: number;
  lateArrivalThreshold: number;
}

export class AttendanceNotificationService {
  private config: NotificationConfig = {
    reminderHours: 24, // Send reminders 24 hours before
    absenceThreshold: 3, // Alert after 3 absences
    lateArrivalThreshold: 3, // Alert after 3 late arrivals
  };

  async sendSessionReminders() {
    try {
      // Get upcoming sessions in the next 24 hours
      const tomorrow = addDays(new Date(), 1);
      const sessions = await storage.getAttendanceSessions();
      
      const upcomingSessions = sessions.filter(session => {
        const sessionDate = new Date(session.date);
        return isBefore(new Date(), sessionDate) && isBefore(sessionDate, tomorrow);
      });

      for (const session of upcomingSessions) {
        // Get team players if session has a team
        let players = [];
        if (session.teamId) {
          players = await storage.getPlayers(); // Filter by team in real implementation
        } else {
          players = await storage.getPlayers();
        }

        // Send reminder to each player
        for (const player of players) {
          if (player.email) {
            await this.sendReminderEmail(player, session);
            
            // Create notification record
            await storage.createAttendanceNotification({
              playerId: player.id,
              sessionId: session.id,
              type: 'reminder',
              message: `Reminder: ${session.title} scheduled for ${format(new Date(session.date), 'PPP')} at ${session.startTime}`,
              scheduledFor: new Date(),
            });
          }
        }
      }
    } catch (error) {
      console.error('Error sending session reminders:', error);
    }
  }

  async checkAbsenceAlerts() {
    try {
      const players = await storage.getPlayers();
      
      for (const player of players) {
        const stats = await storage.getAttendanceStats(player.id);
        
        if (stats && stats.absences >= this.config.absenceThreshold) {
          // Send absence alert to coaches and admins
          await this.sendAbsenceAlert(player, stats);
          
          // Create notification record
          await storage.createAttendanceNotification({
            playerId: player.id,
            sessionId: 0, // General notification, not session-specific
            type: 'absence_alert',
            message: `Alert: ${player.firstName} ${player.lastName} has ${stats.absences} absences (${stats.attendanceRate}% attendance rate)`,
            scheduledFor: new Date(),
          });
        }
      }
    } catch (error) {
      console.error('Error checking absence alerts:', error);
    }
  }

  async checkLateArrivalAlerts() {
    try {
      const players = await storage.getPlayers();
      
      for (const player of players) {
        const stats = await storage.getAttendanceStats(player.id);
        
        if (stats && stats.lateCount >= this.config.lateArrivalThreshold) {
          // Send late arrival alert to coaches
          await this.sendLateArrivalAlert(player, stats);
          
          // Create notification record
          await storage.createAttendanceNotification({
            playerId: player.id,
            sessionId: 0, // General notification, not session-specific
            type: 'late_arrival',
            message: `Alert: ${player.firstName} ${player.lastName} has been late ${stats.lateCount} times`,
            scheduledFor: new Date(),
          });
        }
      }
    } catch (error) {
      console.error('Error checking late arrival alerts:', error);
    }
  }

  private async sendReminderEmail(player: any, session: any) {
    const subject = `Reminder: ${session.title}`;
    const htmlContent = `
      <h2>Training Session Reminder</h2>
      <p>Hi ${player.firstName},</p>
      <p>This is a reminder that you have a ${session.type} session scheduled:</p>
      
      <div style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 20px 0;">
        <h3>${session.title}</h3>
        <p><strong>Date:</strong> ${format(new Date(session.date), 'EEEE, MMMM d, yyyy')}</p>
        <p><strong>Time:</strong> ${session.startTime} - ${session.endTime}</p>
        ${session.location ? `<p><strong>Location:</strong> ${session.location}</p>` : ''}
        ${session.description ? `<p><strong>Description:</strong> ${session.description}</p>` : ''}
      </div>
      
      <p>Please ensure you arrive on time and come prepared.</p>
      <p>If you cannot attend, please contact your coach as soon as possible.</p>
      
      <p>Best regards,<br>SportsPro Team</p>
    `;

    return await sendEmail({
      to: player.email,
      subject: subject,
      html: htmlContent,
      text: `Training Session Reminder - Hi ${player.firstName}, This is a reminder for ${session.title} on ${format(new Date(session.date), 'EEEE, MMMM d, yyyy')} at ${session.startTime}.`
    });
  }

  private async sendAbsenceAlert(player: any, stats: any) {
    // In a real implementation, this would send to coaches/admins
    console.log(`Absence Alert: ${player.firstName} ${player.lastName} - ${stats.absences} absences, ${stats.attendanceRate}% rate`);
  }

  private async sendLateArrivalAlert(player: any, stats: any) {
    // In a real implementation, this would send to coaches
    console.log(`Late Arrival Alert: ${player.firstName} ${player.lastName} - ${stats.lateCount} late arrivals`);
  }

  async processScheduledNotifications() {
    try {
      const pendingNotifications = await storage.getPendingAttendanceNotifications();
      
      for (const notification of pendingNotifications) {
        if (notification.scheduledFor && new Date() >= new Date(notification.scheduledFor)) {
          // Process the notification based on type
          switch (notification.type) {
            case 'reminder':
              // Reminder notifications are processed immediately
              break;
            case 'absence_alert':
              // Send to coaches/admins
              break;
            case 'late_arrival':
              // Send to coaches
              break;
          }
          
          // Mark as sent
          await storage.updateAttendanceNotificationStatus(notification.id, 'sent');
        }
      }
    } catch (error) {
      console.error('Error processing scheduled notifications:', error);
    }
  }

  // Method to be called periodically (e.g., via cron job)
  async runNotificationCheck() {
    console.log('Running attendance notification check...');
    
    await this.sendSessionReminders();
    await this.checkAbsenceAlerts();
    await this.checkLateArrivalAlerts();
    await this.processScheduledNotifications();
    
    console.log('Attendance notification check completed');
  }
}

export const attendanceNotificationService = new AttendanceNotificationService();