import { canvasImageGenerator } from './canvas-image-generator';
import { qrGenerator } from './qr-generator';

interface FlyerDesign {
  title: string;
  imageUrl: string;
  dimensions: { width: number; height: number };
  style: string;
}

interface EventData {
  id: string;
  title: string;
  description: string;
  venue: string;
  start_time: string;
  end_time: string;
  slug: string;
  image_url?: string;
  social_links?: any;
  website_url?: string;
  organizations: {
    name: string;
    logo?: string;
    social_links?: any;
    website_url?: string;
  };
}

class FlyerGenerator {
  private flyerDimensions = {
    poster: { width: 1080, height: 1350 }, // 4:5 ratio - good for printing
    social: { width: 1080, height: 1080 }, // Square - good for Instagram
    story: { width: 1080, height: 1920 }, // 9:16 ratio - good for stories
    landscape: { width: 1920, height: 1080 }, // 16:9 ratio - good for digital displays
    a4: { width: 2480, height: 3508 } // A4 size for high-quality printing
  };

  /**
   * Generate multiple flyer designs for the event
   */
  async generateFlyers(event: EventData): Promise<FlyerDesign[]> {
    const flyers: FlyerDesign[] = [];

    // Generate QR code for flyers
    const qrCode = await qrGenerator.generateEventQR(event.slug, {
      size: 300,
      color: { dark: '#000000', light: '#FFFFFF' }
    });

    // Generate different styles and formats
    const styles = ['modern', 'classic', 'minimal'];
    const formats = ['poster', 'social', 'landscape'];

    for (const style of styles) {
      for (const format of formats) {
        const dimensions = this.flyerDimensions[format];
        const flyer = await this.generateFlyer(event, style, format, dimensions, qrCode.dataUrl);
        flyers.push(flyer);
      }
    }

    // Generate high-resolution print version
    const printFlyer = await this.generateFlyer(
      event, 
      'modern', 
      'a4', 
      this.flyerDimensions.a4, 
      qrCode.dataUrl
    );
    flyers.push(printFlyer);

    return flyers;
  }

  /**
   * Generate a single flyer design
   */
  private async generateFlyer(
    event: EventData,
    style: string,
    format: string,
    dimensions: { width: number; height: number },
    qrCodeDataUrl: string
  ): Promise<FlyerDesign> {
    const config = {
      width: dimensions.width,
      height: dimensions.height,
      style: style as 'modern' | 'classic' | 'minimal',
      event,
      qrCode: qrCodeDataUrl,
      backgroundColor: this.getStyleColors(style).backgroundColor,
      textColor: this.getStyleColors(style).textColor,
      accentColor: this.getStyleColors(style).accentColor
    };

    const imageUrl = await canvasImageGenerator.generateFlyer(config);

    return {
      title: `${this.capitalizeFirst(style)} ${this.capitalizeFirst(format)} Flyer`,
      imageUrl,
      dimensions,
      style
    };
  }

  /**
   * Get color scheme for different styles
   */
  private getStyleColors(style: string) {
    const colorSchemes = {
      modern: {
        backgroundColor: ['#667eea', '#764ba2'], // Purple gradient
        textColor: '#FFFFFF',
        accentColor: '#FF6B6B'
      },
      classic: {
        backgroundColor: ['#2C3E50', '#34495E'], // Dark blue gradient
        textColor: '#FFFFFF',
        accentColor: '#E74C3C'
      },
      minimal: {
        backgroundColor: '#FFFFFF',
        textColor: '#2C3E50',
        accentColor: '#3498DB'
      },
      elegant: {
        backgroundColor: ['#232526', '#414345'], // Dark gradient
        textColor: '#F8F9FA',
        accentColor: '#FD79A8'
      },
      vibrant: {
        backgroundColor: ['#FF6B6B', '#4ECDC4'], // Coral to teal
        textColor: '#FFFFFF',
        accentColor: '#45B7D1'
      }
    };

    return colorSchemes[style] || colorSchemes.modern;
  }

  /**
   * Generate themed flyer sets
   */
  async generateThemedSet(event: EventData, theme: string): Promise<FlyerDesign[]> {
    const flyers: FlyerDesign[] = [];
    
    // Generate QR code
    const qrCode = await qrGenerator.generateEventQR(event.slug, {
      size: 300,
      color: { dark: '#000000', light: '#FFFFFF' }
    });

    const themeConfig = this.getThemeConfig(theme, event);
    
    // Generate different formats for the theme
    for (const [formatName, dimensions] of Object.entries(this.flyerDimensions)) {
      if (formatName === 'story') continue; // Skip story format for themed sets
      
      const config = {
        width: dimensions.width,
        height: dimensions.height,
        style: themeConfig.style,
        event,
        qrCode: qrCode.dataUrl,
        backgroundColor: themeConfig.colors.backgroundColor,
        textColor: themeConfig.colors.textColor,
        accentColor: themeConfig.colors.accentColor
      };

      const imageUrl = await canvasImageGenerator.generateFlyer(config);

      flyers.push({
        title: `${this.capitalizeFirst(theme)} ${this.capitalizeFirst(formatName)} Flyer`,
        imageUrl,
        dimensions,
        style: theme
      });
    }

    return flyers;
  }

  /**
   * Get theme-specific configuration
   */
  private getThemeConfig(theme: string, event: EventData) {
    const themes = {
      corporate: {
        style: 'minimal' as const,
        colors: {
          backgroundColor: '#FFFFFF',
          textColor: '#2C3E50',
          accentColor: '#3498DB'
        }
      },
      party: {
        style: 'modern' as const,
        colors: {
          backgroundColor: ['#FF6B6B', '#4ECDC4'],
          textColor: '#FFFFFF',
          accentColor: '#FFD93D'
        }
      },
      wedding: {
        style: 'classic' as const,
        colors: {
          backgroundColor: ['#F8BBD9', '#E8F5E8'],
          textColor: '#2C3E50',
          accentColor: '#E91E63'
        }
      },
      concert: {
        style: 'modern' as const,
        colors: {
          backgroundColor: ['#000000', '#434343'],
          textColor: '#FFFFFF',
          accentColor: '#FF0080'
        }
      },
      gala: {
        style: 'classic' as const,
        colors: {
          backgroundColor: ['#232526', '#414345'],
          textColor: '#F8F9FA',
          accentColor: '#FFD700'
        }
      }
    };

    return themes[theme] || themes.corporate;
  }

  /**
   * Generate social media story versions
   */
  async generateStoryFlyers(event: EventData): Promise<FlyerDesign[]> {
    const storyFlyers: FlyerDesign[] = [];
    
    // Generate QR code optimized for mobile
    const qrCode = await qrGenerator.generateEventQR(event.slug, {
      size: 250,
      color: { dark: '#000000', light: '#FFFFFF' }
    });

    const storyStyles = ['modern', 'vibrant', 'elegant'];
    
    for (const style of storyStyles) {
      const colors = this.getStyleColors(style);
      const config = {
        width: this.flyerDimensions.story.width,
        height: this.flyerDimensions.story.height,
        style: style as 'modern' | 'classic' | 'minimal',
        event,
        qrCode: qrCode.dataUrl,
        backgroundColor: colors.backgroundColor,
        textColor: colors.textColor,
        accentColor: colors.accentColor
      };

      const imageUrl = await canvasImageGenerator.generateFlyer(config);

      storyFlyers.push({
        title: `${this.capitalizeFirst(style)} Story Flyer`,
        imageUrl,
        dimensions: this.flyerDimensions.story,
        style
      });
    }

    return storyFlyers;
  }

  /**
   * Generate print-ready flyers with bleed
   */
  async generatePrintFlyers(event: EventData): Promise<FlyerDesign[]> {
    const printFlyers: FlyerDesign[] = [];
    
    // Generate high-resolution QR code for print
    const qrCode = await qrGenerator.generateEventQR(event.slug, {
      size: 600, // High resolution for print
      color: { dark: '#000000', light: '#FFFFFF' }
    });

    // A4 with bleed (A4 + 3mm bleed on each side)
    const a4WithBleed = { width: 2551, height: 3579 };
    
    // US Letter with bleed
    const letterWithBleed = { width: 2551, height: 3301 };

    const printSizes = [
      { name: 'A4 with Bleed', dimensions: a4WithBleed },
      { name: 'US Letter with Bleed', dimensions: letterWithBleed },
      { name: 'Poster 11x17', dimensions: { width: 3300, height: 5100 } },
      { name: 'Poster 18x24', dimensions: { width: 5400, height: 7200 } }
    ];

    for (const size of printSizes) {
      const colors = this.getStyleColors('modern');
      const config = {
        width: size.dimensions.width,
        height: size.dimensions.height,
        style: 'modern' as const,
        event,
        qrCode: qrCode.dataUrl,
        backgroundColor: colors.backgroundColor,
        textColor: colors.textColor,
        accentColor: colors.accentColor
      };

      const imageUrl = await canvasImageGenerator.generateFlyer(config);

      printFlyers.push({
        title: `Print Ready - ${size.name}`,
        imageUrl,
        dimensions: size.dimensions,
        style: 'print'
      });
    }

    return printFlyers;
  }

  /**
   * Get recommended flyer formats for event type
   */
  getRecommendedFormats(eventType: string): string[] {
    const recommendations = {
      conference: ['poster', 'landscape', 'a4'],
      wedding: ['poster', 'social', 'story'],
      concert: ['poster', 'social', 'story', 'landscape'],
      gala: ['poster', 'social', 'a4'],
      workshop: ['poster', 'landscape'],
      party: ['social', 'story', 'poster'],
      corporate: ['landscape', 'poster', 'a4']
    };

    return recommendations[eventType] || ['poster', 'social', 'landscape'];
  }

  /**
   * Capitalize first letter of a string
   */
  private capitalizeFirst(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  /**
   * Get optimal image dimensions for different use cases
   */
  getOptimalDimensions(useCase: string): { width: number; height: number } {
    return this.flyerDimensions[useCase] || this.flyerDimensions.poster;
  }

  /**
   * Generate custom flyer with specific requirements
   */
  async generateCustomFlyer(
    event: EventData,
    requirements: {
      width: number;
      height: number;
      style: string;
      colors?: any;
      includeQR?: boolean;
      includeLogo?: boolean;
    }
  ): Promise<FlyerDesign> {
    let qrCodeDataUrl = '';
    
    if (requirements.includeQR !== false) {
      const qrCode = await qrGenerator.generateEventQR(event.slug, {
        size: Math.min(requirements.width / 6, 300),
        color: { dark: '#000000', light: '#FFFFFF' }
      });
      qrCodeDataUrl = qrCode.dataUrl;
    }

    const colors = requirements.colors || this.getStyleColors(requirements.style);
    
    const config = {
      width: requirements.width,
      height: requirements.height,
      style: requirements.style as 'modern' | 'classic' | 'minimal',
      event,
      qrCode: qrCodeDataUrl,
      backgroundColor: colors.backgroundColor,
      textColor: colors.textColor,
      accentColor: colors.accentColor
    };

    const imageUrl = await canvasImageGenerator.generateFlyer(config);

    return {
      title: `Custom ${requirements.style} Flyer`,
      imageUrl,
      dimensions: { width: requirements.width, height: requirements.height },
      style: requirements.style
    };
  }
}

export const flyerGenerator = new FlyerGenerator();