import { Resend } from "resend";

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

export interface BookingRequestEmailProps {
  guideName: string;
  guideEmail: string;
  explorerName: string;
  tourTitle: string;
  bookingDate: string;
  numberOfGuests: number;
  totalPrice: string;
}

export interface BookingConfirmationEmailProps {
  explorerName: string;
  explorerEmail: string;
  tourTitle: string;
  tourSlug: string;
  guideName: string;
  guideEmail: string;
  bookingDate: string;
  numberOfGuests: number;
  totalPrice: string;
}

export interface BookingCompletedEmailProps {
  explorerName: string;
  explorerEmail: string;
  tourTitle: string;
  tourSlug: string;
  guideName: string;
  tourDate: string;
}

export interface ReviewNotificationEmailProps {
  guideName: string;
  guideEmail: string;
  explorerName: string;
  tourTitle: string;
  tourSlug: string;
  rating: number;
  comment?: string;
}

/**
 * Send email notification to guide when a new booking is requested
 */
export async function sendBookingRequestEmail(props: BookingRequestEmailProps) {
  const {
    guideName,
    guideEmail,
    explorerName,
    tourTitle,
    bookingDate,
    numberOfGuests,
    totalPrice,
  } = props;

  try {
    await resend.emails.send({
      from: "ZuriGuide <bookings@store.kungu.dev>",
      to: guideEmail,
      subject: `New Booking Request for "${tourTitle}"`,
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .detail-row { margin: 15px 0; padding: 10px; background: white; border-radius: 4px; }
              .label { font-weight: bold; color: #6b7280; font-size: 14px; }
              .value { color: #111827; font-size: 16px; margin-top: 5px; }
              .button { display: inline-block; background: #2563eb; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin-top: 20px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">🎉 New Booking Request!</h1>
              </div>
              <div class="content">
                <p>Hi ${guideName},</p>
                <p>Great news! You have a new booking request for your tour.</p>
                
                <div class="detail-row">
                  <div class="label">Tour</div>
                  <div class="value">${tourTitle}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Explorer</div>
                  <div class="value">${explorerName}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Date</div>
                  <div class="value">${bookingDate}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Number of Guests</div>
                  <div class="value">${numberOfGuests} ${numberOfGuests === 1 ? 'guest' : 'guests'}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Total Price</div>
                  <div class="value">${totalPrice}</div>
                </div>
                
                <p style="margin-top: 30px;">Please review and confirm this booking in your dashboard.</p>
                
                <div style="text-align: center;">
                  <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/dashboard/bookings" class="button">
                    View Booking
                  </a>
                </div>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Booking request email sent to guide:", guideEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send booking request email:", error);
    return { success: false, error };
  }
}

/**
 * Send confirmation email to explorer when booking is confirmed
 */
export async function sendBookingConfirmationEmail(
  props: BookingConfirmationEmailProps
) {
  const {
    explorerName,
    explorerEmail,
    tourTitle,
    bookingDate,
    numberOfGuests,
    totalPrice,
    guideName,
    guideEmail,
  } = props;

  try {
    await resend.emails.send({
      from: "ZuriGuide <bookings@store.kungu.dev>",
      to: explorerEmail,
      subject: `Booking Confirmed: ${tourTitle}`,
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .detail-row { margin: 15px 0; padding: 10px; background: white; border-radius: 4px; }
              .label { font-weight: bold; color: #6b7280; font-size: 14px; }
              .value { color: #111827; font-size: 16px; margin-top: 5px; }
              .highlight { background: #dcfce7; padding: 15px; border-left: 4px solid #10b981; margin: 20px 0; border-radius: 4px; }
              .button { display: inline-block; background: #10b981; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin-top: 20px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">✅ Booking Confirmed!</h1>
              </div>
              <div class="content">
                <p>Hi ${explorerName},</p>
                <p>Your booking has been confirmed! We're excited for your upcoming tour.</p>
                
                <div class="detail-row">
                  <div class="label">Tour</div>
                  <div class="value">${tourTitle}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Date</div>
                  <div class="value">${bookingDate}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Number of Guests</div>
                  <div class="value">${numberOfGuests} ${numberOfGuests === 1 ? 'guest' : 'guests'}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Total Price</div>
                  <div class="value">${totalPrice}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Your Guide</div>
                  <div class="value">${guideName}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Guide Contact</div>
                  <div class="value">
                    <a href="mailto:${guideEmail}" style="color: #2563eb; text-decoration: none;">
                      ${guideEmail}
                    </a>
                  </div>
                </div>
                
                <div style="background: #eff6ff; padding: 15px; border-radius: 4px; margin: 20px 0;">
                  <p style="margin: 0; font-size: 14px; color: #1e40af;">
                    💬 <strong>Stay Connected:</strong> Feel free to reach out to ${guideName} at the email above for any questions about your tour, special requests, or to confirm meeting details.
                  </p>
                </div>
                
                <p style="margin-top: 30px;">You can view all your booking details in your dashboard.</p>
                
                <div style="text-align: center;">
                  <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/bookings" class="button">
                    View My Bookings
                  </a>
                </div>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Booking confirmation email sent to explorer:", explorerEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send booking confirmation email:", error);
    return { success: false, error };
  }
}

/**
 * Send email to explorer after tour is completed, prompting for review
 */
export async function sendBookingCompletedEmail(
  props: BookingCompletedEmailProps
) {
  const { explorerName, explorerEmail, tourTitle, tourSlug, guideName, tourDate } = props;

  try {
    await resend.emails.send({
      from: "ZuriGuide <noreply@store.kungu.dev>",
      to: explorerEmail,
      subject: `How was your tour: ${tourTitle}?`,
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .button { display: inline-block; background: #8b5cf6; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin-top: 20px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">⭐ Share Your Experience</h1>
              </div>
              <div class="content">
                <p>Hi ${explorerName},</p>
                <p>Thank you for joining the "${tourTitle}" tour with ${guideName} on ${tourDate}!</p>
                <p>We'd love to hear about your experience. Your feedback helps other travelers make informed decisions and helps guides improve their tours.</p>
                
                <div style="text-align: center;">
                  <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/tours/${tourSlug}?review=true" class="button">
                    Leave a Review
                  </a>
                </div>
                
                <p style="margin-top: 30px; color: #6b7280; font-size: 14px;">
                  Thank you for being part of the ZuriGuide community!
                </p>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Tour completion email sent to explorer:", explorerEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send tour completion email:", error);
    return { success: false, error };
  }
}

/**
 * Send notification to guide when a new review is submitted
 */
export async function sendReviewNotificationEmail(
  props: ReviewNotificationEmailProps
) {
  const { guideName, guideEmail, explorerName, tourTitle, rating, comment, tourSlug } =
    props;

  const stars = "⭐".repeat(rating);

  try {
    await resend.emails.send({
      from: "ZuriGuide <reviews@store.kungu.dev>",
      to: guideEmail,
      subject: `New ${rating}-Star Review for "${tourTitle}"`,
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .review-box { background: white; padding: 20px; border-left: 4px solid #f59e0b; margin: 20px 0; border-radius: 4px; }
              .stars { font-size: 24px; margin: 10px 0; }
              .button { display: inline-block; background: #f59e0b; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin-top: 20px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">🌟 New Review Received!</h1>
              </div>
              <div class="content">
                <p>Hi ${guideName},</p>
                <p>You've received a new review for your tour "${tourTitle}".</p>
                
                <div class="review-box">
                  <p><strong>From:</strong> ${explorerName}</p>
                  <div class="stars">${stars}</div>
                  ${comment ? `<p style="margin-top: 15px; font-style: italic;">"${comment}"</p>` : ''}
                </div>
                
                <p>Keep up the great work!</p>
                
                <div style="text-align: center;">
                  <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/tours/${tourSlug}" class="button">
                    View Review
                  </a>
                </div>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Review notification email sent to guide:", guideEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send review notification email:", error);
    return { success: false, error };
  }
}

interface GuideCompletionReminderEmailProps {
  guideName: string;
  guideEmail: string;
  tourTitle: string;
  explorerName: string;
  bookingDate: string;
  bookingId: string;
}

/**
 * Send reminder to guide to mark booking as completed
 * Sent 24 hours after tour date
 */
export async function sendGuideCompletionReminderEmail(
  props: GuideCompletionReminderEmailProps
) {
  const { guideName, guideEmail, tourTitle, explorerName, bookingDate } =
    props;

  try {
    await resend.emails.send({
      from: "ZuriGuide <bookings@zurichconnect.com>",
      to: guideEmail,
      subject: `Reminder: Mark "${tourTitle}" tour as completed`,
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .detail-row { margin: 15px 0; padding: 10px; background: white; border-radius: 4px; }
              .label { font-weight: bold; color: #6b7280; font-size: 14px; }
              .value { color: #111827; font-size: 16px; margin-top: 5px; }
              .button { display: inline-block; background: #f59e0b; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin-top: 20px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
              .highlight { background: #fef3c7; padding: 15px; border-left: 4px solid #f59e0b; margin: 20px 0; border-radius: 4px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">⏰ Tour Completion Reminder</h1>
              </div>
              <div class="content">
                <p>Hi ${guideName},</p>
                <p>This is a friendly reminder that your tour with ${explorerName} took place yesterday.</p>
                
                <div class="detail-row">
                  <div class="label">Tour</div>
                  <div class="value">${tourTitle}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Explorer</div>
                  <div class="value">${explorerName}</div>
                </div>
                
                <div class="detail-row">
                  <div class="label">Tour Date</div>
                  <div class="value">${bookingDate}</div>
                </div>
                
                <div class="highlight">
                  <strong>📝 Action Required:</strong><br>
                  Please mark this booking as completed in your dashboard. This will allow ${explorerName} to leave a review of their experience.
                </div>
                
                <p style="margin-top: 30px;">If you've already completed this tour, please click the button below to confirm:</p>
                
                <div style="text-align: center;">
                  <a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/dashboard" class="button">
                    Mark as Completed
                  </a>
                </div>
                
                <p style="margin-top: 20px; font-size: 14px; color: #6b7280;">
                  Note: Bookings are automatically marked as completed after 24 hours to ensure explorers can leave reviews.
                </p>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Guide completion reminder email sent:", guideEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send guide completion reminder email:", error);
    return { success: false, error };
  }
}

interface AccountDeletionEmailProps {
  userName: string;
  userEmail: string;
}

/**
 * Send confirmation email when user deletes their account
 */
export async function sendAccountDeletionEmail(
  props: AccountDeletionEmailProps
) {
  const { userName, userEmail } = props;

  try {
    await resend.emails.send({
      from: "ZuriGuide <noreply@store.kungu.dev>",
      to: userEmail,
      subject: "Your ZuriGuide account has been deleted",
      html: `
        <!DOCTYPE html>
        <html>
          <head>
            <meta charset="utf-8">
            <style>
              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
              .header { background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%); color: white; padding: 30px; text-align: center; border-radius: 8px 8px 0 0; }
              .content { background: #f9fafb; padding: 30px; border-radius: 0 0 8px 8px; }
              .info-box { background: #fef2f2; padding: 15px; border-left: 4px solid #ef4444; margin: 20px 0; border-radius: 4px; }
              .footer { text-align: center; margin-top: 30px; color: #6b7280; font-size: 14px; }
            </style>
          </head>
          <body>
            <div class="container">
              <div class="header">
                <h1 style="margin: 0;">Account Deletion Confirmed</h1>
              </div>
              <div class="content">
                <p>Hi ${userName || 'there'},</p>
                <p>This email confirms that your ZuriGuide account has been permanently deleted.</p>
                
                <div class="info-box">
                  <p style="margin: 0; font-size: 14px;">
                    <strong>⚠️ What's been deleted:</strong>
                  </p>
                  <ul style="margin: 10px 0; padding-left: 20px; font-size: 14px;">
                    <li>Your profile and personal information</li>
                    <li>All tours you created</li>
                    <li>All your bookings and reviews</li>
                    <li>All invitations and messages</li>
                  </ul>
                </div>
                
                <p>We're sorry to see you go! If you deleted your account by mistake or change your mind, you're welcome to create a new account at any time.</p>
                
                <p style="margin-top: 30px; color: #6b7280; font-size: 14px;">
                  If you didn't request this deletion, please contact our support team immediately.
                </p>
                
                <p style="margin-top: 20px;">Thank you for being part of the ZuriGuide community.</p>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log("Account deletion email sent to:", userEmail);
    return { success: true };
  } catch (error) {
    console.error("Failed to send account deletion email:", error);
    return { success: false, error };
  }
}
