export function replaceShortcodes(html: string, data: Record<string, any>) {
  if (!html) return html;

  return html.replace(/{{\s*([^}]+)\s*}}/g, (_, key) => {
    const value = data[key.trim()];
    return value !== undefined && value !== null ? String(value) : "";
  });
}

const INCH_TO_MM = 25.4;
const PX_PER_MM = 3.78;

function resolvePaperSize(paper: {
  type: "A4" | "Letter" | "Legal" | "Custom";
  width?: number;
  height?: number;
  unit?: "mm" | "in";
}) {
  let widthMm = 210;
  let heightMm = 297;

  switch (paper.type) {
    case "A4":
      widthMm = 210;
      heightMm = 297;
      break;

    case "Letter": // 8.5in × 11in
      widthMm = 8.5 * INCH_TO_MM;
      heightMm = 11 * INCH_TO_MM;
      break;

    case "Legal": // 8.5in × 14in
      widthMm = 8.5 * INCH_TO_MM;
      heightMm = 14 * INCH_TO_MM;
      break;

    case "Custom":
      if (paper.unit === "in") {
        widthMm = (paper.width || 0) * INCH_TO_MM;
        heightMm = (paper.height || 0) * INCH_TO_MM;
      } else {
        widthMm = paper.width || 210;
        heightMm = paper.height || 297;
      }
      break;
  }

  return {
    widthMm,
    heightMm,
    widthPx: Math.round(widthMm * PX_PER_MM),
    heightPx: Math.round(heightMm * PX_PER_MM),
  };
}

export async function generatePdf({
  htmlContent,
  data,
  fileName = "document.pdf",
  showLogoInHeader = false,
  startFromHalfPage = false,
  companyLogo,
}: {
  htmlContent: string;
  data: Record<string, any>;
  fileName?: string;
  showLogoInHeader?: boolean;
  startFromHalfPage?: boolean;
  companyLogo?: string;
}) {
  const finalHtml = replaceShortcodes(htmlContent, data);

  const response = await fetch("/api/generate-pdf", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      htmlContent: finalHtml,
      paperSize: data.paperSize,
      fileName,
      showLogoInHeader,
      startFromHalfPage,
      companyLogo,
    }),
  });

  if (!response.ok) {
    throw new Error("Failed to generate PDF");
  }

  const arrayBuffer = await response.arrayBuffer();
  const pdfBlob = new Blob([arrayBuffer], { type: "application/pdf" });

  return new File([pdfBlob], fileName, {
    type: "application/pdf",
    lastModified: Date.now(),
  });
}

export const backendResponse = {
  customer_name: "Mahak Bansal, Rohan Bansal",
  customer_names: "Mahak Bansal, Rohan Bansal",
  primary_customer_name: "Mahak Bansal",
  customer_address:
    "42, Lake View Apartments, Sector 18, Gurugram, Haryana, India, 122015",
  property_name: "Skyline Residency",
  project_name: "Skyline Phase 2",
  property_id: "PROP-221",
  unit_number: "A-1203",
  floor: "12",
  tower: "A",
  unit_type: "3 BHK",
  super_area: "1850",
  area: "1450",
  basic_price: "1,20,00,000",
  booking_amount: "5,00,000",
  payment_plan: "Construction Linked",
  payment_schedule: "As per agreement",
  company_name: "City Estate Management",
  promoter_name: "Amit Verma",
  promoter_address:
    "Tower A, 4th Floor, MG Road, Indiranagar, Bengaluru, Karnataka, India, 560038",
  customer_service_number: "+91 99999 88888",
  sales_manager_name: "Rahul Sharma",
  authorized_signatory: "Authorized Signatory",
  current_date: new Date().toLocaleDateString("en-IN"),

  // Dynamic paper size
  paperSize: {
    type: "A4", // A4 | A3 | Letter | Custom
    unit: "mm",
    width: 210,
    height: 297,
  },
};
