import { useEffect } from "react";
import { MarkdownView } from "./code-block";

export type KnowledgeDoc = {
  id: string;
  title: string;
  source: string;
  tags: string[];
  owner?: string;
  updated?: string;
  headings: string[];
  content: string;
};

type DocModalProps = {
  doc: KnowledgeDoc;
  onClose: () => void;
  labels: {
    close: string;
    tags: string;
    owner: string;
    updated: string;
  };
};

const DocModal = ({ doc, onClose, labels }: DocModalProps) => {
  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div
      aria-label={doc.title}
      className="docModalBackdrop"
      onClick={onClose}
      role="dialog"
    >
      <article className="docModal" onClick={(event) => event.stopPropagation()}>
        <header className="docModalHeader">
          <div>
            <h2>{doc.title}</h2>
            <small>{doc.source}</small>
          </div>
          <button
            aria-label={labels.close}
            className="iconToggle"
            onClick={onClose}
            type="button"
          >
            ✕
          </button>
        </header>
        <dl className="docMeta">
          {doc.tags.length > 0 ? (
            <div>
              <dt>{labels.tags}</dt>
              <dd>{doc.tags.join(", ")}</dd>
            </div>
          ) : null}
          {doc.owner ? (
            <div>
              <dt>{labels.owner}</dt>
              <dd>{doc.owner}</dd>
            </div>
          ) : null}
          {doc.updated ? (
            <div>
              <dt>{labels.updated}</dt>
              <dd>{doc.updated}</dd>
            </div>
          ) : null}
        </dl>
        <div className="docModalBody">
          <MarkdownView source={doc.content} />
        </div>
      </article>
    </div>
  );
};

export default DocModal;
