import { createAdminClient } from "@/lib/supabase/admin"
import { Resend } from "resend"

// Initialize Resend client
const resend = process.env.RESEND_API_KEY ? new Resend(process.env.RESEND_API_KEY) : null

export async function sendOrderEmail(orderId: string, eventId: string) {
  console.log("[EMAIL] Starting email send process for orderId:", orderId, "eventId:", eventId)
  
  try {
    if (!orderId || !eventId) {
      throw new Error("Missing orderId or eventId")
    }

    // Check if Resend is configured
    if (!resend) {
      console.warn("[EMAIL] ⚠️ RESEND_API_KEY not configured!")
      return {
        success: false,
        message: "Email service not configured. Please set RESEND_API_KEY environment variable.",
      }
    }

    console.log("[EMAIL] Resend client initialized, fetching order data...")
    const supabase = createAdminClient()

    // Fetch order details
    const { data: order, error: orderError } = await supabase
      .from("orders")
      .select("*")
      .eq("id", orderId)
      .eq("event_id", eventId)
      .single()

    if (orderError || !order) {
      console.error("[EMAIL] ❌ Order not found:", orderError)
      throw new Error("Order not found")
    }

    console.log("[EMAIL] Order found, customer email:", order.customer_email)

    // Fetch event details
    const { data: event } = await supabase
      .from("events")
      .select("name, event_date, end_date, location, currency")
      .eq("id", eventId)
      .single()

    console.log("[EMAIL] Event found:", event?.name)

    // Fetch tickets
    const { data: orderTickets } = await supabase.from("order_tickets").select("*").eq("order_id", orderId)

    // Fetch chits
    const { data: chits } = await supabase.from("chits").select("*").eq("order_id", orderId)

    console.log("[EMAIL] Tickets:", orderTickets?.length || 0, "Chits:", chits?.length || 0)

    const tickets = orderTickets || []
    const chitItems = chits || []

    // Format date
    const eventDate = event?.event_date
      ? new Date(event.event_date).toLocaleDateString("en-US", {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric",
        })
      : "TBA"

    // Get base URL for email links
    const baseUrl =
      process.env.NEXT_PUBLIC_APP_URL ||
      (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "https://tikkets.com")

    // Generate the email HTML
    const emailHtml = generateEmailHtml({
      order,
      event,
      tickets,
      chits: chitItems,
      eventDate,
      eventId,
      baseUrl,
    })

    // Send email using Resend
    if (!resend) {
      console.warn("[v0] RESEND_API_KEY not configured. Email not sent. Would send to:", order.customer_email)
      return {
        success: false,
        message: "Email service not configured. Please set RESEND_API_KEY environment variable.",
      }
    }

    const fromEmail = process.env.RESEND_FROM_EMAIL || "noreply@tikkets.com"
    const emailSubject = `Your Tikkets for ${event?.name || "Event"}`

    console.log("[EMAIL] 📧 Sending email via Resend...")
    console.log("[EMAIL] From:", fromEmail)
    console.log("[EMAIL] To:", order.customer_email)
    console.log("[EMAIL] Subject:", emailSubject)

    const { data, error: resendError } = await resend.emails.send({
      from: fromEmail,
      to: order.customer_email,
      subject: emailSubject,
      html: emailHtml,
    })

    if (resendError) {
      console.error("[EMAIL] ❌ Resend API error:", resendError)
      throw new Error(`Failed to send email: ${resendError.message}`)
    }

    console.log("[EMAIL] ✅ Email sent successfully!")
    console.log("[EMAIL] Email ID:", data?.id)
    console.log("[EMAIL] Recipient:", order.customer_email)

    return {
      success: true,
      message: `Email sent to ${order.customer_email}`,
      emailId: data?.id,
    }
  } catch (error: any) {
    console.error("[EMAIL] ❌ Send email error:", error?.message || error)
    console.error("[EMAIL] Error stack:", error?.stack)
    throw error
  }
}

function generateEmailHtml({ order, event, tickets, chits, eventDate, eventId, baseUrl }: any) {
  // Use absolute URLs for images in emails
  const logoUrl = `${baseUrl}/images/logo-1920-black.png`

  return `
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Your Tikkets</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f5f5f5;">
  <table role="presentation" style="width: 100%; border-collapse: collapse;">
    <tr>
      <td style="padding: 40px 20px;">
        <table role="presentation" style="max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);">
          
          <!-- Header -->
          <tr>
            <td style="background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%); padding: 32px 40px; text-align: center;">
              <img src="${logoUrl}" alt="Tikkets" style="height: 40px; margin-bottom: 16px; filter: brightness(0) invert(1);">
              <h1 style="color: #ffffff; font-size: 28px; font-weight: 700; margin: 0 0 8px 0;">Your Tickets Are Ready!</h1>
              <p style="color: rgba(255,255,255,0.9); font-size: 16px; margin: 0;">Thank you for your purchase</p>
            </td>
          </tr>
          
          <!-- Event Banner -->
          <tr>
            <td style="padding: 32px 40px; background-color: #1a1a1a; color: #ffffff;">
              <h2 style="font-size: 24px; font-weight: 700; margin: 0 0 16px 0;">${event?.name || "Event"}</h2>
              <table role="presentation" style="width: 100%;">
                <tr>
                  <td style="padding: 8px 0;">
                    <span style="color: #999; font-size: 14px;">📅 Date</span><br>
                    <span style="font-size: 16px; font-weight: 500;">${eventDate}</span>
                  </td>
                </tr>
                ${
                  event?.location
                    ? `
                <tr>
                  <td style="padding: 8px 0;">
                    <span style="color: #999; font-size: 14px;">📍 Venue</span><br>
                    <span style="font-size: 16px; font-weight: 500;">${event.location}</span>
                  </td>
                </tr>
                `
                    : ""
                }
              </table>
            </td>
          </tr>
          
          <!-- Order Summary -->
          <tr>
            <td style="padding: 32px 40px;">
              <h3 style="font-size: 18px; font-weight: 600; margin: 0 0 20px 0; color: #1a1a1a;">Order Summary</h3>
              
              <table role="presentation" style="width: 100%; border-collapse: collapse;">
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; color: #666; font-size: 14px;">Order ID</td>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; text-align: right; font-weight: 600; font-family: monospace;">${order.id.slice(0, 8).toUpperCase()}</td>
                </tr>
                ${
                  order.customer_name
                    ? `
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; color: #666; font-size: 14px;">Name</td>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; text-align: right; font-weight: 500;">${order.customer_name}</td>
                </tr>
                `
                    : ""
                }
                <tr>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; color: #666; font-size: 14px;">Email</td>
                  <td style="padding: 12px 0; border-bottom: 1px solid #e5e5e5; text-align: right; font-weight: 500;">${order.customer_email}</td>
                </tr>
                <tr>
                  <td style="padding: 16px 0; color: #1a1a1a; font-size: 16px; font-weight: 600;">Total Paid</td>
                  <td style="padding: 16px 0; text-align: right; color: #16a34a; font-size: 20px; font-weight: 700;">${new Intl.NumberFormat(
                    "en-US",
                    {
                      style: "currency",
                      currency: event?.currency || "USD",
                    },
                  ).format(Number(order.total_amount))}</td>
                </tr>
              </table>
            </td>
          </tr>
          
          <!-- Tickets Section -->
          ${
            tickets.length > 0
              ? `
          <tr>
            <td style="padding: 0 40px 32px;">
              <h3 style="font-size: 16px; font-weight: 600; margin: 0 0 16px 0; color: #1a1a1a;">🎟️ Your Tickets (${tickets.length})</h3>
              ${tickets
                .map(
                  (ticket: any, index: number) => `
              <div style="background: #f9f9f9; border-radius: 12px; padding: 20px; margin-bottom: 12px; border-left: 4px solid #dc2626;">
                <p style="font-weight: 600; font-size: 16px; margin: 0 0 8px 0; color: #1a1a1a;">${ticket.ticket_name || "General Admission"}</p>
                <p style="font-size: 13px; color: #666; margin: 0;">Ticket ${index + 1} of ${tickets.length}</p>
                <p style="font-size: 11px; color: #999; margin: 8px 0 0 0; font-family: monospace;">ID: ${ticket.qr_code_data}</p>
              </div>
              `,
                )
                .join("")}
            </td>
          </tr>
          `
              : ""
          }
          
          <!-- Chits Section -->
          ${
            chits.length > 0
              ? `
          <tr>
            <td style="padding: 0 40px 32px;">
              <h3 style="font-size: 16px; font-weight: 600; margin: 0 0 16px 0; color: #1a1a1a;">🎫 Your Chits (${chits.length})</h3>
              ${chits
                .map(
                  (chit: any, index: number) => `
              <div style="background: #f9f9f9; border-radius: 12px; padding: 20px; margin-bottom: 12px; border-left: 4px solid #7c3aed;">
                <p style="font-weight: 600; font-size: 16px; margin: 0 0 8px 0; color: #1a1a1a;">${chit.item_name}</p>
                <p style="font-size: 13px; color: #666; margin: 0;">Qty: ${chit.quantity} • Ready to redeem</p>
                <p style="font-size: 11px; color: #999; margin: 8px 0 0 0; font-family: monospace;">ID: ${chit.qr_code_data}</p>
              </div>
              `,
                )
                .join("")}
            </td>
          </tr>
          `
              : ""
          }
          
          <!-- CTA Button -->
          <tr>
            <td style="padding: 0 40px 32px;">
              <a href="${baseUrl}e/${eventId}/order/${order.id}/guest" style="display: block; background: #dc2626; color: #ffffff; text-decoration: none; padding: 16px 32px; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center;">
                View & Download Your Tickets
              </a>
            </td>
          </tr>
          
          <!-- Footer -->
          <tr>
            <td style="padding: 32px 40px; background-color: #f9f9f9; text-align: center;">
              <p style="font-size: 14px; color: #666; margin: 0 0 16px 0;">
                Questions about your order? Contact the event organizer.
              </p>
              <p style="font-size: 12px; color: #999; margin: 0 0 16px 0;">
                This email was sent to ${order.customer_email} because you made a purchase through Tikkets.
              </p>
              <img src="${logoUrl}" alt="Tikkets" style="height: 24px; opacity: 0.5;">
            </td>
          </tr>
          
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
`
}
