import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";
import { ObjectId } from "mongodb";

// GET - Export order as PDF
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const ordersCollection = await getCollection("orders");
    const settingsCollection = await getCollection("settings");

    // Fetch order
    const order = await ordersCollection.findOne({
      _id: new ObjectId(id),
    });

    if (!order) {
      return NextResponse.json(
        { error: "Order not found" },
        { status: 404 }
      );
    }

    // Fetch company settings
    const settings = await settingsCollection.findOne({});

    // Generate PDF using jspdf
    const PDFDocument = require("jspdf").jsPDF;
    const doc = new PDFDocument();

    // Add logo if available
    if (settings?.logo_url) {
      try {
        // Note: In production, you'd need to fetch and convert the image
        // For now, we'll just add text
        doc.setFontSize(20);
        doc.text(settings.company_name || "Server Zone Computer", 20, 30);
      } catch (e) {
        doc.setFontSize(20);
        doc.text(settings?.company_name || "Server Zone Computer", 20, 30);
      }
    } else {
      doc.setFontSize(20);
      doc.text(settings?.company_name || "Server Zone Computer", 20, 30);
    }

    // Company details
    doc.setFontSize(10);
    let yPos = 50;
    if (settings?.address) {
      doc.text(
        `${settings.address.street || ""}, ${settings.address.city || ""}, ${settings.address.zip || ""}`,
        20,
        yPos
      );
      yPos += 5;
    }
    if (settings?.phone) {
      doc.text(`Phone: ${settings.phone}`, 20, yPos);
      yPos += 5;
    }
    if (settings?.support_email) {
      doc.text(`Email: ${settings.support_email}`, 20, yPos);
      yPos += 5;
    }
    if (settings?.vat_number) {
      doc.text(`VAT Number: ${settings.vat_number}`, 20, yPos);
      yPos += 5;
    }

    // Invoice details
    yPos += 10;
    doc.setFontSize(16);
    doc.text("INVOICE", 20, yPos);
    yPos += 10;

    doc.setFontSize(10);
    doc.text(`Order Number: ${order.orderNumber || order._id}`, 20, yPos);
    yPos += 5;
    doc.text(
      `Date: ${new Date(order.createdAt).toLocaleDateString()}`,
      20,
      yPos
    );
    yPos += 5;
    doc.text(`Status: ${order.status}`, 20, yPos);
    yPos += 10;

    // Customer details
    doc.setFontSize(12);
    doc.text("Bill To:", 20, yPos);
    yPos += 5;
    doc.setFontSize(10);
    doc.text(order.customer.name, 20, yPos);
    yPos += 5;
    doc.text(order.customer.email, 20, yPos);
    yPos += 5;
    if (order.customer.address) {
      doc.text(
        `${order.customer.address.street}, ${order.customer.address.city}`,
        20,
        yPos
      );
      yPos += 5;
      doc.text(
        `${order.customer.address.zip}, ${order.customer.address.country}`,
        20,
        yPos
      );
      yPos += 10;
    }

    // Items table
    doc.setFontSize(12);
    doc.text("Items:", 20, yPos);
    yPos += 8;

    // Table headers
    doc.setFontSize(10);
    doc.text("Item", 20, yPos);
    doc.text("Qty", 100, yPos);
    doc.text("Price", 130, yPos);
    doc.text("Total", 170, yPos);
    yPos += 5;

    // Draw line
    doc.line(20, yPos, 190, yPos);
    yPos += 5;

    // Items
    order.items.forEach((item: any) => {
      doc.text(item.title.substring(0, 30), 20, yPos);
      doc.text(item.quantity.toString(), 100, yPos);
      doc.text(
        `${settings?.currency || "AED"} ${item.price.toFixed(2)}`,
        130,
        yPos
      );
      doc.text(
        `${settings?.currency || "AED"} ${item.total.toFixed(2)}`,
        170,
        yPos
      );
      yPos += 5;
    });

    yPos += 5;
    doc.line(20, yPos, 190, yPos);
    yPos += 10;

    // Totals
    doc.setFontSize(10);
    doc.text("Subtotal:", 130, yPos);
    doc.text(
      `${settings?.currency || "AED"} ${order.totals.subtotal.toFixed(2)}`,
      170,
      yPos
    );
    yPos += 5;

    if (order.totals.tax > 0) {
      doc.text("Tax:", 130, yPos);
      doc.text(
        `${settings?.currency || "AED"} ${order.totals.tax.toFixed(2)}`,
        170,
        yPos
      );
      yPos += 5;
    }

    if (order.totals.shipping > 0) {
      doc.text("Shipping:", 130, yPos);
      doc.text(
        `${settings?.currency || "AED"} ${order.totals.shipping.toFixed(2)}`,
        170,
        yPos
      );
      yPos += 5;
    }

    if (order.totals.discount > 0) {
      doc.text("Discount:", 130, yPos);
      doc.text(
        `-${settings?.currency || "AED"} ${order.totals.discount.toFixed(2)}`,
        170,
        yPos
      );
      yPos += 5;
    }

    yPos += 2;
    doc.line(130, yPos, 190, yPos);
    yPos += 5;

    doc.setFontSize(12);
    doc.setFont(undefined, "bold");
    doc.text("Total:", 130, yPos);
    doc.text(
      `${settings?.currency || "AED"} ${order.totals.total.toFixed(2)}`,
      170,
      yPos
    );

    // Footer
    yPos = 280;
    doc.setFontSize(8);
    doc.setFont(undefined, "normal");
    doc.text("Thank you for your business!", 20, yPos);

    // Generate PDF buffer
    const pdfBuffer = Buffer.from(doc.output("arraybuffer"));

    // Return PDF
    return new NextResponse(pdfBuffer, {
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="invoice-${order.orderNumber || order._id}.pdf"`,
      },
    });
  } catch (error) {
    console.error("Error generating PDF:", error);
    return NextResponse.json(
      { error: "Failed to generate PDF" },
      { status: 500 }
    );
  }
}

