import { useEffect, useState } from "react";
import { X } from "lucide-react";

import ModalPortal from "../../components/ui/ModalPortal";

export default function DocumentViewerDialog({ doc, onClose }) {
  const [objectUrl, setObjectUrl] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    let url = null;
    let cancelled = false;

    async function load() {
      try {
        const result = await window.omsorg.documents.view(doc.id);

        if (cancelled) return;

        if (!result.ok) {
          setError("Dokument konnte nicht geladen werden.");
          return;
        }

        url = URL.createObjectURL(result.data.blob);
        setObjectUrl(url);
      } catch (err) {
        if (!cancelled) {
          setError(`Dokument konnte nicht geladen werden: ${err.message}`);
        }
      }
    }

    load();

    return () => {
      cancelled = true;
      if (url) {
        URL.revokeObjectURL(url);
      }
    };
  }, [doc.id, doc.contentType]);

  function renderContent() {
    if (error) {
      return <p className="login-error">{error}</p>;
    }

    if (!objectUrl) {
      return <p>Lädt...</p>;
    }

    if (doc.contentType === "application/pdf") {
      return <iframe src={objectUrl} title={doc.fileName} className="document-viewer-content" />;
    }

    if (doc.contentType?.startsWith("image/")) {
      return <img src={objectUrl} alt={doc.fileName} className="document-viewer-content document-viewer-content--image" />;
    }

    return <p>Keine Vorschau verfügbar, bitte herunterladen.</p>;
  }

  return (
    <ModalPortal>
      <div className="modal-overlay" role="dialog" aria-modal="true" aria-label={`Vorschau: ${doc.fileName}`}>
        <div className="modal-panel modal-panel--viewer">
          <button type="button" className="modal-close-button" onClick={onClose} aria-label="Schließen">
            <X size={20} />
          </button>

          <h2>{doc.fileName}</h2>

          <div className="document-viewer-body">{renderContent()}</div>
        </div>
      </div>
    </ModalPortal>
  );
}
