import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import jsPDF from 'jspdf'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ trackingNumber: string }> }
) {
  try {
    const { trackingNumber } = await params

    // Find the service request with template
    const serviceRequest = await db.serviceRequest.findUnique({
      where: { 
        trackingNumber: trackingNumber.toUpperCase(),
        status: 'COMPLETED' // Only allow download for completed requests
      },
      include: {
        user: true,
        service: {
          include: {
            templates: true
          }
        }
      }
    })

    if (!serviceRequest) {
      return NextResponse.json({ 
        message: 'Pengajuan tidak ditemukan atau belum selesai' 
      }, { status: 404 })
    }

    // Generate PDF with template
    const pdf = await generatePDF(serviceRequest)
    const pdfBytes = pdf.output('arraybuffer')

    // Create PDF response
    const response = new NextResponse(pdfBytes, {
      status: 200,
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="${serviceRequest.trackingNumber}.pdf"`,
        'Content-Length': pdfBytes.byteLength.toString(),
      },
    })

    return response
  } catch (error) {
    console.error('Error generating PDF:', error)
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 })
  }
}

async function generatePDF(request: any): Promise<jsPDF> {
  const doc = new jsPDF()
  const submissionData = request.submissionData as any
  
  // Check if there's a custom template
  const template = request.service.templates && request.service.templates[0]
  
  if (template && template.templateContent) {
    // Use custom template
    await generatePDFFromTemplate(doc, template.templateContent, request)
  } else {
    // Use default template
    generateDefaultPDF(doc, request)
  }
  
  return doc
}

async function generatePDFFromTemplate(doc: jsPDF, templateContent: string, request: any) {
  const submissionData = request.submissionData
  
  // Replace placeholders with actual data
  let processedContent = templateContent
    .replace(/\{\{trackingNumber\}\}/g, request.trackingNumber)
    .replace(/\{\{serviceName\}\}/g, request.service.title)
    .replace(/\{\{userName\}\}/g, request.user.name)
    .replace(/\{\{userEmail\}\}/g, request.user.email)
    .replace(/\{\{status\}\}/g, getStatusLabel(request.status))
    .replace(/\{\{createdAt\}\}/g, new Date(request.createdAt).toLocaleString('id-ID'))
    .replace(/\{\{fullName\}\}/g, submissionData.fullName || submissionData.name || '-')
    .replace(/\{\{placeOfBirth\}\}/g, submissionData.placeOfBirth || '-')
    .replace(/\{\{dateOfBirth\}\}/g, submissionData.dateOfBirth || '-')
    .replace(/\{\{gender\}\}/g, submissionData.gender === 'L' ? 'Laki-laki' : 'Perempuan')
    .replace(/\{\{religion\}\}/g, submissionData.religion || '-')
    .replace(/\{\{occupation\}\}/g, submissionData.occupation || '-')
    .replace(/\{\{address\}\}/g, submissionData.address || '-')
    .replace(/\{\{phone\}\}/g, submissionData.phone || '-')
    .replace(/\{\{identityNumber\}\}/g, submissionData.identityNumber || '-')
    .replace(/\{\{purpose\}\}/g, submissionData.purpose || '-')
    .replace(/\{\{reportType\}\}/g, submissionData.reportType || '-')
    .replace(/\{\{incidentDate\}\}/g, submissionData.incidentDate || '-')
    .replace(/\{\{incidentLocation\}\}/g, submissionData.incidentLocation || '-')
    .replace(/\{\{incidentDescription\}\}/g, submissionData.incidentDescription || '-')
    .replace(/\{\{witnessInfo\}\}/g, submissionData.witnessInfo || '-')
    .replace(/\{\{serviceType\}\}/g, submissionData.serviceType || '-')
    .replace(/\{\{vehicleType\}\}/g, submissionData.vehicleType || '-')
    .replace(/\{\{vehicleBrand\}\}/g, submissionData.vehicleBrand || '-')
    .replace(/\{\{vehicleTypeDetail\}\}/g, submissionData.vehicleTypeDetail || '-')
    .replace(/\{\{vehicleColor\}\}/g, submissionData.vehicleColor || '-')
    .replace(/\{\{vehicleNumber\}\}/g, submissionData.vehicleNumber || '-')
  
  // Split content into lines and add to PDF
  const lines = processedContent.split('\n')
  let yPos = 20
  
  doc.setFont('helvetica')
  doc.setFontSize(12)
  
  lines.forEach(line => {
    if (yPos > 270) {
      doc.addPage()
      yPos = 20
    }
    
    // Handle different font sizes based on content
    if (line.includes('===') || line.includes('###')) {
      doc.setFontSize(16)
      line = line.replace(/===|###/g, '').trim()
    } else if (line.includes('---') || line.includes('##')) {
      doc.setFontSize(14)
      line = line.replace(/---|##/g, '').trim()
    } else {
      doc.setFontSize(12)
    }
    
    doc.text(line, 20, yPos)
    yPos += 7
  })
  
  // Add footer
  doc.setFontSize(10)
  const footerY = 280
  doc.text('Dokumen ini dicetak secara otomatis oleh sistem.', 20, footerY)
  doc.text(`Tanggal cetak: ${new Date().toLocaleString('id-ID')}`, 20, footerY + 5)
}

function generateDefaultPDF(doc: jsPDF, request: any) {
  const submissionData = request.submissionData as any
  
  // Set font
  doc.setFont('helvetica')
  
  // Header
  doc.setFontSize(20)
  doc.text('POLRES WONOSOBO', 105, 20, { align: 'center' })
  doc.setFontSize(16)
  doc.text('BUKTI PENGAJUAN LAYANAN', 105, 30, { align: 'center' })
  
  // Line
  doc.setLineWidth(0.5)
  doc.line(20, 35, 190, 35)
  
  // Tracking info
  doc.setFontSize(12)
  doc.text(`Nomor Tracking: ${request.trackingNumber}`, 20, 45)
  doc.text(`Tanggal: ${new Date(request.createdAt).toLocaleString('id-ID')}`, 20, 52)
  doc.text(`Layanan: ${request.service.title}`, 20, 59)
  
  // Data Pemohon section
  doc.setFontSize(14)
  doc.text('DATA PEMOHON:', 20, 75)
  doc.setLineWidth(0.3)
  doc.line(20, 78, 190, 78)
  
  doc.setFontSize(11)
  let yPos = 85
  
  // Common fields
  const fields = [
    { label: 'Nama', value: submissionData.fullName || submissionData.name || '-' },
    { label: 'Email', value: request.user.email },
    { label: 'Tempat/Tanggal Lahir', value: `${submissionData.placeOfBirth || '-'}, ${submissionData.dateOfBirth || '-'}` },
    { label: 'Jenis Kelamin', value: submissionData.gender === 'L' ? 'Laki-laki' : 'Perempuan' },
    { label: 'Agama', value: submissionData.religion || '-' },
    { label: 'Pekerjaan', value: submissionData.occupation || '-' },
    { label: 'Alamat', value: submissionData.address || '-' },
    { label: 'Telepon', value: submissionData.phone || '-' },
    { label: 'No. KTP', value: submissionData.identityNumber || '-' }
  ]
  
  fields.forEach(field => {
    doc.text(`${field.label}: ${field.value}`, 20, yPos)
    yPos += 7
  })
  
  // Service-specific fields
  if (request.service.slug === 'skck') {
    doc.text(`Keperluan: ${submissionData.purpose || '-'}`, 20, yPos)
    yPos += 7
  } else if (request.service.slug === 'spkt') {
    doc.text(`Jenis Laporan: ${submissionData.reportType || '-'}`, 20, yPos)
    yPos += 7
    doc.text(`Tanggal Kejadian: ${submissionData.incidentDate || '-'}`, 20, yPos)
    yPos += 7
    doc.text(`Lokasi Kejadian: ${submissionData.incidentLocation || '-'}`, 20, yPos)
    yPos += 7
  } else if (request.service.slug === 'lalu-lintas') {
    doc.text(`Jenis Layanan: ${submissionData.serviceType || '-'}`, 20, yPos)
    yPos += 7
    doc.text(`Jenis Kendaraan: ${submissionData.vehicleType || '-'}`, 20, yPos)
    yPos += 7
    doc.text(`Merek Kendaraan: ${submissionData.vehicleBrand || '-'}`, 20, yPos)
    yPos += 7
    doc.text(`Nomor Polisi: ${submissionData.vehicleNumber || '-'}`, 20, yPos)
    yPos += 7
  }
  
  // Status section
  yPos += 10
  doc.setFontSize(14)
  doc.text('STATUS:', 20, yPos)
  doc.setLineWidth(0.3)
  doc.line(20, yPos + 3, 190, yPos + 3)
  
  doc.setFontSize(12)
  const statusLabel = getStatusLabel(request.status)
  doc.text(statusLabel, 20, yPos + 10)
  
  // Footer
  doc.setFontSize(10)
  const footerY = 280
  doc.text('Dokumen ini dicetak secara otomatis oleh sistem.', 20, footerY)
  doc.text(`Tanggal cetak: ${new Date().toLocaleString('id-ID')}`, 20, footerY + 5)
  doc.text('Polres Wonosobo', 105, footerY + 15, { align: 'center' })
  doc.text(new Date().getFullYear().toString(), 105, footerY + 20, { align: 'center' })
}

function getStatusLabel(status: string): string {
  switch (status) {
    case 'PENDING':
      return 'Status: Menunggu Verifikasi'
    case 'IN_PROGRESS':
      return 'Status: Sedang Diproses'
    case 'NEED_REVISION':
      return 'Status: Perlu Revisi'
    case 'REVIEWING':
      return 'Status: Sedang Ditinjau'
    case 'COMPLETED':
      return 'Status: Selesai'
    default:
      return `Status: ${status}`
  }
}