import jsPDF from "jspdf"

interface OrderItem {
  item_name: string
  quantity: number
  price: number
}

interface OrderData {
  id: string
  created_at: string
  customer_name: string
  customer_email: string
  customer_phone?: string | null
  table_number?: string | null
  chits: OrderItem[]
  tax_amount: number
  total_amount: number
  payment_status: string
  event_name?: string
}

export async function generateReceiptPDF(order: OrderData): Promise<void> {
  const doc = new jsPDF({
    orientation: "portrait",
    unit: "mm",
    format: "a4",
  })

  const pageWidth = doc.internal.pageSize.getWidth()
  const margin = 20
  let yPos = 20

  // Load and add logo
  try {
    const logoUrl = "/images/logo-1920-black.png"
    const img = await loadImage(logoUrl)
    const logoWidth = 50
    const logoHeight = 15
    doc.addImage(img, "PNG", (pageWidth - logoWidth) / 2, yPos, logoWidth, logoHeight)
    yPos += logoHeight + 10
  } catch (error) {
    // Fallback: just add text if logo fails to load
    doc.setFontSize(24)
    doc.setFont("helvetica", "bold")
    doc.text("Tikkets.com", pageWidth / 2, yPos + 10, { align: "center" })
    yPos += 20
  }

  // Receipt title
  doc.setFontSize(18)
  doc.setFont("helvetica", "bold")
  doc.text("RECEIPT", pageWidth / 2, yPos, { align: "center" })
  yPos += 10

  // Divider line
  doc.setLineWidth(0.5)
  doc.setDrawColor(200, 200, 200)
  doc.line(margin, yPos, pageWidth - margin, yPos)
  yPos += 10

  // Order details section
  doc.setFontSize(10)
  doc.setFont("helvetica", "normal")
  doc.setTextColor(100, 100, 100)

  const orderDate = new Date(order.created_at).toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  })

  // Order info box
  doc.setFillColor(248, 248, 248)
  doc.roundedRect(margin, yPos, pageWidth - margin * 2, 35, 3, 3, "F")
  yPos += 8

  doc.setTextColor(60, 60, 60)
  doc.setFont("helvetica", "bold")
  doc.text("Order ID:", margin + 5, yPos)
  doc.setFont("helvetica", "normal")
  doc.text(`#${order.id.slice(0, 8).toUpperCase()}`, margin + 30, yPos)

  doc.setFont("helvetica", "bold")
  doc.text("Date:", pageWidth / 2, yPos)
  doc.setFont("helvetica", "normal")
  doc.text(orderDate, pageWidth / 2 + 15, yPos)

  yPos += 8

  doc.setFont("helvetica", "bold")
  doc.text("Customer:", margin + 5, yPos)
  doc.setFont("helvetica", "normal")
  doc.text(order.customer_name, margin + 30, yPos)

  if (order.table_number) {
    doc.setFont("helvetica", "bold")
    doc.text("Table:", pageWidth / 2, yPos)
    doc.setFont("helvetica", "normal")
    doc.text(order.table_number, pageWidth / 2 + 15, yPos)
  }

  yPos += 8

  doc.setFont("helvetica", "bold")
  doc.text("Email:", margin + 5, yPos)
  doc.setFont("helvetica", "normal")
  doc.text(order.customer_email, margin + 30, yPos)

  if (order.customer_phone) {
    doc.setFont("helvetica", "bold")
    doc.text("Phone:", pageWidth / 2, yPos)
    doc.setFont("helvetica", "normal")
    doc.text(order.customer_phone, pageWidth / 2 + 15, yPos)
  }

  yPos += 20

  // Items header
  doc.setFillColor(51, 51, 51)
  doc.rect(margin, yPos, pageWidth - margin * 2, 8, "F")
  yPos += 5.5

  doc.setTextColor(255, 255, 255)
  doc.setFont("helvetica", "bold")
  doc.setFontSize(9)
  doc.text("ITEM", margin + 5, yPos)
  doc.text("QTY", pageWidth - margin - 50, yPos, { align: "center" })
  doc.text("PRICE", pageWidth - margin - 25, yPos, { align: "center" })
  doc.text("TOTAL", pageWidth - margin - 5, yPos, { align: "right" })

  yPos += 7

  // Items list
  doc.setTextColor(60, 60, 60)
  doc.setFont("helvetica", "normal")
  doc.setFontSize(10)

  order.chits.forEach((item, index) => {
    const itemTotal = item.price * item.quantity
    const bgColor = index % 2 === 0 ? 255 : 248

    doc.setFillColor(bgColor, bgColor, bgColor)
    doc.rect(margin, yPos - 4, pageWidth - margin * 2, 8, "F")

    doc.text(item.item_name, margin + 5, yPos)
    doc.text(item.quantity.toString(), pageWidth - margin - 50, yPos, { align: "center" })
    doc.text(`$${item.price.toFixed(2)}`, pageWidth - margin - 25, yPos, { align: "center" })
    doc.text(`$${itemTotal.toFixed(2)}`, pageWidth - margin - 5, yPos, { align: "right" })

    yPos += 8
  })

  yPos += 5

  // Totals section
  doc.setLineWidth(0.5)
  doc.setDrawColor(200, 200, 200)
  doc.line(pageWidth - margin - 60, yPos, pageWidth - margin, yPos)
  yPos += 8

  // Subtotal
  const subtotal = order.total_amount - order.tax_amount
  doc.setFont("helvetica", "normal")
  doc.text("Subtotal:", pageWidth - margin - 60, yPos)
  doc.text(`$${subtotal.toFixed(2)}`, pageWidth - margin - 5, yPos, { align: "right" })
  yPos += 6

  // Tax
  doc.text("Tax:", pageWidth - margin - 60, yPos)
  doc.text(`$${order.tax_amount.toFixed(2)}`, pageWidth - margin - 5, yPos, { align: "right" })
  yPos += 8

  // Total
  doc.setLineWidth(0.5)
  doc.line(pageWidth - margin - 60, yPos - 2, pageWidth - margin, yPos - 2)
  doc.setFont("helvetica", "bold")
  doc.setFontSize(12)
  doc.text("TOTAL:", pageWidth - margin - 60, yPos + 4)
  doc.text(`$${order.total_amount.toFixed(2)}`, pageWidth - margin - 5, yPos + 4, { align: "right" })

  yPos += 20

  // Payment status badge
  const statusColor = order.payment_status === "completed" ? [34, 197, 94] : [234, 179, 8]
  doc.setFillColor(statusColor[0], statusColor[1], statusColor[2])
  const statusText = order.payment_status.toUpperCase()
  const statusWidth = doc.getTextWidth(statusText) + 10
  doc.roundedRect((pageWidth - statusWidth) / 2, yPos - 4, statusWidth, 8, 2, 2, "F")
  doc.setTextColor(255, 255, 255)
  doc.setFontSize(9)
  doc.setFont("helvetica", "bold")
  doc.text(statusText, pageWidth / 2, yPos + 1, { align: "center" })

  yPos += 20

  // Footer
  doc.setTextColor(150, 150, 150)
  doc.setFontSize(8)
  doc.setFont("helvetica", "normal")
  doc.text("Thank you for your purchase!", pageWidth / 2, yPos, { align: "center" })
  yPos += 5
  doc.text("For questions, contact the event organizer.", pageWidth / 2, yPos, { align: "center" })
  yPos += 5
  doc.text("Powered by Tikkets.com", pageWidth / 2, yPos, { align: "center" })

  // Save the PDF
  doc.save(`tikkets-receipt-${order.id.slice(0, 8)}.pdf`)
}

// Helper function to load image
function loadImage(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.crossOrigin = "anonymous"
    img.onload = () => {
      const canvas = document.createElement("canvas")
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext("2d")
      if (ctx) {
        ctx.drawImage(img, 0, 0)
        resolve(canvas.toDataURL("image/png"))
      } else {
        reject(new Error("Failed to get canvas context"))
      }
    }
    img.onerror = () => reject(new Error("Failed to load image"))
    img.src = url
  })
}
