"use client";

import { useEffect, useRef } from "react";
import type { OfficeTimezone } from "@/lib/timezone";

interface WatermarkCanvasProps {
  photo: Blob;
  latitude: number;
  longitude: number;
  capturedAt: Date;
  /** The office timezone the capture time is shown in, matching the server watermark. */
  timezone: OfficeTimezone;
  className?: string;
}

/**
 * Preview-only overlay so the employee can see what they're about to
 * submit. This is NOT the record of truth — the backend re-renders its own
 * watermark server-side onto the stored photo, since a client-drawn canvas
 * can't be trusted for the audit trail.
 */
export function WatermarkCanvas({ photo, latitude, longitude, capturedAt, timezone, className }: WatermarkCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext("2d");
    if (!canvas || !ctx) return;

    const objectUrl = URL.createObjectURL(photo);
    const image = new Image();
    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      ctx.drawImage(image, 0, 0);
      drawWatermark(ctx, canvas.width, canvas.height, latitude, longitude, capturedAt, timezone);
      URL.revokeObjectURL(objectUrl);
    };
    image.src = objectUrl;

    return () => URL.revokeObjectURL(objectUrl);
  }, [photo, latitude, longitude, capturedAt, timezone]);

  return <canvas ref={canvasRef} className={className} />;
}

function drawWatermark(
  ctx: CanvasRenderingContext2D,
  width: number,
  height: number,
  latitude: number,
  longitude: number,
  capturedAt: Date,
  timezone: OfficeTimezone,
) {
  const lines = [
    `${capturedAt.toLocaleString("id-ID", { dateStyle: "full", timeStyle: "medium", timeZone: timezone.timeZone })} ${timezone.label}`,
    `Lat ${latitude.toFixed(6)}, Long ${longitude.toFixed(6)}`,
  ];

  const padding = Math.max(12, width * 0.02);
  const fontSize = Math.max(14, Math.round(width * 0.028));
  const lineHeight = fontSize * 1.4;
  const boxHeight = lineHeight * lines.length + padding;

  ctx.fillStyle = "rgba(0, 0, 0, 0.55)";
  ctx.fillRect(0, height - boxHeight, width, boxHeight);

  ctx.font = `${fontSize}px sans-serif`;
  ctx.fillStyle = "#ffffff";
  ctx.textBaseline = "top";
  lines.forEach((line, index) => {
    ctx.fillText(line, padding, height - boxHeight + padding / 2 + index * lineHeight);
  });
}
