import { Types } from 'mongoose';
import NotificationModel from '../models/Notification';
import UserModel from '../models/User';
import DeviceToken from '../models/DeviceToken';
import notificationService from '../services/notificationService';
import { PushNotificationUtils } from './PushNotificationUtils';

export interface CreateNotificationData {
  title: string;
  message: string;
  type?: 'MESSAGE' | 'EMERGENCY' | 'QRSCAN' | 'DEFAULT';
  link?: string;
  user_id: string;
  qrcode_id?: string;
  scan_id?: string;
  data?: Record<string, any>;
  sendPush?: boolean;
}

export interface NotificationResult {
  notification: any;
  pushSent: boolean;
  pushError?: string;
}

export class NotificationUtils {
  /**
   * Create a notification and optionally send push notification
   */
  static async createNotification(
    notificationData: CreateNotificationData
  ): Promise<NotificationResult> {
    try {
      // Validate user_id
      if (!Types.ObjectId.isValid(notificationData.user_id)) {
        throw new Error('Invalid user ID format');
      }

      // Validate qrcode_id if provided
      if (
        notificationData.qrcode_id &&
        !Types.ObjectId.isValid(notificationData.qrcode_id)
      ) {
        throw new Error('Invalid QR code ID format');
      }

      // Validate scan_id if provided
      if (
        notificationData.scan_id &&
        !Types.ObjectId.isValid(notificationData.scan_id)
      ) {
        throw new Error('Invalid scan ID format');
      }

      // Create notification in database
      const notification = new NotificationModel({
        title: notificationData.title,
        message: notificationData.message,
        type: notificationData.type || 'DEFAULT',
        link: notificationData.link,
        user_id: new Types.ObjectId(notificationData.user_id),
        qrcode_id: notificationData.qrcode_id
          ? new Types.ObjectId(notificationData.qrcode_id)
          : undefined,
        scan_id: notificationData.scan_id
          ? new Types.ObjectId(notificationData.scan_id)
          : undefined,
        data: notificationData.data || {},
        push_sent: false,
      });

      await notification.save();

      let pushSent = false;
      let pushError: string | undefined;

      // Send push notification if requested
      if (notificationData.sendPush !== false) {
        try {
          const pushResult = await this.sendPushNotification(notificationData.user_id, {
            title: notificationData.title,
            body: notificationData.message,
            data: {
              notificationId: notification._id.toString(),
              type: notificationData.type || 'DEFAULT',
              link: notificationData.link || '',
              ...notificationData.data,
            },
          });

          pushSent = pushResult.success;
          pushError = pushResult.error;

          // Update notification with push status
          await NotificationModel.findByIdAndUpdate(notification._id, {
            push_sent: pushSent,
            push_sent_at: pushSent ? new Date() : null,
            push_error: pushError,
          });
        } catch (error) {
          console.error('Error sending push notification:', error);
          pushError = error instanceof Error ? error.message : 'Unknown push error';

          // Update notification with error
          await NotificationModel.findByIdAndUpdate(notification._id, {
            push_sent: false,
            push_error: pushError,
          });
        }
      }

      return {
        notification: await notification.populate(
          'user_id',
          'first_name last_name email'
        ),
        pushSent,
        pushError,
      };
    } catch (error) {
      console.error('Error creating notification:', error);
      throw error;
    }
  }

  /**
   * Send push notification to user's devices (differentiates between web and mobile)
   */
  static async sendPushNotification(
    userId: string,
    payload: {
      title: string;
      body: string;
      data?: Record<string, string>;
      imageUrl?: string;
    }
  ): Promise<{
    success: boolean;
    error?: string;
    sentCount?: number;
    breakdown?: { web: number; mobile: number };
  }> {
    try {
      // Check if user has push notifications enabled
      const user = await UserModel.findById(userId).select('pushNotificationsEnabled');
      if (!user) {
        return { success: false, error: 'User not found' };
      }

      // If push notifications are disabled, skip sending
      if (user.pushNotificationsEnabled === false) {
        return { success: false, error: 'Push notifications disabled by user' };
      }

      // Get all active device tokens for the user
      const deviceTokens = await DeviceToken.find({
        userId: new Types.ObjectId(userId),
        isActive: true,
      });

      if (deviceTokens.length === 0) {
        return { success: false, error: 'No active device tokens found for user' };
      }

      let webSentCount = 0;
      let mobileSentCount = 0;
      let lastError: string | undefined;

      // Separate devices by type
      const webDevices = deviceTokens.filter(d => d.deviceType === 'web');
      const mobileDevices = deviceTokens.filter(
        d => d.deviceType === 'ios' || d.deviceType === 'android'
      );

      // Send to mobile devices using Firebase (FCM)
      for (const device of mobileDevices) {
        try {
          await notificationService.sendToDevice(device.deviceToken, payload);
          mobileSentCount++;

          // Update last used timestamp
          device.lastUsed = new Date();
          await device.save();
        } catch (error: any) {
          // Handle invalid token errors gracefully
          if (error?.message === 'INVALID_TOKEN') {
            console.warn(
              `⚠️ Invalid/expired token for ${device.deviceType} device (userId: ${userId}). Token will be marked as inactive.`
            );

            // Mark token as inactive - user needs to re-register device
            device.isActive = false;
            await device.save();

            lastError = 'Device token no longer valid';
          } else {
            console.error(`Failed to send FCM to ${device.deviceType} device:`, error);
            lastError = error instanceof Error ? error.message : 'Unknown error';
          }
        }
      }

      // Send to web devices using Firebase (FCM for web)
      for (const device of webDevices) {
        try {
          // Validate token
          if (!PushNotificationUtils.validateToken(device.deviceToken)) {
            console.error('Invalid FCM token format');
            continue;
          }

          const result = await PushNotificationUtils.sendNotification({
            token: device.deviceToken,
            payload: {
              title: payload.title,
              message: payload.body,
              icon: payload.imageUrl,
              url: payload.data?.link || '/',
            },
          });

          if (result.success) {
            webSentCount++;

            // Update last used timestamp
            device.lastUsed = new Date();
            await device.save();
          } else {
            lastError = result.message;

            // Mark token as inactive if it's no longer valid
            if (result.message.includes('no longer valid')) {
              device.isActive = false;
              await device.save();
            }
          }
        } catch (error) {
          console.error('Failed to send FCM notification to web:', error);
          lastError = error instanceof Error ? error.message : 'Unknown error';
        }
      }

      const totalSent = webSentCount + mobileSentCount;

      return {
        success: totalSent > 0,
        error: totalSent === 0 ? lastError : undefined,
        sentCount: totalSent,
        breakdown: {
          web: webSentCount,
          mobile: mobileSentCount,
        },
      };
    } catch (error) {
      console.error('Error in sendPushNotification:', error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * Create and send notification for QR code scan
   */
  static async createQRScanNotification(
    userId: string,
    qrCodeId: string,
    scanData: {
      scanId?: string;
      location?: string;
      deviceInfo?: string;
      timestamp?: Date;
    } = {}
  ): Promise<NotificationResult> {
    return this.createNotification({
      title: 'QR Code Scanned',
      message: `Your QR code was scanned${scanData.location ? ` in ${scanData.location}` : ''}`,
      type: 'QRSCAN',
      user_id: userId,
      qrcode_id: qrCodeId,
      scan_id: scanData.scanId,
      data: {
        scan_location: scanData.location || '',
        device_info: scanData.deviceInfo || '',
        scan_timestamp: scanData.timestamp?.toISOString() || new Date().toISOString(),
      },
      sendPush: true,
    });
  }

  /**
   * Create and send emergency notification
   */
  static async createEmergencyNotification(
    userId: string,
    message: string,
    qrCodeId?: string,
    additionalData?: Record<string, any>
  ): Promise<NotificationResult> {
    return this.createNotification({
      title: 'Emergency Alert',
      message,
      type: 'EMERGENCY',
      user_id: userId,
      qrcode_id: qrCodeId,
      data: additionalData || {},
      sendPush: true,
    });
  }

  /**
   * Create and send message notification
   */
  public static async createMessageNotification(
    userId: string,
    title: string,
    message: string,
    link?: string,
    scanId?: string,
    additionalData?: Record<string, any>
  ): Promise<NotificationResult> {
    return this.createNotification({
      title,
      message,
      type: 'MESSAGE',
      scan_id: scanId,
      user_id: userId,
      link,
      data: additionalData || {},
      sendPush: true,
    });
  }

  /**
   * Bulk create notifications for multiple users
   */
  static async createBulkNotifications(
    userIds: string[],
    notificationData: Omit<CreateNotificationData, 'user_id'>
  ): Promise<NotificationResult[]> {
    const results: NotificationResult[] = [];

    for (const userId of userIds) {
      try {
        const result = await this.createNotification({
          ...notificationData,
          user_id: userId,
        });
        results.push(result);
      } catch (error) {
        console.error(`Failed to create notification for user ${userId}:`, error);
        results.push({
          notification: null,
          pushSent: false,
          pushError: error instanceof Error ? error.message : 'Unknown error',
        });
      }
    }

    return results;
  }
}
