import { supabase } from "@/integrations/supabase/client";
import QRCode from "qrcode";
import { v4 as uuidv4 } from "uuid";
import { format } from "date-fns";
import { toZonedTime } from "date-fns-tz";
import type jsPDF from "jspdf";

const TZ = "America/New_York";

interface EmbedValidationOptions {
  documentTitle: string;
  documentType: string;
  documentDate?: string;
  associationId?: string;
  metadata?: Record<string, any>;
}

/**
 * Draws a compact validation proof block at the bottom of the current page.
 * Returns the validation record from the database.
 *
 * Layout (bottom of page):
 *  ─────────────────────────────────────
 *  [QR 75x75]  VALIDATION CERTIFICATE
 *              Document: ...
 *              Date: ...     Generated: ...
 *              ID: xxxxxxxx-xxxx  Hash: abcdef...
 *              Scan QR or visit URL to verify
 *  ─────────────────────────────────────
 */
export async function embedValidationProof(
  doc: jsPDF,
  options: EmbedValidationOptions,
) {
  const now = new Date();
  const estNow = toZonedTime(now, TZ);
  const generatedStr = format(estNow, "MMM d, yyyy h:mm a");

  // Create verification hash
  const raw = `${now.toISOString()}-${crypto.randomUUID()}`;
  const hashBuffer = await crypto.subtle.digest(
    "SHA-256",
    new TextEncoder().encode(raw),
  );
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const verificationHash = hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")
    .slice(0, 32);

  // Get current user
  const {
    data: { user },
  } = await supabase.auth.getUser();

  // Save to database
  const { data: proof, error } = await supabase
    .from("document_validation_proofs")
    .insert({
      document_type: options.documentType,
      document_title: options.documentTitle || "Untitled Document",
      generated_at: now.toISOString(),
      generated_by: user?.id || null,
      association_id: options.associationId || null,
      metadata: options.metadata || {},
      verification_hash: verificationHash,
    })
    .select()
    .single();

  if (error) {
    console.error("[EmbedValidation] DB error:", error);
    throw error;
  }

  const verifyUrl = `https://avria.cloud/verify/${proof.id}`;

  // Generate QR code
  const qrDataUrl = await QRCode.toDataURL(verifyUrl, {
    width: 150,
    margin: 1,
    color: { dark: "#1a1a2e", light: "#ffffff" },
    errorCorrectionLevel: "H",
  });

  // --- Draw on PDF ---
  const pageW = doc.internal.pageSize.getWidth();
  const pageH = doc.internal.pageSize.getHeight();
  const margin = 60; // match agenda margin
  const qrSize = 55; // ~75px at 72 dpi ≈ 55pt
  const blockH = qrSize + 16; // total height of block
  const startY = pageH - 40 - blockH; // 40pt from bottom

  // Top rule
  doc.setDrawColor(180, 180, 180);
  doc.setLineWidth(0.5);
  doc.line(margin, startY, pageW - margin, startY);

  const contentY = startY + 10;

  // QR code
  doc.addImage(qrDataUrl, "PNG", margin, contentY, qrSize, qrSize);

  // Text block to the right of QR
  const textX = margin + qrSize + 12;
  let ty = contentY + 8;

  doc.setFont("helvetica", "bold");
  doc.setFontSize(8);
  doc.setTextColor(26, 26, 46);
  doc.text("VALIDATION CERTIFICATE", textX, ty);

  ty += 10;
  doc.setFont("helvetica", "normal");
  doc.setFontSize(7);
  doc.setTextColor(80, 80, 80);
  doc.text(`Document: ${options.documentTitle}`, textX, ty);

  ty += 9;
  const dateLabel = options.documentDate || "";
  if (dateLabel) {
    doc.text(`Date: ${dateLabel}`, textX, ty);
    doc.text(`Generated: ${generatedStr}`, textX + 160, ty);
  } else {
    doc.text(`Generated: ${generatedStr}`, textX, ty);
  }

  ty += 9;
  doc.setFont("courier", "normal");
  doc.setFontSize(6);
  doc.setTextColor(100, 100, 100);
  doc.text(`ID: ${proof.id}`, textX, ty);

  ty += 8;
  doc.text(`Hash: ${verificationHash}`, textX, ty);

  ty += 8;
  doc.setFont("helvetica", "italic");
  doc.setFontSize(6);
  doc.setTextColor(140, 140, 140);
  doc.text("Scan QR code or visit avria.cloud/verify to confirm authenticity.", textX, ty);

  // Bottom rule
  doc.setDrawColor(180, 180, 180);
  doc.setLineWidth(0.5);
  doc.line(margin, startY + blockH + 6, pageW - margin, startY + blockH + 6);

  return proof;
}
