"use client";

import { useEffect, useState } from "react";
import { ExternalLink, FileText, Loader2, Minus, Plus, X } from "lucide-react";
import { cn } from "@/lib/utils";

export function SecureImageViewer({
  src,
  alt,
  mimeType = "image/jpeg",
  className,
  imageClassName = "h-full w-full object-cover"
}: {
  src: string;
  alt: string;
  mimeType?: string | null;
  className?: string;
  imageClassName?: string;
}) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [zoom, setZoom] = useState(1);
  const isImage = (mimeType ?? "").startsWith("image/");

  useEffect(() => {
    if (!open) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", onKeyDown);
    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  if (!isImage) {
    return (
      <a
        href={src}
        target="_blank"
        rel="noreferrer"
        className={cn("grid place-items-center bg-[var(--surface-muted)] text-[var(--primary)]", className)}
        title="فتح الملف"
      >
        <FileText size={30} aria-hidden />
      </a>
    );
  }

  return (
    <>
      <button
        type="button"
        onClick={() => {
          setOpen(true);
          setLoading(true);
          setError(false);
          setZoom(1);
        }}
        className={cn("relative block overflow-hidden bg-[var(--surface-muted)]", className)}
        aria-label={`عرض ${alt} بحجم كبير`}
      >
        {/* The protected route checks authorization on every request. */}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={src} alt={alt} className={imageClassName} />
        <span className="absolute inset-x-0 bottom-0 bg-black/65 px-3 py-2 text-xs font-bold text-white">
          عرض الصورة
        </span>
      </button>

      {open ? (
        <div
          className="fixed inset-0 z-50 grid overflow-y-auto bg-black/80 p-3 sm:p-6"
          role="dialog"
          aria-modal="true"
          aria-label={alt}
          onMouseDown={(event) => {
            if (event.target === event.currentTarget) setOpen(false);
          }}
        >
          <div className="mx-auto flex h-full max-h-[calc(100dvh-1.5rem)] w-full min-w-0 max-w-6xl flex-col overflow-hidden rounded-md bg-white sm:max-h-[calc(100dvh-3rem)]">
            <div className="flex min-h-14 min-w-0 items-center justify-between gap-2 border-b px-2 sm:gap-3 sm:px-4">
              <p className="min-w-0 truncate text-sm font-black">{alt}</p>
              <div className="flex shrink-0 items-center gap-1">
                <button type="button" onClick={() => setZoom((value) => Math.max(1, value - 0.25))} className="grid size-10 shrink-0 place-items-center rounded-md hover:bg-[var(--surface-muted)]" title="تصغير" aria-label="تصغير الصورة">
                  <Minus size={18} aria-hidden />
                </button>
                <button type="button" onClick={() => setZoom((value) => Math.min(4, value + 0.25))} className="grid size-10 shrink-0 place-items-center rounded-md hover:bg-[var(--surface-muted)]" title="تكبير" aria-label="تكبير الصورة">
                  <Plus size={18} aria-hidden />
                </button>
                <a href={src} target="_blank" rel="noreferrer" className="grid size-10 shrink-0 place-items-center rounded-md hover:bg-[var(--surface-muted)]" title="فتح بالحجم الأصلي" aria-label="فتح الصورة بالحجم الأصلي">
                  <ExternalLink size={18} aria-hidden />
                </a>
                <button type="button" onClick={() => setOpen(false)} className="grid size-10 shrink-0 place-items-center rounded-md hover:bg-[var(--surface-muted)]" title="إغلاق" aria-label="إغلاق عارض الصورة">
                  <X size={20} aria-hidden />
                </button>
              </div>
            </div>
            <div className="relative min-h-0 flex-1 overflow-auto bg-[#111815] touch-pan-x touch-pan-y">
              {loading ? (
                <div className="absolute inset-0 z-10 grid place-items-center text-white">
                  <div className="grid justify-items-center gap-3 text-sm font-bold">
                    <Loader2 size={28} className="animate-spin" aria-hidden />
                    جارٍ تحميل الصورة...
                  </div>
                </div>
              ) : null}
              {error ? (
                <div className="absolute inset-0 z-10 grid place-items-center p-5 text-center text-sm font-bold text-white">
                  تعذر تحميل الصورة. تحقق من الاتصال والصلاحيات ثم أعد المحاولة.
                </div>
              ) : null}
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={src}
                alt={alt}
                onLoad={() => setLoading(false)}
                onError={() => {
                  setLoading(false);
                  setError(true);
                }}
                className="mx-auto block max-w-none origin-top object-contain transition-transform"
                style={{ transform: `scale(${zoom})`, width: zoom === 1 ? "100%" : "auto", minHeight: "100%" }}
              />
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
