import { createCanvas, loadImage } from 'canvas';
import fs from 'fs';
import fsPromises from 'fs/promises';
import CONSTANTS from "../../config/constants";

import { CanvasRenderingContext2D } from 'canvas';

function wrapText(
  ctx: CanvasRenderingContext2D,
  text: string,
  x: number,
  y: number,
  maxWidth: number,
  lineHeight: number
) {
  const words = text.split(' ');
  let line = '';

  for (let n = 0; n < words.length; n++) {
    const testLine = line + words[n] + ' ';
    const metrics = ctx.measureText(testLine);
    const testWidth = metrics.width;
    if (testWidth > maxWidth && n > 0) {
      ctx.fillText(line, x, y);
      line = words[n] + ' ';
      y += lineHeight;
    } else {
      line = testLine;
    }
  }
  ctx.fillText(line, x, y);
  return y + lineHeight; // return new Y for next text
}

export const createRoundedImageWithPadding = async (imagePath: string, outputPath: string, padding: number = 1, radius: number = 50) => {
  const image = await loadImage(imagePath);

  // New canvas size includes padding
  const canvasWidth = image.width + padding * 2;
  const canvasHeight = image.height + padding * 2;
  const canvas = createCanvas(canvasWidth, canvasHeight);
  const ctx = canvas.getContext('2d');

  // Calculate position to center image with padding
  const x = padding;
  const y = padding;

  // Create rounded rectangle clipping path
  ctx.beginPath();
  ctx.roundRect(x, y, image.width, image.height, radius);
  ctx.clip();

  // Draw the image
  ctx.drawImage(image, x, y, image.width, image.height);

  // Save output
   const buffer = canvas.toBuffer('image/png');
  //console.log(buffer);
  fs.writeFileSync(outputPath, buffer as Uint8Array);
}


export const createBusinessCard = async (
  clientId: number,
  staffId: number,
  name: string,
  designation: string,
  businessName: string,
  mobile: string,
  email: string,
  website: string,
  address: string,
  poweredBy: boolean = false,
) => {
  const image = await loadImage('uploads/documents/defaults/template-business-card.png');

  // Create canvas and get context
  const canvas = createCanvas(1050, 600);
  const ctx = canvas.getContext('2d');

  // Draw the image on the canvas
  ctx.drawImage(image, 0, 0, 1050, 600);

        // ===== TEXT STYLES =====
        ctx.textBaseline = 'top';
ctx.fillStyle = '#fff';

// Name
name = name.split(' ').slice(0, 2).join(' ');
const textWidth = ctx.measureText(name).width;
ctx.textAlign = 'right';
const rightMargin = 200;
const x = 1050 - 60;
ctx.font = 'bold 48px "Segoe UI"';
ctx.fillText(name, x, 70);

// Title
ctx.font = '30px "Segoe UI"';
ctx.fillStyle = '#ccc';
ctx.fillText(designation, x, 125);
ctx.textAlign = 'center';

// Company
ctx.font = 'bold 50px "Segoe UI"';
ctx.fillStyle = '#fff';
ctx.fillText(businessName, 1050/2, 230);
ctx.textAlign = 'left';
ctx.restore();

// ===== CONTACT INFO =====
ctx.font = '28px "Segoe UI"';
ctx.fillStyle = '#fff';
let y = 366;
const lineGap = 47;
const maxTextWidth = 700;
const paddingLeft = 15;

y = wrapText(ctx, `${mobile}`, 100 + paddingLeft, y, maxTextWidth, lineGap);
y = wrapText(ctx, `${email}`, 100 + paddingLeft, y, maxTextWidth, lineGap);
y = wrapText(ctx, `${website}`, 100 + paddingLeft, y, maxTextWidth, lineGap);
y = wrapText(ctx, `${address}`, 100 + paddingLeft, y, maxTextWidth, 35);

if(poweredBy) {
        // ===== POWERED BY KIPINN APP =====
        //const tagline = `Powered by Kipinn`;
        const tagline = `Powered by ${businessName}`;
        ctx.font = 'italic 18px "Segoe UI"';
        ctx.fillStyle = '#ccc';
        const taglineWidth = ctx.measureText(tagline).width;
        ctx.fillText(tagline, 1050 - taglineWidth - 40, 600 - 40);
}
  // Export to file
  const buffer = canvas.toBuffer('image/png');
  //console.log(buffer);
  let folderPath=`uploads/documents/client_${clientId}`;
  if(staffId && staffId > 0) {
    folderPath = `uploads/documents/client_${clientId}/staff_${staffId}`;
  }
  const urlBase = folderPath.replace(
    "uploads/",
    `${process.env.UPLOAD_PATH}/`
  );
  if (!fs.existsSync(folderPath)) {
        await fsPromises.mkdir(folderPath, { recursive: true });
  }
  const timestamp = Date.now();

  let fileName = `business-card-${timestamp}.png`;
  fs.writeFileSync(`${folderPath}/${fileName}`, buffer as Uint8Array);
  
  createRoundedImageWithPadding(`${folderPath}/${fileName}`, `${folderPath}/${fileName}`, 5, 50);
  return {
    url: `${urlBase}/${fileName}`,
  };
};

export const roleDescription = async (role: number) => {
  switch (role) {
    case CONSTANTS.STAFF_ROLES.ADMIN:
      return "Administrator";
    case CONSTANTS.STAFF_ROLES.FINANCE_ADMIN:
      return "Finance Admin";
    case CONSTANTS.STAFF_ROLES.WARDEN:
      return "Warden";
    case CONSTANTS.STAFF_ROLES.ELECTRICIAN:
      return "Electrician";
    case CONSTANTS.STAFF_ROLES.PLUMBER:
      return "Plumber";
    case CONSTANTS.STAFF_ROLES.LAUNDRY:
      return "Laundry Staff";
    case CONSTANTS.STAFF_ROLES.CARPENTER:
      return "Carpenter";
    case CONSTANTS.STAFF_ROLES.PARTNER:
      return "Partner";
    case CONSTANTS.STAFF_ROLES.COOK:
      return "Cook";
    case CONSTANTS.STAFF_ROLES.HOUSEKEEPING:
      return "Housekeeping Staff";
    case CONSTANTS.STAFF_ROLES.SALESPERSON:
      return "Salesperson";
    case CONSTANTS.STAFF_ROLES.SECURITY_GUARD:
      return "Security Guard";
    case CONSTANTS.STAFF_ROLES.BACK_OFFICE:
      return "Back Office Staff";
    case CONSTANTS.STAFF_ROLES.HELPDESK:
      return "Help Desk Manager";
    case CONSTANTS.STAFF_ROLES.AC_TECH:
      return "AC Tech";
    case CONSTANTS.STAFF_ROLES.PURIFIER_TECH:
      return "Purifier Tech";
    default:
      return "Staff";
  }
};
