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

const TZ = "America/New_York";

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

/**
 * Generate a validation proof certificate with QR code.
 * Saves a record to document_validation_proofs and generates a PDF certificate.
 */
export async function generateValidationProof(opts: ProofOptions) {
  const now = new Date();
  const estNow = toZonedTime(now, TZ);
  const dateStr = format(estNow, "MMMM d, yyyy");
  const timeStr = format(estNow, "h:mm:ss a z");
  const fullTimestamp = format(estNow, "yyyy-MM-dd'T'HH:mm:ss");

  // Create a verification hash from timestamp + random
  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: opts.documentType,
    document_title: opts.documentTitle || "Untitled Document",
    generated_at: now.toISOString(),
    generated_by: user?.id || null,
    association_id: opts.associationId || null,
    metadata: opts.metadata || {},
    verification_hash: verificationHash,
  }).select().single();

  if (error) throw error;

  // Build verification URL
  const baseUrl = "https://avria.cloud";
  const verifyUrl = `${baseUrl}/verify/${proof.id}`;

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

  // Generate certificate PDF
  const doc = new jsPDF({ orientation: "portrait", unit: "mm", format: "letter" });
  const pageW = doc.internal.pageSize.getWidth();
  const pageH = doc.internal.pageSize.getHeight();
  const centerX = pageW / 2;

  // Border
  doc.setDrawColor(26, 26, 46);
  doc.setLineWidth(1.5);
  doc.rect(15, 15, pageW - 30, pageH - 30);
  doc.setLineWidth(0.5);
  doc.rect(18, 18, pageW - 36, pageH - 36);

  // Header
  let y = 40;
  doc.setFont("helvetica", "bold");
  doc.setFontSize(24);
  doc.setTextColor(26, 26, 46);
  doc.text("CERTIFICATE OF VALIDATION", centerX, y, { align: "center" });

  y += 12;
  doc.setFontSize(10);
  doc.setTextColor(100, 100, 100);
  doc.text("Document Authenticity & Timestamp Verification", centerX, y, { align: "center" });

  // Decorative line
  y += 8;
  doc.setDrawColor(59, 130, 246);
  doc.setLineWidth(1);
  doc.line(50, y, pageW - 50, y);

  // Document info
  y += 16;
  doc.setFont("helvetica", "normal");
  doc.setFontSize(11);
  doc.setTextColor(60, 60, 60);
  doc.text("This certificate confirms that the following document was generated and validated:", centerX, y, { align: "center" });

  // Form Title
  y += 16;
  doc.setFont("helvetica", "bold");
  doc.setFontSize(16);
  doc.setTextColor(26, 26, 46);
  const titleLines = doc.splitTextToSize(opts.documentTitle || "Untitled Document", pageW - 80);
  doc.text(titleLines, centerX, y, { align: "center" });
  y += titleLines.length * 8;

  // Document Date
  y += 6;
  doc.setFont("helvetica", "normal");
  doc.setFontSize(12);
  doc.setTextColor(80, 80, 80);
  const docDate = opts.documentDate || dateStr;
  doc.text(`Document Date: ${docDate}`, centerX, y, { align: "center" });

  y += 6;
  doc.setFontSize(11);
  doc.text(`Document Type: ${opts.documentType}`, centerX, y, { align: "center" });

  // Timestamp block
  y += 16;
  doc.setFillColor(245, 247, 250);
  doc.roundedRect(40, y - 4, pageW - 80, 32, 3, 3, "F");

  y += 6;
  doc.setFont("helvetica", "bold");
  doc.setFontSize(12);
  doc.setTextColor(26, 26, 46);
  doc.text("Generated On", centerX, y, { align: "center" });

  y += 8;
  doc.setFont("helvetica", "normal");
  doc.setFontSize(14);
  doc.text(dateStr, centerX, y, { align: "center" });

  y += 8;
  doc.setFontSize(11);
  doc.setTextColor(100, 100, 100);
  doc.text(timeStr, centerX, y, { align: "center" });

  // QR Code
  y += 18;
  const qrSize = 45;
  doc.addImage(qrDataUrl, "PNG", centerX - qrSize / 2, y, qrSize, qrSize);

  y += qrSize + 6;
  doc.setFontSize(8);
  doc.setTextColor(120, 120, 120);
  doc.text("Scan to verify this document", centerX, y, { align: "center" });

  // Verification details
  y += 12;
  doc.setFontSize(9);
  doc.setTextColor(100, 100, 100);
  doc.text(`Verification ID: ${proof.id}`, centerX, y, { align: "center" });
  y += 5;
  doc.text(`Hash: ${verificationHash}`, centerX, y, { align: "center" });

  // Footer
  y = pageH - 35;
  doc.setDrawColor(200, 200, 200);
  doc.setLineWidth(0.3);
  doc.line(40, y, pageW - 40, y);
  y += 6;
  doc.setFontSize(8);
  doc.setTextColor(140, 140, 140);
  doc.text("This certificate was automatically generated by Avria Community Management.", centerX, y, { align: "center" });
  y += 4;
  doc.text("Verification can be performed by scanning the QR code above or visiting the verification URL.", centerX, y, { align: "center" });

  doc.save(`Validation-Certificate-${verificationHash.slice(0, 8)}.pdf`);

  return proof;
}
