import type { APIRoute } from 'astro';
import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

export const POST: APIRoute = async ({ request }) => {
  try {
    const { event, pin, email, type = 'immediate' } = await request.json();
    
    if (!event || !pin || !email) {
      return new Response(JSON.stringify({ error: 'Missing required fields' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    // Validate PIN format
    if (!/^\d{4}$/.test(pin)) {
      return new Response(JSON.stringify({ error: 'Invalid PIN format' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    const eventDate = new Date(event.start_time).toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
    
    const eventTime = new Date(event.start_time).toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true
    });
    
    let subject: string;
    let htmlContent: string;
    
    if (type === 'immediate') {
      subject = `Scanner Lock PIN for ${event.title}`;
      htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>Scanner Lock PIN</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
          <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 10px; text-align: center; margin-bottom: 30px;">
            <h1 style="margin: 0; font-size: 28px;">🔒 Scanner Lock PIN</h1>
            <p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">Black Canyon Tickets</p>
          </div>
          
          <div style="background: #f8f9fa; padding: 25px; border-radius: 10px; margin-bottom: 25px;">
            <h2 style="color: #667eea; margin: 0 0 15px 0;">Your Scanner Access PIN</h2>
            <p style="margin: 0 0 15px 0;">Your scanner has been locked for the event:</p>
            <p style="font-weight: bold; font-size: 18px; margin: 0 0 15px 0; color: #333;">${event.title}</p>
            <p style="margin: 0 0 15px 0;">Date: ${eventDate} at ${eventTime}</p>
            
            <div style="background: white; border: 2px solid #667eea; border-radius: 8px; padding: 20px; text-align: center; margin: 20px 0;">
              <p style="margin: 0 0 10px 0; font-size: 16px;">Your PIN is:</p>
              <div style="font-size: 32px; font-weight: bold; font-family: monospace; color: #667eea; letter-spacing: 8px;">${pin}</div>
            </div>
            
            <p style="margin: 15px 0 0 0; font-size: 14px; color: #666;">
              Use this PIN to unlock your scanner if you need to exit scan-only mode.
            </p>
          </div>
          
          <div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin-bottom: 25px;">
            <h3 style="color: #856404; margin: 0 0 10px 0;">Important Security Information</h3>
            <ul style="margin: 0; padding-left: 20px; color: #856404;">
              <li>Keep this PIN secure and do not share it with unauthorized personnel</li>
              <li>The scanner is now locked to scan-only mode for security</li>
              <li>You will receive a reminder email when your event starts</li>
              <li>The PIN will be required to unlock and return to normal portal access</li>
            </ul>
          </div>
          
          <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
            <p style="margin: 0; font-size: 14px; color: #666;">
              Sent by Black Canyon Tickets Scanner Lock System<br>
              <a href="https://portal.blackcanyontickets.com" style="color: #667eea;">portal.blackcanyontickets.com</a>
            </p>
          </div>
        </body>
        </html>
      `;
    } else {
      // Reminder email
      subject = `Reminder: Scanner Lock PIN for ${event.title}`;
      htmlContent = `
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>Scanner Lock PIN Reminder</title>
        </head>
        <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
          <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 10px; text-align: center; margin-bottom: 30px;">
            <h1 style="margin: 0; font-size: 28px;">🔔 Scanner PIN Reminder</h1>
            <p style="margin: 10px 0 0 0; font-size: 16px; opacity: 0.9;">Your Event is Starting Soon</p>
          </div>
          
          <div style="background: #f8f9fa; padding: 25px; border-radius: 10px; margin-bottom: 25px;">
            <h2 style="color: #667eea; margin: 0 0 15px 0;">Scanner Lock PIN Reminder</h2>
            <p style="margin: 0 0 15px 0;">Your event is starting! Here's your scanner PIN in case you need to unlock your device:</p>
            <p style="font-weight: bold; font-size: 18px; margin: 0 0 15px 0; color: #333;">${event.title}</p>
            <p style="margin: 0 0 15px 0;">Date: ${eventDate} at ${eventTime}</p>
            
            <div style="background: white; border: 2px solid #667eea; border-radius: 8px; padding: 20px; text-align: center; margin: 20px 0;">
              <p style="margin: 0 0 10px 0; font-size: 16px;">Your PIN is:</p>
              <div style="font-size: 32px; font-weight: bold; font-family: monospace; color: #667eea; letter-spacing: 8px;">${pin}</div>
            </div>
            
            <p style="margin: 15px 0 0 0; font-size: 14px; color: #666;">
              Use this PIN to unlock your scanner if you need to exit scan-only mode during the event.
            </p>
          </div>
          
          <div style="background: #e8f5e8; border: 1px solid #c3e6c3; border-radius: 8px; padding: 20px; margin-bottom: 25px;">
            <h3 style="color: #2d5a2d; margin: 0 0 10px 0;">Event Day Reminders</h3>
            <ul style="margin: 0; padding-left: 20px; color: #2d5a2d;">
              <li>Your scanner is locked and ready for secure ticket scanning</li>
              <li>Staff can only scan tickets - no other portal access</li>
              <li>Use the PIN above to unlock if you need administrative access</li>
              <li>Keep the PIN secure throughout the event</li>
            </ul>
          </div>
          
          <div style="text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
            <p style="margin: 0; font-size: 14px; color: #666;">
              Sent by Black Canyon Tickets Scanner Lock System<br>
              <a href="https://portal.blackcanyontickets.com" style="color: #667eea;">portal.blackcanyontickets.com</a>
            </p>
          </div>
        </body>
        </html>
      `;
    }
    
    // Send email
    const { data, error } = await resend.emails.send({
      from: 'Scanner Lock <scanner@blackcanyontickets.com>',
      to: [email],
      subject,
      html: htmlContent
    });
    
    if (error) {

      return new Response(JSON.stringify({ error: 'Failed to send email' }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
    
    return new Response(JSON.stringify({ 
      success: true, 
      emailId: data?.id,
      message: 'Email sent successfully' 
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
    
  } catch (error) {

    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};