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 complaint with all relations
  const complaint = await db.CustomerComplaintRegister.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.Material,
        as: 'material',
        attributes: ['id', 'material_number', 'description']
      },
      {
        model: db.User,
        as: 'assignedUser',
        attributes: ['id', 'username', 'email']
      }
    ]
  });

  if (!complaint) {
    return sendError(res, 'Customer Complaint Register not found', 404);
  }

  // Fetch Print Header for logo
  const printHeader = await db.PrintHeader.findOne({
    where: { company_id: complaint.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 in landscape A4
  const doc = new PDFDocument({ 
    margin: 30, 
    size: 'A4', 
    layout: 'landscape',
    bufferPages: true 
  });
  
  const filename = `CCR_${complaint.ccr_no || complaint.id}.pdf`;
  
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
  
  doc.pipe(res);

  // Page dimensions (landscape A4)
  const pageWidth = 841.89;
  const pageHeight = 595.28;
  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 ===
  const headerHeight = 70;
  
  // 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, below logo)
  doc.font('Helvetica-Bold').fontSize(12).fillColor(primaryColor);
  doc.text(complaint.company?.name || 'RAM Industries', margin, currentY + 45, {
    width: 150,
    align: 'left'
  });

  // Document info box (top right)
  const docBoxX = pageWidth - margin - 110;
  const docBoxY = currentY;
  const docBoxW = 110;
  const docBoxH = 45;
  
  drawRect(docBoxX, docBoxY, docBoxW, docBoxH, true, lightBg);
  drawText('RI/QA/F/08', docBoxX, docBoxY, docBoxW, 15, { align: 'center', bold: true, fontSize: 9 });
  doc.moveTo(docBoxX, docBoxY + 15).lineTo(docBoxX + docBoxW, docBoxY + 15).stroke();
  drawText(`Rev ${complaint.rev_no || '0/01.10.18'}`, docBoxX, docBoxY + 15, docBoxW, 15, { align: 'center', fontSize: 7 });
  doc.moveTo(docBoxX, docBoxY + 30).lineTo(docBoxX + docBoxW, docBoxY + 30).stroke();
  drawText(complaint.rev_date || '2018-10-01', docBoxX, docBoxY + 30, docBoxW, 15, { align: 'center', fontSize: 7 });

  currentY += headerHeight + 10;

  // === TITLE ===
  doc.font('Helvetica-Bold').fontSize(14).fillColor(primaryColor);
  doc.text('CUSTOMER COMPLAINT REGISTER', margin, currentY, {
    width: contentWidth,
    align: 'center'
  });

  currentY += 25;

  // === TABLE STRUCTURE ===
  const tableStartY = currentY;
  const rowHeight = 70;
  
  // Optimized column widths to fit within page (total = 781.89)
  const col1 = 60;   // Date
  const col2 = 95;   // Customer
  const col3 = 70;   // Mode
  const col4 = 95;   // Part Name, Part No
  const col5 = 135;  // Complaint Description
  const col6 = 65;   // CAR Ref No
  const col7 = 105;  // Action Taken
  const col8 = 75;   // Closure Status
  const col9 = 82;   // Remarks/Sign

  const totalTableWidth = col1 + col2 + col3 + col4 + col5 + col6 + col7 + col8 + col9;

  // Draw header row with styled background
  drawRect(margin, currentY, totalTableWidth, 30, true, lightBg);

  // Header labels
  let colX = margin;
  drawText('Date', colX, currentY, col1, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col1, currentY).lineTo(colX + col1, currentY + 30).stroke();
  colX += col1;
  
  drawText('Customer', colX, currentY, col2, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col2, currentY).lineTo(colX + col2, currentY + 30).stroke();
  colX += col2;
  
  drawText('Mode (Oral\n/ Phone /\nLetter / Mail)', colX, currentY, col3, 30, { align: 'center', bold: true, fontSize: 7, valign: 'middle' });
  doc.moveTo(colX + col3, currentY).lineTo(colX + col3, currentY + 30).stroke();
  colX += col3;
  
  drawText('Part Name,\nPart No', colX, currentY, col4, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col4, currentY).lineTo(colX + col4, currentY + 30).stroke();
  colX += col4;
  
  drawText('Complaint\nDescription', colX, currentY, col5, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col5, currentY).lineTo(colX + col5, currentY + 30).stroke();
  colX += col5;
  
  drawText('CAR Ref\nNo.', colX, currentY, col6, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col6, currentY).lineTo(colX + col6, currentY + 30).stroke();
  colX += col6;
  
  drawText('Action Taken\n(briefly)', colX, currentY, col7, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col7, currentY).lineTo(colX + col7, currentY + 30).stroke();
  colX += col7;
  
  drawText('Closure\nStatus', colX, currentY, col8, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });
  doc.moveTo(colX + col8, currentY).lineTo(colX + col8, currentY + 30).stroke();
  colX += col8;
  
  drawText('Remarks /\nSign', colX, currentY, col9, 30, { align: 'center', bold: true, fontSize: 8, valign: 'middle' });

  currentY += 30;

  // === DATA ROW ===
  drawRect(margin, currentY, totalTableWidth, rowHeight);

  colX = margin;
  
  // Date
  drawText(complaint.ccr_date || '', colX, currentY, col1, rowHeight, { align: 'center', fontSize: 8 });
  doc.moveTo(colX + col1, currentY).lineTo(colX + col1, currentY + rowHeight).stroke();
  colX += col1;
  
  // Customer
  const customerName = complaint.customer_name || complaint.customer?.name || '';
  drawText(customerName, colX, currentY, col2, rowHeight, { fontSize: 7 });
  doc.moveTo(colX + col2, currentY).lineTo(colX + col2, currentY + rowHeight).stroke();
  colX += col2;
  
  // Mode
  drawText(complaint.mode_of_complaint || '', colX, currentY, col3, rowHeight, { align: 'center', fontSize: 7 });
  doc.moveTo(colX + col3, currentY).lineTo(colX + col3, currentY + rowHeight).stroke();
  colX += col3;
  
  // Part Name, Part No
  const partInfo = `${complaint.part_name || ''}\n${complaint.part_no || ''}`;
  drawText(partInfo, colX, currentY, col4, rowHeight, { fontSize: 7 });
  doc.moveTo(colX + col4, currentY).lineTo(colX + col4, currentY + rowHeight).stroke();
  colX += col4;
  
  // Complaint Description
  drawText(complaint.complaint_description || '', colX, currentY, col5, rowHeight, { fontSize: 7 });
  doc.moveTo(colX + col5, currentY).lineTo(colX + col5, currentY + rowHeight).stroke();
  colX += col5;
  
  // CAR Ref No
  drawText(complaint.car_ref_no || '', colX, currentY, col6, rowHeight, { align: 'center', fontSize: 7 });
  doc.moveTo(colX + col6, currentY).lineTo(colX + col6, currentY + rowHeight).stroke();
  colX += col6;
  
  // Action Taken
  drawText(complaint.action_taken || '', colX, currentY, col7, rowHeight, { fontSize: 7 });
  doc.moveTo(colX + col7, currentY).lineTo(colX + col7, currentY + rowHeight).stroke();
  colX += col7;
  
  // Closure Status
  const closureStatus = complaint.closure_status?.replace(/_/g, ' ') || '';
  drawText(closureStatus, colX, currentY, col8, rowHeight, { align: 'center', fontSize: 7 });
  doc.moveTo(colX + col8, currentY).lineTo(colX + col8, currentY + rowHeight).stroke();
  colX += col8;
  
  // Remarks/Sign
  drawText(complaint.remarks || '', colX, currentY, col9, rowHeight, { fontSize: 7 });

  currentY += rowHeight;

  // Add 5 more empty rows
  for (let row = 0; row < 5; row++) {
    drawRect(margin, currentY, totalTableWidth, rowHeight);
    
    // Draw vertical lines
    colX = margin;
    const cols = [col1, col2, col3, col4, col5, col6, col7, col8, col9];
    for (let i = 0; i < cols.length; i++) {
      colX += cols[i];
      doc.moveTo(colX, currentY).lineTo(colX, currentY + rowHeight).stroke();
    }
    
    currentY += rowHeight;
  }

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

module.exports = exports;
