import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth-utils";
import prisma from "@/lib/db";
import { format } from "date-fns";

interface RouteContext {
  params: Promise<{ id: string }>;
}

/**
 * POST /api/bookings/[id]/cancel
 * Cancel a booking (by tourist or guide)
 */
export async function POST(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const user = await getCurrentUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await context.params;

    // Get booking with tour details
    const booking = await prisma.booking.findUnique({
      where: { id },
      include: {
        tour: {
          select: {
            id: true,
            title: true,
            createdById: true,
            createdBy: {
              select: {
                name: true,
                email: true,
              },
            },
          },
        },
        user: {
          select: {
            name: true,
            email: true,
          },
        },
      },
    });

    if (!booking) {
      return NextResponse.json(
        { error: "Booking not found" },
        { status: 404 }
      );
    }

    // Check authorization (tourist or guide)
    const isTourist = booking.userId === user.id;
    const isGuide = booking.tour.createdById === user.id;

    if (!isTourist && !isGuide) {
      return NextResponse.json(
        { error: "You are not authorized to cancel this booking" },
        { status: 403 }
      );
    }

    // Check if booking can be cancelled
    if (booking.status !== "PENDING" && booking.status !== "CONFIRMED") {
      return NextResponse.json(
        { 
          error: `Cannot cancel ${booking.status.toLowerCase()} bookings` 
        },
        { status: 400 }
      );
    }

    // Update booking status to CANCELLED
    const updatedBooking = await prisma.booking.update({
      where: { id },
      data: { status: "CANCELLED" },
    });

    // Send cancellation emails
    const formattedDate = format(new Date(booking.date), "PPP");
    const cancelledBy = isTourist ? "tourist" : "guide";

    // Send email to tourist
    await sendCancellationEmail({
      to: booking.user.email,
      name: booking.user.name || "Traveler",
      tourTitle: booking.tour.title,
      bookingDate: formattedDate,
      cancelledBy,
      role: "tourist",
    });

    // Send email to guide
    await sendCancellationEmail({
      to: booking.tour.createdBy.email,
      name: booking.tour.createdBy.name || "Guide",
      tourTitle: booking.tour.title,
      bookingDate: formattedDate,
      cancelledBy,
      role: "guide",
    });

    return NextResponse.json({
      booking: updatedBooking,
      message: "Booking cancelled successfully",
    });
  } catch (error) {
    console.error("Error cancelling booking:", error);
    return NextResponse.json(
      { error: "Failed to cancel booking" },
      { status: 500 }
    );
  }
}

// Helper function to send cancellation emails
async function sendCancellationEmail({
  to,
  name,
  tourTitle,
  bookingDate,
  cancelledBy,
  role,
}: {
  to: string;
  name: string;
  tourTitle: string;
  bookingDate: string;
  cancelledBy: string;
  role: string;
}) {
  try {
    // Import Resend dynamically to avoid issues
    const { Resend } = await import("resend");
    const resend = new Resend(process.env.RESEND_API_KEY);

    const subject = `Booking Cancelled: ${tourTitle}`;
    const cancellerText = cancelledBy === role 
      ? "You have cancelled" 
      : `The ${cancelledBy} has cancelled`;

    await resend.emails.send({
      from: "ZuriGuide <bookings@store.kungu.dev>",
      to,
      subject,
      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, #ef4444 0%, #dc2626 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; }
              .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 Cancelled</h1>
              </div>
              <div class="content">
                <p>Hi ${name},</p>
                <p>${cancellerText} the following booking:</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>
                
                <p style="margin-top: 30px;">
                  ${role === "tourist" 
                    ? "If you'd like to book this tour again, you can visit the tour page anytime." 
                    : "The tourist slot is now available for other bookings."}
                </p>
              </div>
              <div class="footer">
                <p>© ${new Date().getFullYear()} ZuriGuide. All rights reserved.</p>
              </div>
            </div>
          </body>
        </html>
      `,
    });

    console.log(`Cancellation email sent to ${role}:`, to);
  } catch (error) {
    console.error("Failed to send cancellation email:", error);
  }
}
