import QRCode from 'qrcode';
import path from 'path';
import fs from 'fs/promises';
import { QRCodeEncryption } from './qrcodeEncryption';
import { FileHandlerUtils } from './FileHandlerUtils';

export class QRCodeHelper {
  /**
   * Generate QR code image and save to file system
   */
  public static async generateQRCode(
    data: string,
    filename: string,
    type: string,
    options?: {
      color?: string;
      background_color?: string;
      size?: number;
    }
  ): Promise<{ filePath: string; size: number }> {
    try {
      // Create uploads directory if it doesn't exist
      // Use root-level uploads directory for both production and development
      const baseUploadsDir = path.join(process.cwd(), 'uploads');
      const uploadsDir = path.join(baseUploadsDir, 'qrcodes');
      await fs.mkdir(uploadsDir, { recursive: true });

      // Generate filename with type prefix
      const typePrefix = type.toLowerCase().replace('_', '-');
      const fullFilename = `${typePrefix}-${filename}.png`;
      const filePath = path.join(uploadsDir, fullFilename);

      // QR code generation options
      const qrOptions = {
        type: 'png' as const,
        quality: 0.92,
        margin: 4,                // important — quiet zone of 4 modules
        scale: 4,                 // integer module size (no fractional pixels)
        color: {
          dark: options?.color || '#000000',
          light: options?.background_color || '#FFFFFF',
        },
        // width: options?.size || 256,
      };

      // Generate QR code
      await QRCode.toFile(filePath, data, qrOptions);

      // Get file size
      const stats = await fs.stat(filePath);

      return {
        filePath: `uploads/qrcodes/${fullFilename}`,
        size: stats.size,
      };
    } catch (error) {
      console.error('Error generating QR code:', error);
      throw new Error('Failed to generate QR code');
    }
  }

  /**
   * Generate QR code data URL (base64)
   */
  public static async generateQRCodeDataURL(
    data: string,
    options?: {
      color?: string;
      background_color?: string;
      size?: number;
    }
  ): Promise<string> {
    try {
      const qrOptions = {
        quality: 0.92,
        margin: 1,
        color: {
          dark: options?.color || '#000000',
          light: options?.background_color || '#FFFFFF',
        },
        width: options?.size || 256,
      };

      return await QRCode.toDataURL(data, qrOptions);
    } catch (error) {
      console.error('Error generating QR code data URL:', error);
      throw new Error('Failed to generate QR code data URL');
    }
  }

  /**
   * Generate QR code content based on type
   * Uses plain QR code ID (no encryption)
   */
  public static generateQRCodeContent(
    qrcodeId: string,
    type: string,
    title: string,
    typeDetails?: any
  ): string {
    if (type === 'LINK' && typeDetails?.link) {
      return typeDetails.link;
    }

    if (type === 'WIFI' && typeDetails) {
      const ssid = typeDetails.ssid || '';
      const password = typeDetails.password || '';
      const encryption = typeDetails.encryption || 'WPA';
      const hidden = typeDetails.hidden ? 'true' : 'false';
      return `WIFI:T:${encryption};S:${ssid};P:${password};H:${hidden};;`;
    }

    const baseUrl = process.env.FRONTEND_URL || 'http://localhost:8080';

    // Use plain QR code ID in the URL
    return `${baseUrl}/scan-details/${qrcodeId}?qrType=${type}`;
  }

  /**
   * Parse QR code data from scanned content
   * @param qrcodeId - Plain QR code ID from scan
   * @returns Object containing qrcodeId
   */
  public static decryptQRCodeContent(qrcodeId: string): { id: string; type?: string; timestamp?: number } {
    try {
      // Simply return the plain QR code ID
      return {
        id: qrcodeId,
      };
    } catch (error) {
      console.error('Error parsing QR code content:', error);
      throw new Error('Invalid QR code data');
    }
  }

  /**
   * Delete QR code file from file system
   */
  public static async deleteQRCodeFile(filePath: string): Promise<void> {
    try {
      // Use the new FileHandlerUtils for safe file deletion
      const deleted = await FileHandlerUtils.deleteFile(filePath);

      if (!deleted) {
        console.warn(`QR code file not found or could not be deleted: ${filePath}`);
      }
    } catch (error) {
      console.error('Error deleting QR code file:', error);
      // Don't throw error if file doesn't exist
    }
  }

  /**
   * Generate unique filename for QR code
   */
  public static generateFilename(title: string, userId: string): string {
    const timestamp = Date.now();
    const sanitizedTitle = title.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
    return `${sanitizedTitle}-${userId}-${timestamp}`;
  }

  /**
   * Validate QR code expiration
   */
  public static isQRCodeExpired(expiredAt?: Date): boolean {
    if (!expiredAt) return false;
    return new Date() > expiredAt;
  }

  /**
   * Get QR code type display name
   */
  public static getTypeDisplayName(type: string): string {
    const displayNames: Record<string, string> = {
      MEMORY_TAG: 'Memory Tag',
      MEDICAL_QR: 'Medical QR',
      CAR: 'Car',
      LUGGAGE: 'Luggage',
      PET: 'Pet',
      IDENTIFICATIONS: 'Identifications',
      DOCUMENT: 'Document',
      LINK: 'Link',
      WIFI: 'WiFi',
    };

    return displayNames[type] || type;
  }
}
