const db = require('../models');
const { sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const PDFDocument = require('pdfkit');
const path = require('path');
const fs = require('fs');

exports.generatePDF = asyncHandler(async (req, res) => {
  const { id } = req.params;

  // Fetch checklist with all relations
  const checkList = await db.InProcessCheckList.findByPk(id, {
    include: [
      {
        model: db.Company,
        as: 'company',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.Plant,
        as: 'plant',
        attributes: ['id', 'code', 'name']
      },
      {
        model: db.BusinessPartner,
        as: 'customer',
        attributes: ['id', 'bp_number', 'name', 'legal_name']
      },
      {
        model: db.InProcessCheckListDetail,
        as: 'details',
        order: [['line_no', 'ASC']]
      }
    ]
  });

  if (!checkList) {
    return sendError(res, 'In-Process CheckList not found', 404);
  }

  // Fetch Print Header for logo
  const printHeader = await db.PrintHeader.findOne({
    where: { company_id: checkList.company_id, status: 'ACTIVE' },
    order: [['id', 'DESC']]
  });

  let companyLogoPath = null;
  if (printHeader?.logo_path) {
    let fullPath = path.join(__dirname, '..', 'uploads', printHeader.logo_path);
    if (fs.existsSync(fullPath)) {
      companyLogoPath = fullPath;
    } else {
      fullPath = path.join(__dirname, '..', printHeader.logo_path);
      if (fs.existsSync(fullPath)) companyLogoPath = fullPath;
    }
  }

  // Create PDF
  const doc = new PDFDocument({ 
    margin: 30, 
    size: 'A4',
    bufferPages: true 
  });
  
  const filename = `IPC_${checkList.ipc_no || checkList.id}.pdf`;
  
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
  
  doc.pipe(res);

  // Page dimensions (Portrait A4)
  const pageWidth = 595.28;
  const pageHeight = 841.89;
  const margin = 30;
  const contentWidth = pageWidth - (margin * 2);

  const primaryColor = '#2C3E50';
  const lightBg = '#ECF0F1';
  const borderColor = '#34495E';

  // Helper functions
  const drawRect = (x, y, w, h, fill = false, fillColor = null) => {
    doc.save();
    if (fill && fillColor) {
      doc.fillColor(fillColor).rect(x, y, w, h).fill();
    }
    doc.lineWidth(0.75);
    doc.strokeColor(borderColor).rect(x, y, w, h).stroke();
    doc.restore();
  };

  const drawText = (text, x, y, w, h, opts = {}) => {
    const {
      align = 'left',
      valign = 'top',
      fontSize = 8,
      bold = false,
      padding = 3
    } = opts;

    if (text === null || text === undefined) text = '';
    text = String(text);

    doc.save();
    doc.font(bold ? 'Helvetica-Bold' : 'Helvetica');
    doc.fontSize(fontSize);
    doc.fillColor('#000000');

    const textOpts = {
      width: w - (padding * 2),
      align: align,
      lineBreak: true
    };

    let textX = x + padding;
    let textY = y + padding;

    if (valign === 'middle') {
      const textHeight = doc.heightOfString(text, textOpts);
      textY = y + (h - textHeight) / 2;
    }

    doc.text(text, textX, textY, textOpts);
    doc.restore();
  };

  let currentY = margin;

  // === HEADER SECTION ===
  // Company Logo (left side)
  if (companyLogoPath) {
    try {
      doc.image(companyLogoPath, margin, currentY, { width: 80, height: 40, fit: [80, 40] });
    } catch (error) {
      console.error('Error loading logo:', error);
    }
  }

  // Company Name (left side)
  doc.font('Helvetica-Bold').fontSize(11).fillColor(primaryColor);
  doc.text(checkList.company?.name || 'RAM Industries', margin, currentY + 45, {
    width: 150,
    align: 'left'
  });

  // Document info box (top right)
  const docBoxX = pageWidth - margin - 100;
  const docBoxY = currentY;
  const docBoxW = 100;
  const docBoxH = 45;
  
  drawRect(docBoxX, docBoxY, docBoxW, docBoxH, true, lightBg);
  drawText('RI/QA/F/09', docBoxX, docBoxY, docBoxW, 15, { align: 'center', bold: true, fontSize: 9 });
  doc.moveTo(docBoxX, docBoxY + 15).lineTo(docBoxX + docBoxW, docBoxY + 15).stroke();
  drawText(`Rev ${checkList.rev_no || '0 / 05.10.2018'}`, docBoxX, docBoxY + 15, docBoxW, 15, { align: 'center', fontSize: 7 });
  doc.moveTo(docBoxX, docBoxY + 30).lineTo(docBoxX + docBoxW, docBoxY + 30).stroke();
  drawText(new Date().toLocaleDateString(), docBoxX, docBoxY + 30, docBoxW, 15, { align: 'center', fontSize: 7 });

  currentY += 70;

  // === TITLE ===
  doc.font('Helvetica-Bold').fontSize(13).fillColor(primaryColor);
  doc.text('IN-PROCESS CHECK LIST', margin, currentY, {
    width: contentWidth,
    align: 'center'
  });

  currentY += 25;

  // === HEADER INFO BOX ===
  const infoBoxHeight = 60;
  drawRect(margin, currentY, contentWidth, infoBoxHeight, true, lightBg);

  // Info fields
  const infoY = currentY;
  const infoFieldHeight = 20;
  
  // Row 1: WON, Customer, Customer Name
  drawText('WON', margin + 5, infoY + 5, 60, infoFieldHeight, { bold: true, fontSize: 7 });
  drawText(checkList.work_order_no || '', margin + 65, infoY + 5, 150, infoFieldHeight, { fontSize: 8 });
  
  drawText('Customer', margin + 220, infoY + 5, 60, infoFieldHeight, { bold: true, fontSize: 7 });
  const customerName = checkList.customer_name || checkList.customer?.name || '';
  drawText(customerName, margin + 280, infoY + 5, contentWidth - 285, infoFieldHeight, { fontSize: 8 });

  // Row 2: Model, Total Qty, Date
  drawText('Model', margin + 5, infoY + 25, 60, infoFieldHeight, { bold: true, fontSize: 7 });
  drawText(checkList.model || '', margin + 65, infoY + 25, 150, infoFieldHeight, { fontSize: 8 });
  
  drawText('Total Qty', margin + 220, infoY + 25, 60, infoFieldHeight, { bold: true, fontSize: 7 });
  drawText(checkList.total_qty || '', margin + 280, infoY + 25, 100, infoFieldHeight, { fontSize: 8 });
  
  drawText('Date', margin + 385, infoY + 25, 40, infoFieldHeight, { bold: true, fontSize: 7 });
  drawText(checkList.ipc_date || '', margin + 425, infoY + 25, contentWidth - 430, infoFieldHeight, { fontSize: 8 });

  currentY += infoBoxHeight + 10;

  // === DETAIL TABLE ===
  const tableStartY = currentY;
  const headerHeight = 30;
  const rowHeight = 50;
  
  // Column widths
  const colSNo = 35;
  const colDesc = 130;
  const colDrawing = 80;
  const colModel = 80;
  const colQtySet = 60;
  const colTotalQty = 60;
  const colQC = 50;
  const colRemarks = 40;

  // Draw table header
  drawRect(margin, currentY, contentWidth, headerHeight, true, lightBg);

  let colX = margin;
  drawText('S.No', colX, currentY, colSNo, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colSNo, currentY).lineTo(colX + colSNo, currentY + headerHeight).stroke();
  colX += colSNo;

  drawText('Item Description', colX, currentY, colDesc, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colDesc, currentY).lineTo(colX + colDesc, currentY + headerHeight).stroke();
  colX += colDesc;

  drawText('Drawing No.', colX, currentY, colDrawing, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colDrawing, currentY).lineTo(colX + colDrawing, currentY + headerHeight).stroke();
  colX += colDrawing;

  drawText('Model', colX, currentY, colModel, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colModel, currentY).lineTo(colX + colModel, currentY + headerHeight).stroke();
  colX += colModel;

  drawText('Qty/Set', colX, currentY, colQtySet, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colQtySet, currentY).lineTo(colX + colQtySet, currentY + headerHeight).stroke();
  colX += colQtySet;

  drawText('Total Qty', colX, currentY, colTotalQty, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colTotalQty, currentY).lineTo(colX + colTotalQty, currentY + headerHeight).stroke();
  colX += colTotalQty;

  drawText('QC', colX, currentY, colQC, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + colQC, currentY).lineTo(colX + colQC, currentY + headerHeight).stroke();
  colX += colQC;

  drawText('Remarks', colX, currentY, colRemarks, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });

  currentY += headerHeight;

  // Draw detail rows
  const detailsToShow = checkList.details && checkList.details.length > 0 ? checkList.details : [];
  const minRows = 10; // Show at least 10 rows
  const totalRows = Math.max(detailsToShow.length, minRows);

  for (let i = 0; i < totalRows; i++) {
    const detail = detailsToShow[i] || {};
    
    drawRect(margin, currentY, contentWidth, rowHeight);

    colX = margin;
    
    // S.No
    drawText(detail.line_no || (i + 1), colX, currentY, colSNo, rowHeight, { align: 'center', fontSize: 8, valign: 'middle' });
    doc.moveTo(colX + colSNo, currentY).lineTo(colX + colSNo, currentY + rowHeight).stroke();
    colX += colSNo;

    // Item Description
    drawText(detail.item_description || '', colX, currentY, colDesc, rowHeight, { fontSize: 7 });
    doc.moveTo(colX + colDesc, currentY).lineTo(colX + colDesc, currentY + rowHeight).stroke();
    colX += colDesc;

    // Drawing No
    drawText(detail.drawing_no || '', colX, currentY, colDrawing, rowHeight, { fontSize: 7, align: 'center', valign: 'middle' });
    doc.moveTo(colX + colDrawing, currentY).lineTo(colX + colDrawing, currentY + rowHeight).stroke();
    colX += colDrawing;

    // Model
    drawText(detail.model || '', colX, currentY, colModel, rowHeight, { fontSize: 7, align: 'center', valign: 'middle' });
    doc.moveTo(colX + colModel, currentY).lineTo(colX + colModel, currentY + rowHeight).stroke();
    colX += colModel;

    // Qty/Set
    drawText(detail.qty_per_set || '', colX, currentY, colQtySet, rowHeight, { fontSize: 7, align: 'center', valign: 'middle' });
    doc.moveTo(colX + colQtySet, currentY).lineTo(colX + colQtySet, currentY + rowHeight).stroke();
    colX += colQtySet;

    // Total Qty
    drawText(detail.total_qty || '', colX, currentY, colTotalQty, rowHeight, { fontSize: 7, align: 'center', valign: 'middle' });
    doc.moveTo(colX + colTotalQty, currentY).lineTo(colX + colTotalQty, currentY + rowHeight).stroke();
    colX += colTotalQty;

    // QC
    drawText(detail.qc_status || '', colX, currentY, colQC, rowHeight, { fontSize: 7, align: 'center', valign: 'middle' });
    doc.moveTo(colX + colQC, currentY).lineTo(colX + colQC, currentY + rowHeight).stroke();
    colX += colQC;

    // Remarks
    drawText(detail.remarks || '', colX, currentY, colRemarks, rowHeight, { fontSize: 6 });

    currentY += rowHeight;

    // Check if we need a new page
    if (currentY > pageHeight - 100 && i < totalRows - 1) {
      doc.addPage({ margin: 30, size: 'A4' });
      currentY = margin;
      
      // Redraw header on new page
      drawRect(margin, currentY, contentWidth, headerHeight, true, lightBg);
      
      colX = margin;
      drawText('S.No', colX, currentY, colSNo, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colSNo, currentY).lineTo(colX + colSNo, currentY + headerHeight).stroke();
      colX += colSNo;

      drawText('Item Description', colX, currentY, colDesc, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colDesc, currentY).lineTo(colX + colDesc, currentY + headerHeight).stroke();
      colX += colDesc;

      drawText('Drawing No.', colX, currentY, colDrawing, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colDrawing, currentY).lineTo(colX + colDrawing, currentY + headerHeight).stroke();
      colX += colDrawing;

      drawText('Model', colX, currentY, colModel, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colModel, currentY).lineTo(colX + colModel, currentY + headerHeight).stroke();
      colX += colModel;

      drawText('Qty/Set', colX, currentY, colQtySet, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colQtySet, currentY).lineTo(colX + colQtySet, currentY + headerHeight).stroke();
      colX += colQtySet;

      drawText('Total Qty', colX, currentY, colTotalQty, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colTotalQty, currentY).lineTo(colX + colTotalQty, currentY + headerHeight).stroke();
      colX += colTotalQty;

      drawText('QC', colX, currentY, colQC, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
      doc.moveTo(colX + colQC, currentY).lineTo(colX + colQC, currentY + headerHeight).stroke();
      colX += colQC;

      drawText('Remarks', colX, currentY, colRemarks, headerHeight, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });

      currentY += headerHeight;
    }
  }

  // Finalize PDF
  doc.end();
});

module.exports = exports;
