import { supabase } from './supabase';
import { qrGenerator } from './qr-generator';
import { socialMediaGenerator } from './social-media-generator';
import { emailTemplateGenerator } from './email-template-generator';
import { flyerGenerator } from './flyer-generator';
import { fileStorageService } from './file-storage-service';

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;
  contact_email?: string;
  organization_id: string;
  organizations: {
    name: string;
    logo?: string;
    social_links?: any;
    website_url?: string;
  };
}

interface MarketingAsset {
  id?: string;
  asset_type: string;
  platform?: string;
  title: string;
  content?: string;
  image_url?: string;
  download_url?: string;
  file_format: string;
  dimensions?: any;
  metadata?: any;
}

class MarketingKitService {
  /**
   * Generate complete marketing kit for an event
   */
  async generateCompleteKit(event: EventData, organizationId: string, userId: string) {
    try {
      // Start kit generation record
      const { data: kitGeneration, error: kitError } = await supabase
        .from('marketing_kit_generations')
        .insert({
          event_id: event.id,
          organization_id: organizationId,
          generated_by: userId,
          generation_type: 'full_kit',
          assets_included: ['social_post', 'flyer', 'email_template', 'qr_code'],
          generation_status: 'processing'
        })
        .select()
        .single();

      if (kitError) {
        throw new Error('Failed to start kit generation');
      }

      const assets: MarketingAsset[] = [];

      // 1. Generate QR Code first (needed for other assets)
      const qrCodes = await this.generateQRCodes(event);
      assets.push(...qrCodes);

      // 2. Generate Social Media Posts
      const socialPosts = await this.generateSocialMediaPosts(event);
      assets.push(...socialPosts);

      // 3. Generate Flyer/Poster
      const flyers = await this.generateFlyers(event);
      assets.push(...flyers);

      // 4. Generate Email Templates
      const emailTemplates = await this.generateEmailTemplates(event);
      assets.push(...emailTemplates);

      // Save all assets to database
      const savedAssets = await this.saveAssetsToDatabase(assets, event.id, organizationId);

      // Create ZIP file with all assets
      const zipUrl = await this.createZipDownload(savedAssets, event);

      // Update kit generation with success
      await supabase
        .from('marketing_kit_generations')
        .update({
          generation_status: 'completed',
          zip_file_url: zipUrl,
          zip_expires_at: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() // 7 days
        })
        .eq('id', kitGeneration.id);

      return {
        event,
        assets: this.groupAssetsByType(savedAssets),
        zip_download_url: zipUrl,
        generated_at: new Date().toISOString(),
        generation_id: kitGeneration.id
      };

    } catch (error) {

      throw error;
    }
  }

  /**
   * Generate specific asset types only
   */
  async generateSpecificAssets(
    event: EventData, 
    organizationId: string, 
    userId: string, 
    assetTypes: string[]
  ) {
    const assets: MarketingAsset[] = [];

    for (const assetType of assetTypes) {
      switch (assetType) {
        case 'qr_code':
          assets.push(...await this.generateQRCodes(event));
          break;
        case 'social_post':
          assets.push(...await this.generateSocialMediaPosts(event));
          break;
        case 'flyer':
          assets.push(...await this.generateFlyers(event));
          break;
        case 'email_template':
          assets.push(...await this.generateEmailTemplates(event));
          break;
      }
    }

    const savedAssets = await this.saveAssetsToDatabase(assets, event.id, organizationId);

    return {
      event,
      assets: this.groupAssetsByType(savedAssets),
      generated_at: new Date().toISOString()
    };
  }

  /**
   * Generate QR codes for different use cases
   */
  private async generateQRCodes(event: EventData): Promise<MarketingAsset[]> {
    const ticketUrl = `${import.meta.env.PUBLIC_SITE_URL || 'https://portal.blackcanyontickets.com'}/e/${event.slug}`;
    
    const qrCodes = await qrGenerator.generateMultiFormat(ticketUrl);
    
    return [
      {
        asset_type: 'qr_code',
        title: 'QR Code - Social Media',
        content: qrCodes.social.dataUrl,
        file_format: 'png',
        dimensions: { width: qrCodes.social.size, height: qrCodes.social.size },
        metadata: { url: ticketUrl, use_case: 'social' }
      },
      {
        asset_type: 'qr_code',
        title: 'QR Code - Print/Flyer',
        content: qrCodes.print.dataUrl,
        file_format: 'png',
        dimensions: { width: qrCodes.print.size, height: qrCodes.print.size },
        metadata: { url: ticketUrl, use_case: 'print' }
      },
      {
        asset_type: 'qr_code',
        title: 'QR Code - Email',
        content: qrCodes.email.dataUrl,
        file_format: 'png',
        dimensions: { width: qrCodes.email.size, height: qrCodes.email.size },
        metadata: { url: ticketUrl, use_case: 'email' }
      }
    ];
  }

  /**
   * Generate social media posts for different platforms
   */
  private async generateSocialMediaPosts(event: EventData): Promise<MarketingAsset[]> {
    const platforms = ['facebook', 'instagram', 'twitter', 'linkedin'];
    const posts: MarketingAsset[] = [];

    for (const platform of platforms) {
      const post = await socialMediaGenerator.generatePost(event, platform);
      posts.push({
        asset_type: 'social_post',
        platform,
        title: `${platform} Post - ${event.title}`,
        content: post.text,
        image_url: post.imageUrl,
        file_format: 'png',
        dimensions: post.dimensions,
        metadata: {
          hashtags: post.hashtags,
          social_links: event.social_links || event.organizations.social_links,
          platform_specific: post.platformSpecific
        }
      });
    }

    return posts;
  }

  /**
   * Generate flyers and posters
   */
  private async generateFlyers(event: EventData): Promise<MarketingAsset[]> {
    const flyers = await flyerGenerator.generateFlyers(event);
    
    return flyers.map(flyer => ({
      asset_type: 'flyer',
      title: flyer.title,
      image_url: flyer.imageUrl,
      file_format: 'png',
      dimensions: flyer.dimensions,
      metadata: {
        style: flyer.style,
        includes_qr: true,
        includes_logo: !!event.organizations.logo
      }
    }));
  }

  /**
   * Generate email campaign templates
   */
  private async generateEmailTemplates(event: EventData): Promise<MarketingAsset[]> {
    const templates = await emailTemplateGenerator.generateTemplates(event);
    
    return templates.map(template => ({
      asset_type: 'email_template',
      title: template.title,
      content: template.html,
      file_format: 'html',
      metadata: {
        subject: template.subject,
        preview_text: template.previewText,
        includes_qr: true,
        cta_text: template.ctaText
      }
    }));
  }

  /**
   * Save generated assets to database
   */
  private async saveAssetsToDatabase(
    assets: MarketingAsset[], 
    eventId: string, 
    organizationId: string
  ): Promise<any[]> {
    const assetsToInsert = assets.map(asset => ({
      event_id: eventId,
      organization_id: organizationId,
      asset_type: asset.asset_type,
      platform: asset.platform,
      title: asset.title,
      content: asset.content,
      image_url: asset.image_url,
      file_format: asset.file_format,
      dimensions: asset.dimensions,
      metadata: asset.metadata,
      generated_at: new Date().toISOString(),
      is_active: true
    }));

    const { data: savedAssets, error } = await supabase
      .from('marketing_kit_assets')
      .insert(assetsToInsert)
      .select();

    if (error) {
      throw new Error(`Failed to save assets: ${error.message}`);
    }

    return savedAssets || [];
  }

  /**
   * Create ZIP download with all assets
   */
  private async createZipDownload(assets: any[], event: EventData): Promise<string> {
    // This would typically use a file storage service to create a ZIP
    // For now, we'll create a placeholder URL
    // In production, you'd use something like AWS S3, Google Cloud Storage, etc.
    
    const zipFileName = `${event.slug}-marketing-kit-${Date.now()}.zip`;
    
    // TODO: Implement actual ZIP creation and upload
    // const zipBuffer = await this.createZipBuffer(assets);
    // const zipUrl = await fileStorageService.uploadFile(zipBuffer, zipFileName);
    
    // For now, return a placeholder
    const zipUrl = `/api/events/${event.id}/marketing-kit/download`;
    
    return zipUrl;
  }

  /**
   * Group assets by type for organized display
   */
  private groupAssetsByType(assets: any[]) {
    return assets.reduce((acc, asset) => {
      if (!acc[asset.asset_type]) {
        acc[asset.asset_type] = [];
      }
      acc[asset.asset_type].push(asset);
      return acc;
    }, {});
  }

  /**
   * Get existing marketing kit for an event
   */
  async getExistingKit(eventId: string, organizationId: string) {
    const { data: assets, error } = await supabase
      .from('marketing_kit_assets')
      .select('*')
      .eq('event_id', eventId)
      .eq('organization_id', organizationId)
      .eq('is_active', true)
      .order('generated_at', { ascending: false });

    if (error) {
      throw new Error(`Failed to fetch marketing kit: ${error.message}`);
    }

    return {
      assets: this.groupAssetsByType(assets || []),
      generated_at: assets?.[0]?.generated_at
    };
  }

  /**
   * Delete marketing kit assets
   */
  async deleteKit(eventId: string, organizationId: string) {
    const { error } = await supabase
      .from('marketing_kit_assets')
      .update({ is_active: false })
      .eq('event_id', eventId)
      .eq('organization_id', organizationId);

    if (error) {
      throw new Error(`Failed to delete marketing kit: ${error.message}`);
    }

    return { success: true };
  }
}

export const marketingKitService = new MarketingKitService();