import { NextRequest, NextResponse } from "next/server";
import { requireStaffAuth } from "@/lib/staff-auth";
import { prisma } from "@/lib/db";
import { sendEmail } from "@/lib/email";
import { createId } from "@paralleldrive/cuid2";
import { stripe, getOrCreateCustomer } from "@/lib/stripe";
import { getDataSource } from "@/lib/data-source";

/**
 * POST /api/staff/users/[id]/billing/email
 * Send a billing email to a user with optional payment link
 */
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    const staffUser = await requireStaffAuth();
    if (!staffUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const {
      subject,
      content,
      amount,
      dueDate,
      currency = "GBP",
      includePaymentLink = false,
    } = body;

    // Validation
    if (!subject || subject.trim().length < 5) {
      return NextResponse.json(
        { error: "Subject required (minimum 5 characters)" },
        { status: 400 },
      );
    }

    if (!content || content.trim().length < 10) {
      return NextResponse.json(
        { error: "Message content required (minimum 10 characters)" },
        { status: 400 },
      );
    }

    // If payment link requested, amount is required
    if (includePaymentLink && (!amount || parseFloat(amount) <= 0)) {
      return NextResponse.json(
        { error: "Amount is required when including a payment link" },
        { status: 400 },
      );
    }

    // Get user with Stripe customer info
    const user = await prisma.users.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        email: true,
        name: true,
        companyName: true,
        stripeCustomerId: true,
        subscriptions: {
          select: { stripeCustomerId: true },
          orderBy: { createdAt: "desc" },
          take: 1,
        },
      },
    });

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

    // Generate payment link if requested and amount is provided
    let paymentUrl: string | null = null;
    let checkoutSessionId: string | null = null;

    if (includePaymentLink && amount) {
      try {
        // Get or create Stripe customer
        const stripeCustomerId =
          user.subscriptions[0]?.stripeCustomerId || user.stripeCustomerId;
        let customerId = stripeCustomerId;

        if (!customerId) {
          const customer = await getOrCreateCustomer({
            email: user.email,
            name: user.name || user.companyName || undefined,
            metadata: {
              user_id: user.id,
            },
          });
          customerId = customer.id;

          // Update user with Stripe customer ID
          await prisma.users.update({
            where: { id: user.id },
            data: { stripeCustomerId: customer.id },
          });
        }

        // Create a checkout session for the payment
        const amountInCents = Math.round(parseFloat(amount) * 100);
        const emailId = createId();

        const session = await stripe.checkout.sessions.create({
          mode: "payment",
          customer: customerId,
          line_items: [
            {
              price_data: {
                currency: currency.toLowerCase(),
                product_data: {
                  name: subject.trim(),
                  description: `Invoice for ${user.companyName || user.name || user.email}`,
                },
                unit_amount: amountInCents,
              },
              quantity: 1,
            },
          ],
          payment_intent_data: {
            metadata: {
              billing_email_id: emailId,
              user_id: user.id,
              sent_by_staff: staffUser.id,
              invoice_type: "manual_billing",
            },
          },
          success_url: `${process.env.NEXT_PUBLIC_APP_URL}/payment/success?session_id={CHECKOUT_SESSION_ID}&billing_email=${emailId}`,
          cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/payment/cancelled`,
          expires_at: dueDate
            ? Math.min(
                Math.floor(new Date(dueDate).getTime() / 1000),
                Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60,
              )
            : Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days from now
          metadata: {
            billing_email_id: emailId,
            user_id: user.id,
          },
        });

        paymentUrl = session.url;
        checkoutSessionId = session.id;

        console.log(`🔗 Created payment link for ${user.email}: ${paymentUrl}`);
      } catch (stripeError) {
        console.error("⚠️ Stripe payment link creation failed:", stripeError);
        // Continue without payment link - don't fail the entire operation
      }
    }

    // Create billing email record -- Convex or Prisma
    let billingEmailId = "";

    if (getDataSource("billing") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        const convexId = await convexMutation(
          "support/mutations:createBillingEmail",
          {
            userId: params.id,
            staffId: staffUser.id,
            subject: subject.trim(),
            body: content.trim(),
            amount: amount ? parseFloat(amount) : undefined,
            dueDate: dueDate ? new Date(dueDate).getTime() : undefined,
            status: "SENT",
          },
        );
        billingEmailId = convexId as string;
      } catch (convexError) {
        console.error(
          "Convex billing email failed, falling back to Prisma:",
          convexError,
        );
        billingEmailId = "";
      }
    }

    // Prisma path (default or fallback)
    if (!billingEmailId) {
      const emailRecordId = createId();
      const billingEmail = await prisma.billing_emails.create({
        data: {
          id: emailRecordId,
          userId: params.id,
          staffId: staffUser.id,
          subject: subject.trim(),
          body: content.trim(),
          amount: amount ? parseFloat(amount) : null,
          dueDate: dueDate ? new Date(dueDate) : null,
          status: "SENT",
        },
      });
      billingEmailId = billingEmail.id;
    }

    // Format currency for display
    const currencySymbol = getCurrencySymbol(currency);
    const formattedAmount = amount
      ? `${currencySymbol}${parseFloat(amount).toFixed(2)}`
      : null;

    // Build the email HTML
    const emailHTML = `
      <!DOCTYPE html>
      <html>
      <head>
        <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: #ffffff; padding: 30px; border: 1px solid #e5e7eb; }
          .footer { background: #f9fafb; padding: 20px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 8px 8px; }
          .amount-box { background: #f0fdf4; border: 2px solid #10b981; border-radius: 8px; padding: 20px; margin: 20px 0; text-align: center; }
          .amount { font-size: 32px; font-weight: bold; color: #059669; }
          .pay-button { display: inline-block; background: #10b981; color: white; padding: 15px 40px; text-decoration: none; border-radius: 8px; font-size: 18px; font-weight: bold; margin: 20px 0; }
          .pay-button:hover { background: #059669; }
          .due-date { color: #dc2626; font-weight: bold; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <h1>Mawidi Billing Notice</h1>
          </div>
          <div class="content">
            <p>Dear ${user.name || user.email},</p>
            <div style="white-space: pre-wrap; margin-bottom: 20px;">${content.trim()}</div>
            ${
              formattedAmount
                ? `
              <div class="amount-box">
                <p style="margin: 0 0 10px 0; color: #6b7280;">Amount Due</p>
                <div class="amount">${formattedAmount}</div>
                ${dueDate ? `<p style="margin: 10px 0 0 0;" class="due-date">Due by: ${new Date(dueDate).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}</p>` : ""}
              </div>
            `
                : ""
            }
            ${
              paymentUrl
                ? `
              <div style="text-align: center; margin: 30px 0;">
                <a href="${paymentUrl}" class="pay-button">Pay Now</a>
                <p style="font-size: 12px; color: #6b7280; margin-top: 10px;">Secure payment powered by Stripe</p>
              </div>
              <p style="font-size: 12px; color: #6b7280;">
                If the button doesn't work, copy and paste this link into your browser:<br>
                <a href="${paymentUrl}" style="color: #10b981; word-break: break-all;">${paymentUrl}</a>
              </p>
            `
                : ""
            }
            <p style="margin-top: 30px;">If you have questions about this invoice, please contact our support team.</p>
          </div>
          <div class="footer">
            <p>© ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
            <p style="font-size: 11px;">This is an automated billing notice. Please do not reply to this email.</p>
          </div>
        </div>
      </body>
      </html>
    `;

    await sendEmail({
      to: user.email,
      subject: subject.trim(),
      html: emailHTML,
    });

    // Create audit log

    console.log(
      `💰 Billing email sent to ${user.email} by ${staffUser.email}${paymentUrl ? " with payment link" : ""}`,
    );

    return NextResponse.json(
      {
        success: true,
        message: paymentUrl
          ? "Billing email with payment link sent successfully"
          : "Billing email sent successfully",
        billingEmail: {
          id: billingEmailId,
          subject: subject.trim(),
          status: "SENT",
          paymentUrl,
        },
      },
      { status: 201 },
    );
  } catch (error) {
    console.error("❌ Failed to send billing email:", error);
    return NextResponse.json(
      { error: "Failed to send billing email" },
      { status: 500 },
    );
  }
}

function getCurrencySymbol(currency: string): string {
  const symbols: Record<string, string> = {
    GBP: "£",
    USD: "$",
    EUR: "€",
    AED: "AED ",
    SAR: "SAR ",
    QAR: "QAR ",
    KWD: "KWD ",
    BHD: "BHD ",
    OMR: "OMR ",
  };
  return symbols[currency.toUpperCase()] || `${currency.toUpperCase()} `;
}
