import { storage } from "./storage";
import { sendEmail } from "./email";
import type { InsertNotification } from "@shared/schema";

interface SendNotificationParams {
  userId: string;
  organizationId?: number;
  type: "info" | "success" | "warning" | "error" | "match" | "payment" | "attendance";
  title: string;
  message: string;
  link?: string;
  metadata?: any;
  channels?: ("in_app" | "email" | "sms")[];
}

interface SendEmailNotificationParams {
  to: string;
  subject: string;
  html: string;
  userId: string;
}

interface SendSMSNotificationParams {
  to: string;
  message: string;
  userId: string;
}

export class NotificationService {
  async sendNotification(params: SendNotificationParams): Promise<void> {
    const { channels = ["in_app"], ...notificationData } = params;

    // Always create in-app notification if included in channels
    if (channels.includes("in_app")) {
      await this.createInAppNotification(notificationData);
    }

    // Send email notification if requested
    if (channels.includes("email")) {
      const user = await storage.getUser(params.userId);
      if (user?.email) {
        await this.sendEmailNotification({
          to: user.email,
          subject: params.title,
          html: this.buildEmailHtml(params.title, params.message, params.link),
          userId: params.userId,
        });
      }
    }

    // Send SMS notification if requested (requires Twilio credentials)
    if (channels.includes("sms")) {
      const user = await storage.getUser(params.userId);
      // SMS will only work if Twilio credentials are configured
      if (user && process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
        // SMS implementation would go here when Twilio is set up
        console.log(`SMS notification would be sent to user ${params.userId}`);
      }
    }
  }

  private async createInAppNotification(data: Omit<SendNotificationParams, "channels">): Promise<void> {
    const notification: InsertNotification = {
      userId: data.userId,
      organizationId: data.organizationId,
      type: data.type,
      title: data.title,
      message: data.message,
      link: data.link,
      isRead: false,
      metadata: data.metadata,
    };

    await storage.createNotification(notification);
  }

  private async sendEmailNotification(params: SendEmailNotificationParams): Promise<void> {
    try {
      await sendEmail({
        to: params.to,
        subject: params.subject,
        html: params.html,
      });
    } catch (error) {
      console.error("Failed to send email notification:", error);
    }
  }

  private buildEmailHtml(title: string, message: string, link?: string): string {
    return `
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>${title}</title>
        <style>
          body { 
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; 
            line-height: 1.6; 
            color: #333; 
            margin: 0; 
            padding: 0; 
            background-color: #f5f7fa;
          }
          .container { 
            max-width: 600px; 
            margin: 0 auto; 
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          }
          .header { 
            background: linear-gradient(135deg, #1e3a8a 0%, #3730a3 100%); 
            color: white; 
            padding: 40px; 
            text-align: center; 
          }
          .content { 
            padding: 40px; 
          }
          .footer { 
            text-align: center; 
            padding: 20px; 
            color: #666; 
            font-size: 14px; 
            border-top: 1px solid #eee;
          }
          .button { 
            background: #1e3a8a; 
            color: white; 
            padding: 12px 24px; 
            text-decoration: none; 
            border-radius: 6px; 
            display: inline-block; 
            margin-top: 20px;
          }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>${title}</h1>
          </div>
          <div class="content">
            <p>${message}</p>
            ${link ? `<a href="${link}" class="button">View Details</a>` : ''}
          </div>
          <div class="footer">
            <p>SportsPro - Advanced Sports Management Platform</p>
            <p>© ${new Date().getFullYear()} All rights reserved</p>
          </div>
        </div>
      </body>
      </html>
    `;
  }

  // Bulk notification methods
  async sendBulkNotification(userIds: string[], params: Omit<SendNotificationParams, "userId">): Promise<void> {
    const promises = userIds.map(userId => 
      this.sendNotification({ ...params, userId })
    );
    await Promise.all(promises);
  }

  // Notification templates
  async sendMatchNotification(params: {
    userId: string;
    organizationId?: number;
    matchDetails: string;
    matchTime: string;
    venue: string;
    link?: string;
  }): Promise<void> {
    await this.sendNotification({
      userId: params.userId,
      organizationId: params.organizationId,
      type: "match",
      title: "Upcoming Match",
      message: `${params.matchDetails} at ${params.matchTime} - ${params.venue}`,
      link: params.link,
      channels: ["in_app", "email"],
    });
  }

  async sendPaymentNotification(params: {
    userId: string;
    organizationId?: number;
    amount: string;
    dueDate: string;
    link?: string;
  }): Promise<void> {
    await this.sendNotification({
      userId: params.userId,
      organizationId: params.organizationId,
      type: "payment",
      title: "Payment Reminder",
      message: `Payment of ${params.amount} is due on ${params.dueDate}`,
      link: params.link,
      channels: ["in_app", "email"],
    });
  }

  async sendAttendanceNotification(params: {
    userId: string;
    organizationId?: number;
    sessionTitle: string;
    sessionDate: string;
    sessionTime: string;
    link?: string;
  }): Promise<void> {
    await this.sendNotification({
      userId: params.userId,
      organizationId: params.organizationId,
      type: "attendance",
      title: "Session Reminder",
      message: `${params.sessionTitle} on ${params.sessionDate} at ${params.sessionTime}`,
      link: params.link,
      channels: ["in_app", "email"],
    });
  }
}

export const notificationService = new NotificationService();
