"use client";

import { useState } from "react";
import { AlertCircle, Download, ExternalLink, FileText, X } from "lucide-react";
import { documentKind } from "@/lib/documents";

type DocumentViewerProps = {
  url?: string | null;
  fileName?: string | null;
  mimeType?: string | null;
  buttonLabel?: string;
  emptyLabel?: string;
  compact?: boolean;
  checkBeforeOpen?: boolean;
};

const notFoundMessage = "Document file not found. Please upload again.";

export function DocumentViewer({
  url,
  fileName,
  mimeType,
  buttonLabel = "View",
  emptyLabel = "No file",
  compact = false,
  checkBeforeOpen = true
}: DocumentViewerProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);

  if (!url) return <span className="text-sm text-slate-500">{emptyLabel}</span>;

  const kind = documentKind(fileName ?? url, mimeType);
  const sizeClass = compact ? "px-2 py-1 text-xs" : "";

  const openPreview = async () => {
    setError(null);
    if (checkBeforeOpen && url.startsWith("/")) {
      try {
        const response = await fetch(url, { method: "HEAD", cache: "no-store" });
        if (!response.ok) {
          setError(notFoundMessage);
          return;
        }
      } catch {
        setError(notFoundMessage);
        return;
      }
    }
    if (kind === "office" || kind === "file") {
      window.open(url, "_blank", "noopener,noreferrer");
      return;
    }
    setIsOpen(true);
  };

  return (
    <>
      <div className="grid gap-1">
        <button className={`btn-secondary ${sizeClass}`} type="button" onClick={openPreview}>
          <FileText className="h-4 w-4" aria-hidden="true" />
          {kind === "office" || kind === "file" ? "Download" : buttonLabel}
        </button>
        {error ? (
          <p className="flex items-center gap-1 text-xs font-medium text-red-600">
            <AlertCircle className="h-3.5 w-3.5" aria-hidden="true" />
            {error}
          </p>
        ) : null}
      </div>

      {isOpen ? (
        <div className="fixed inset-0 z-50 grid place-items-center bg-slate-950/70 p-4" role="dialog" aria-modal="true" onClick={(event) => event.stopPropagation()}>
          <div className="grid max-h-[92vh] w-full max-w-5xl gap-3 rounded-md bg-white p-4 shadow-2xl">
            <div className="flex items-center justify-between gap-3">
              <div>
                <p className="text-sm font-semibold text-ink">{fileName ?? "Document"}</p>
                <p className="text-xs text-slate-500">{kind === "pdf" ? "PDF document" : "Image document"}</p>
              </div>
              <div className="flex items-center gap-2">
                <a className="btn-secondary px-2 py-1 text-xs" href={url} target="_blank" rel="noreferrer">
                  <ExternalLink className="h-4 w-4" aria-hidden="true" />
                  New tab
                </a>
                <a className="btn-secondary px-2 py-1 text-xs" href={url} download>
                  <Download className="h-4 w-4" aria-hidden="true" />
                  Download
                </a>
                <button className="btn-secondary px-2 py-1 text-xs" type="button" onClick={() => setIsOpen(false)} aria-label="Close document preview">
                  <X className="h-4 w-4" aria-hidden="true" />
                </button>
              </div>
            </div>

            {error ? (
              <p className="flex items-center gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm font-medium text-red-700">
                <AlertCircle className="h-4 w-4" aria-hidden="true" />
                {error}
              </p>
            ) : null}

            {kind === "pdf" ? (
              <iframe className="h-[76vh] w-full rounded-md border border-line bg-slate-50" src={url} title="Document PDF preview" />
            ) : (
              <div className="grid max-h-[76vh] place-items-center overflow-auto rounded-md border border-line bg-slate-50 p-3">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  className="max-h-[72vh] max-w-full rounded-md object-contain"
                  src={url}
                  alt="Document preview"
                  onError={() => setError(notFoundMessage)}
                />
              </div>
            )}
          </div>
        </div>
      ) : null}
    </>
  );
}
