"use client";

import { useEffect, useRef } from "react";
import { drawAnnotationsOnCanvas } from "@/lib/annotations";
import { setupHiDpiCanvas } from "@/lib/canvas";
import type { Feature, Screenshot } from "@/lib/types";

export function FeaturePreview({
  feature,
  categoryName,
}: {
  feature: Feature;
  categoryName: string;
}) {
  return (
    <div className="mx-auto max-w-[612px]">
      <div className="overflow-hidden rounded-xl border border-[var(--line)] bg-white shadow-sm">
        <div className="aspect-[612/792] overflow-y-auto p-8 text-[13px] leading-relaxed text-slate-800">
          <div className="text-[10px] font-medium tracking-[0.14em] text-blue-600">
            {categoryName.toUpperCase()}
          </div>
          <h1 className="mt-2 text-[22px] font-semibold leading-tight text-slate-900">
            {feature.name}
          </h1>

          <div className="mt-5">
            <div className="text-[10px] font-semibold uppercase tracking-wide text-slate-500">
              Description
            </div>
            <p className="mt-1 text-slate-700">
              {feature.description || "—"}
            </p>
          </div>

          <div className="mt-4">
            <div className="text-[10px] font-semibold uppercase tracking-wide text-slate-500">
              Business benefit
            </div>
            <p className="mt-1 text-slate-700">
              {feature.businessBenefit || "—"}
            </p>
          </div>

          <div className="mt-6 space-y-4">
            {feature.screenshots.length === 0 ? (
              <p className="text-slate-400">No screenshots attached.</p>
            ) : (
              feature.screenshots.slice(0, 2).map((shot) => (
                <AnnotatedImage key={shot.id} screenshot={shot} />
              ))
            )}
          </div>
        </div>
      </div>
      <p className="mt-3 text-center text-xs text-[var(--muted)]">
        Approximate PDF page preview (Letter size)
      </p>
    </div>
  );
}

function AnnotatedImage({ screenshot }: { screenshot: Screenshot }) {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const img = new Image();
    img.src = `/api/uploads/${screenshot.id}`;
    img.onload = () => {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const maxW = canvas.parentElement?.clientWidth || 500;
      const scale = Math.min(1, maxW / img.naturalWidth);
      const w = Math.round(img.naturalWidth * scale);
      const h = Math.round(img.naturalHeight * scale);
      const setup = setupHiDpiCanvas(canvas, w, h);
      if (!setup) return;
      const { ctx, width, height } = setup;
      ctx.drawImage(img, 0, 0, width, height);
      drawAnnotationsOnCanvas(ctx, screenshot.annotations, width, height);
    };
  }, [screenshot]);

  return (
    <canvas
      ref={canvasRef}
      className="block max-w-full rounded border border-slate-200"
    />
  );
}
