import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types';

const supabase = createClient<Database>(
  import.meta.env.PUBLIC_SUPABASE_URL,
  import.meta.env.PUBLIC_SUPABASE_ANON_KEY
);

// OpenAI configuration
const OPENAI_API_KEY = import.meta.env.OPENAI_API_KEY;
const OPENAI_API_URL = 'https://api.openai.com/v1/chat/completions';

export interface SocialMediaContent {
  id?: string;
  platform: 'facebook' | 'twitter' | 'instagram' | 'linkedin';
  content: string;
  hashtags: string[];
  image_url?: string;
  tone?: 'professional' | 'casual' | 'exciting' | 'informative' | 'urgent';
  votes?: number;
  generated_at?: string;
}

export async function generateSocialMediaContentWithAI(event: any): Promise<SocialMediaContent[]> {
  if (!OPENAI_API_KEY) {

    return generateFallbackContent(event);
  }

  try {
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });

    const prompt = `Generate 5 varied social media posts for an event with the following details:
Event: ${event.title}
Date: ${eventDate}
Venue: ${event.venue}
Description: ${event.description || 'A special event'}

Please create 5 different posts with these variations:
1. Professional/formal tone for LinkedIn
2. Casual/friendly tone for Facebook  
3. Exciting/energetic tone for Instagram
4. Informative/educational tone
5. Urgent/FOMO (fear of missing out) tone

For each post:
- Keep it concise and engaging
- Include relevant emojis
- Suggest 3-5 relevant hashtags
- Vary the messaging approach
- Make each post unique and platform-appropriate

Format as JSON with an array called "posts", each containing: 
{
  "platform": "facebook|twitter|instagram|linkedin",
  "content": "post text",
  "hashtags": ["tag1", "tag2"],
  "tone": "professional|casual|exciting|informative|urgent"
}`;

    const response = await fetch(OPENAI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: 'You are a social media marketing expert specializing in event promotion. Generate engaging, varied content that drives ticket sales. Always respond with valid JSON.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.9,
        max_tokens: 2000
      })
    });

    if (!response.ok) {
      const error = await response.text();
      throw new Error(`OpenAI API error: ${response.status} - ${error}`);
    }

    const data = await response.json();
    const content = data.choices[0].message.content;
    
    // Parse the JSON response
    let parsedContent;
    try {
      parsedContent = JSON.parse(content);
    } catch (e) {

      return generateFallbackContent(event);
    }
    
    // Extract posts array
    const posts = parsedContent.posts || parsedContent;
    
    // Ensure it's an array
    const postsArray = Array.isArray(posts) ? posts : [posts];
    
    return postsArray.map((post: any, index: number) => ({
      id: `ai-${Date.now()}-${index}`,
      platform: post.platform || 'facebook',
      content: post.content || '',
      hashtags: Array.isArray(post.hashtags) ? post.hashtags : [],
      tone: post.tone || 'professional',
      votes: 0,
      generated_at: new Date().toISOString()
    }));

  } catch (error) {

    return generateFallbackContent(event);
  }
}

function generateFallbackContent(event: any): SocialMediaContent[] {
  const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
  
  const baseHashtags = ['#event', '#tickets', '#liveentertainment'];
  
  return [
    {
      id: `fallback-${Date.now()}-1`,
      platform: 'linkedin',
      content: `We're pleased to announce ${event.title}, taking place on ${eventDate} at ${event.venue}. This exclusive event offers an exceptional opportunity for networking and entertainment. Secure your tickets today.`,
      hashtags: [...baseHashtags, '#networking', '#professional'],
      tone: 'professional',
      votes: 0
    },
    {
      id: `fallback-${Date.now()}-2`,
      platform: 'facebook',
      content: `🎉 Hey everyone! Don't miss out on ${event.title}! Join us on ${eventDate} at ${event.venue} for an unforgettable experience. Grab your tickets now - link in bio! 🎫`,
      hashtags: [...baseHashtags, '#community', '#fun'],
      tone: 'casual',
      votes: 0
    },
    {
      id: `fallback-${Date.now()}-3`,
      platform: 'instagram',
      content: `🔥 IT'S HAPPENING! ${event.title} is coming to ${event.venue}! 🎉✨ Mark your calendars for ${eventDate} - this is THE event you don't want to miss! Limited tickets available! 🎫🏃‍♀️`,
      hashtags: [...baseHashtags, '#instagood', '#eventlife', '#mustattend'],
      tone: 'exciting',
      votes: 0
    },
    {
      id: `fallback-${Date.now()}-4`,
      platform: 'twitter',
      content: `📅 Learn more: ${event.title} features world-class entertainment on ${eventDate} at ${event.venue}. An evening of culture and sophistication awaits. Details: [link]`,
      hashtags: [...baseHashtags, '#culture', '#arts'],
      tone: 'informative',
      votes: 0
    },
    {
      id: `fallback-${Date.now()}-5`,
      platform: 'facebook',
      content: `⏰ LAST CHANCE! Only a few tickets left for ${event.title}! Don't be the one who misses out on the event of the season. ${eventDate} at ${event.venue} - GET YOUR TICKETS NOW! 🎟️💨`,
      hashtags: [...baseHashtags, '#lastchance', '#limitedtickets', '#FOMO'],
      tone: 'urgent',
      votes: 0
    }
  ];
}

export interface EmailTemplate {
  id?: string;
  subject: string;
  html_content: string;
  text_content: string;
  preview_text: string;
  tone?: string;
  votes?: number;
  generated_at?: string;
}

export interface FlyerData {
  id?: string;
  title: string;
  content: string;
  style: string;
  theme: string;
  votes?: number;
  generated_at?: string;
}

// Generate AI-powered email templates
export async function generateEmailTemplatesWithAI(event: any): Promise<EmailTemplate[]> {
  if (!OPENAI_API_KEY) {

    return generateFallbackEmailTemplates(event);
  }

  try {
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });

    const prompt = `Generate 3 different email templates for an event with these details:
Event: ${event.title}
Date: ${eventDate}
Venue: ${event.venue}
Description: ${event.description || 'A special event'}

Create 3 variations with different tones:
1. Professional/corporate tone
2. Friendly/casual tone
3. Urgent/promotional tone

For each email template:
- Create an engaging subject line
- Write a compelling preview text (50-80 characters)
- Generate HTML email content with proper formatting
- Create a text version for accessibility
- Include a clear call-to-action

Format as JSON with an array called "templates", each containing:
{
  "tone": "professional|casual|urgent",
  "subject": "subject line",
  "preview_text": "preview text",
  "html_content": "HTML email content",
  "text_content": "plain text version"
}`;

    const response = await fetch(OPENAI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: 'You are an email marketing expert specializing in event promotion. Create compelling email templates that drive ticket sales and engagement. Always respond with valid JSON.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.8,
        max_tokens: 3000
      })
    });

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices[0].message.content;
    
    let parsedContent;
    try {
      parsedContent = JSON.parse(content);
    } catch (e) {

      return generateFallbackEmailTemplates(event);
    }
    
    const templates = parsedContent.templates || parsedContent;
    const templatesArray = Array.isArray(templates) ? templates : [templates];
    
    return templatesArray.map((template: any, index: number) => ({
      id: `ai-email-${Date.now()}-${index}`,
      subject: template.subject || '',
      html_content: template.html_content || '',
      text_content: template.text_content || '',
      preview_text: template.preview_text || '',
      tone: template.tone || 'professional',
      votes: 0,
      generated_at: new Date().toISOString()
    }));

  } catch (error) {

    return generateFallbackEmailTemplates(event);
  }
}

function generateFallbackEmailTemplates(event: any): EmailTemplate[] {
  const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });

  return [
    {
      id: `fallback-email-${Date.now()}-1`,
      subject: `${event.title} - ${eventDate}`,
      preview_text: `Join us for ${event.title} at ${event.venue}`,
      html_content: `<h1>${event.title}</h1><p>We cordially invite you to ${event.title} on ${eventDate} at ${event.venue}.</p><p>${event.description || 'An exceptional event awaits you.'}</p><a href="#">Reserve Your Tickets</a>`,
      text_content: `${event.title}\n\nWe cordially invite you to ${event.title} on ${eventDate} at ${event.venue}.\n\n${event.description || 'An exceptional event awaits you.'}\n\nReserve Your Tickets: [LINK]`,
      tone: 'professional',
      votes: 0
    },
    {
      id: `fallback-email-${Date.now()}-2`,
      subject: `🎉 Don't miss ${event.title}!`,
      preview_text: `Hey there! ${event.title} is coming up fast`,
      html_content: `<h1>🎉 ${event.title}</h1><p>Hey there! We're so excited to invite you to ${event.title} on ${eventDate} at ${event.venue}.</p><p>${event.description || 'It\'s going to be amazing!'}</p><a href="#">Get Your Tickets Now!</a>`,
      text_content: `🎉 ${event.title}\n\nHey there! We're so excited to invite you to ${event.title} on ${eventDate} at ${event.venue}.\n\n${event.description || 'It\'s going to be amazing!'}\n\nGet Your Tickets Now: [LINK]`,
      tone: 'casual',
      votes: 0
    },
    {
      id: `fallback-email-${Date.now()}-3`,
      subject: `⏰ LAST CHANCE: ${event.title} tickets selling fast!`,
      preview_text: `Limited tickets remaining for ${event.title}`,
      html_content: `<h1>⏰ LAST CHANCE!</h1><p>Limited tickets remaining for ${event.title} on ${eventDate} at ${event.venue}.</p><p>Don't miss out on this exclusive event!</p><a href="#">SECURE YOUR SPOT NOW</a>`,
      text_content: `⏰ LAST CHANCE!\n\nLimited tickets remaining for ${event.title} on ${eventDate} at ${event.venue}.\n\nDon't miss out on this exclusive event!\n\nSECURE YOUR SPOT NOW: [LINK]`,
      tone: 'urgent',
      votes: 0
    }
  ];
}

// Generate AI-powered flyer/asset data
export async function generateFlyerDataWithAI(event: any): Promise<FlyerData[]> {
  if (!OPENAI_API_KEY) {

    return generateFallbackFlyerData(event);
  }

  try {
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });

    const prompt = `Generate 3 different flyer designs for an event:
Event: ${event.title}
Date: ${eventDate}
Venue: ${event.venue}
Description: ${event.description || 'A special event'}

Create 3 variations with different styles:
1. Elegant/sophisticated style
2. Modern/contemporary style
3. Bold/energetic style

For each flyer design:
- Create compelling headline text
- Write engaging body content
- Suggest design theme and colors
- Include style guidelines

Format as JSON with an array called "flyers", each containing:
{
  "style": "elegant|modern|bold",
  "title": "main headline",
  "content": "body content for flyer",
  "theme": "theme description",
  "colors": "color scheme suggestions"
}`;

    const response = await fetch(OPENAI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: 'You are a graphic design expert specializing in event flyers. Create compelling flyer concepts that attract attendees. Always respond with valid JSON.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.8,
        max_tokens: 2000
      })
    });

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices[0].message.content;
    
    let parsedContent;
    try {
      parsedContent = JSON.parse(content);
    } catch (e) {

      return generateFallbackFlyerData(event);
    }
    
    const flyers = parsedContent.flyers || parsedContent;
    const flyersArray = Array.isArray(flyers) ? flyers : [flyers];
    
    return flyersArray.map((flyer: any, index: number) => ({
      id: `ai-flyer-${Date.now()}-${index}`,
      title: flyer.title || event.title,
      content: flyer.content || '',
      style: flyer.style || 'modern',
      theme: flyer.theme || 'Default theme',
      votes: 0,
      generated_at: new Date().toISOString()
    }));

  } catch (error) {

    return generateFallbackFlyerData(event);
  }
}

function generateFallbackFlyerData(event: any): FlyerData[] {
  const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });

  return [
    {
      id: `fallback-flyer-${Date.now()}-1`,
      title: `${event.title}`,
      content: `Join us for an elegant evening on ${eventDate} at ${event.venue}. ${event.description || 'An unforgettable experience awaits.'}`,
      style: 'elegant',
      theme: 'Sophisticated black and gold theme with elegant typography',
      votes: 0
    },
    {
      id: `fallback-flyer-${Date.now()}-2`,
      title: `${event.title}`,
      content: `Experience ${event.title} like never before. ${eventDate} • ${event.venue}. ${event.description || 'Modern entertainment for the contemporary audience.'}`,
      style: 'modern',
      theme: 'Clean minimalist design with bold blues and whites',
      votes: 0
    },
    {
      id: `fallback-flyer-${Date.now()}-3`,
      title: `${event.title.toUpperCase()}`,
      content: `🎉 THE EVENT OF THE YEAR! ${eventDate} at ${event.venue}. ${event.description || 'Get ready for an explosive experience!'}`,
      style: 'bold',
      theme: 'High-energy design with bright colors and dynamic typography',
      votes: 0
    }
  ];
}

// Function to save user vote/preference
export async function saveContentVote(contentId: string, vote: 'up' | 'down'): Promise<void> {
  // In a real implementation, this would save to a database
  // For now, we'll just log it

  // You could store this in localStorage for learning
  const votes = JSON.parse(localStorage.getItem('marketing_content_votes') || '{}');
  votes[contentId] = vote;
  localStorage.setItem('marketing_content_votes', JSON.stringify(votes));
}

// Function to get voting data for learning
export function getVotingData(): Record<string, 'up' | 'down'> {
  return JSON.parse(localStorage.getItem('marketing_content_votes') || '{}');
}

// Generate a single new social media post for a specific platform
export async function regenerateSocialMediaPost(event: any, platform: string, tone?: string): Promise<SocialMediaContent | null> {
  if (!OPENAI_API_KEY) {

    return generateFallbackSocialPost(event, platform, tone);
  }

  try {
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });

    const selectedTone = tone || 'engaging';
    
    const prompt = `Generate a new social media post for ${platform} with the following details:
Event: ${event.title}
Date: ${eventDate}
Venue: ${event.venue}
Description: ${event.description || 'A special event'}

Create a ${selectedTone} post that:
- Is optimized for ${platform}
- Uses a ${selectedTone} tone
- Includes relevant emojis
- Has a clear call-to-action
- Is different from previous attempts (be creative and unique)
- Suggests 3-5 relevant hashtags

Format as JSON with:
{
  "platform": "${platform}",
  "content": "post text with emojis",
  "hashtags": ["#tag1", "#tag2", "#tag3"],
  "tone": "${selectedTone}"
}`;

    const response = await fetch(OPENAI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: `You are a social media expert specializing in ${platform} content. Create engaging, platform-specific posts that drive ticket sales. Always respond with valid JSON.`
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.9, // Higher temperature for more creativity
        max_tokens: 500
      })
    });

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices[0].message.content;
    
    let parsedContent;
    try {
      parsedContent = JSON.parse(content);
    } catch (e) {

      return generateFallbackSocialPost(event, platform, tone);
    }
    
    return {
      id: `ai-regen-${Date.now()}`,
      platform: parsedContent.platform || platform,
      content: parsedContent.content || '',
      hashtags: Array.isArray(parsedContent.hashtags) ? parsedContent.hashtags : [],
      tone: parsedContent.tone || selectedTone,
      votes: 0,
      generated_at: new Date().toISOString()
    };

  } catch (error) {

    return generateFallbackSocialPost(event, platform, tone);
  }
}

function generateFallbackSocialPost(event: any, platform: string, tone?: string): SocialMediaContent {
  const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });

  const fallbackContent = {
    facebook: `🎉 Join us for ${event.title} on ${eventDate} at ${event.venue}! This is going to be an incredible experience. Get your tickets now!`,
    twitter: `🎫 ${event.title} - ${eventDate} at ${event.venue}. Don't miss out! Tickets available now.`,
    instagram: `✨ ${event.title} ✨\n📅 ${eventDate}\n📍 ${event.venue}\n\nThis is THE event you've been waiting for! 🎟️`,
    linkedin: `We're excited to announce ${event.title} on ${eventDate} at ${event.venue}. Join us for this professional networking and entertainment event.`
  };

  return {
    id: `fallback-regen-${Date.now()}`,
    platform: platform as any,
    content: fallbackContent[platform as keyof typeof fallbackContent] || fallbackContent.facebook,
    hashtags: ['#event', '#tickets', '#liveentertainment'],
    tone: tone || 'engaging',
    votes: 0,
    generated_at: new Date().toISOString()
  };
}

// Generate a single new email template
export async function regenerateEmailTemplate(event: any, tone: string): Promise<EmailTemplate | null> {
  if (!OPENAI_API_KEY) {

    return generateFallbackEmailTemplate(event, tone);
  }

  try {
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });

    const prompt = `Generate a new email template with a ${tone} tone for this event:
Event: ${event.title}
Date: ${eventDate}
Venue: ${event.venue}
Description: ${event.description || 'A special event'}

Create a ${tone} email template that:
- Has an engaging subject line
- Includes compelling preview text (50-80 characters)
- Contains HTML email content with proper formatting
- Has a plain text version for accessibility
- Is different from previous attempts (be creative and unique)
- Includes a clear call-to-action

Format as JSON with:
{
  "tone": "${tone}",
  "subject": "subject line",
  "preview_text": "preview text",
  "html_content": "HTML email content",
  "text_content": "plain text version"
}`;

    const response = await fetch(OPENAI_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [
          {
            role: 'system',
            content: 'You are an email marketing expert. Create compelling email templates that drive engagement and ticket sales. Always respond with valid JSON.'
          },
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.9,
        max_tokens: 2000
      })
    });

    if (!response.ok) {
      throw new Error(`OpenAI API error: ${response.status}`);
    }

    const data = await response.json();
    const content = data.choices[0].message.content;
    
    let parsedContent;
    try {
      parsedContent = JSON.parse(content);
    } catch (e) {

      return generateFallbackEmailTemplate(event, tone);
    }
    
    return {
      id: `ai-email-regen-${Date.now()}`,
      subject: parsedContent.subject || '',
      html_content: parsedContent.html_content || '',
      text_content: parsedContent.text_content || '',
      preview_text: parsedContent.preview_text || '',
      tone: parsedContent.tone || tone,
      votes: 0,
      generated_at: new Date().toISOString()
    };

  } catch (error) {

    return generateFallbackEmailTemplate(event, tone);
  }
}

function generateFallbackEmailTemplate(event: any, tone: string): EmailTemplate {
  const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });

  const templates = {
    professional: {
      subject: `${event.title} - ${eventDate}`,
      preview_text: `Join us for ${event.title} at ${event.venue}`,
      html_content: `<h1>${event.title}</h1><p>We cordially invite you to ${event.title} on ${eventDate} at ${event.venue}.</p><p>${event.description || 'An exceptional event awaits you.'}</p><a href="#">Reserve Your Tickets</a>`,
      text_content: `${event.title}\n\nWe cordially invite you to ${event.title} on ${eventDate} at ${event.venue}.\n\n${event.description || 'An exceptional event awaits you.'}\n\nReserve Your Tickets: [LINK]`
    },
    casual: {
      subject: `🎉 Don't miss ${event.title}!`,
      preview_text: `Hey there! ${event.title} is coming up fast`,
      html_content: `<h1>🎉 ${event.title}</h1><p>Hey there! We're so excited to invite you to ${event.title} on ${eventDate} at ${event.venue}.</p><p>${event.description || 'It\'s going to be amazing!'}</p><a href="#">Get Your Tickets Now!</a>`,
      text_content: `🎉 ${event.title}\n\nHey there! We're so excited to invite you to ${event.title} on ${eventDate} at ${event.venue}.\n\n${event.description || 'It\'s going to be amazing!'}\n\nGet Your Tickets Now: [LINK]`
    },
    urgent: {
      subject: `⏰ LAST CHANCE: ${event.title} tickets selling fast!`,
      preview_text: `Limited tickets remaining for ${event.title}`,
      html_content: `<h1>⏰ LAST CHANCE!</h1><p>Limited tickets remaining for ${event.title} on ${eventDate} at ${event.venue}.</p><p>Don't miss out on this exclusive event!</p><a href="#">SECURE YOUR SPOT NOW</a>`,
      text_content: `⏰ LAST CHANCE!\n\nLimited tickets remaining for ${event.title} on ${eventDate} at ${event.venue}.\n\nDon't miss out on this exclusive event!\n\nSECURE YOUR SPOT NOW: [LINK]`
    }
  };

  const template = templates[tone as keyof typeof templates] || templates.professional;
  
  return {
    id: `fallback-email-regen-${Date.now()}`,
    subject: template.subject,
    html_content: template.html_content,
    text_content: template.text_content,
    preview_text: template.preview_text,
    tone,
    votes: 0,
    generated_at: new Date().toISOString()
  };
}