import React from "react";
import ReactMarkdown from "react-markdown";
import { Popup, Button, Icon } from "semantic-ui-react";

const bareUrlPattern = /https?:\/\/[^\s<>()]+[^\s<>().,!?;:]/g;

function LinkMenu({ href, children, txt, darkMode }) {
  const [open, setOpen] = React.useState(false);
  const [copied, setCopied] = React.useState(false);

  const label = (text) => (typeof txt === "function" ? txt(text) : text);

  const openTab = () => {
    if (href) window.open(href, "_blank", "noopener,noreferrer");
    setOpen(false);
  };

  const copyUrl = (e) => {
    e.stopPropagation();
    if (href && navigator.clipboard) {
      navigator.clipboard.writeText(href).then(
        () => {
          setCopied(true);
          setTimeout(() => setCopied(false), 1500);
        },
        () => {}
      );
    }
  };

  return (
    <Popup
      on="click"
      open={open}
      onOpen={() => setOpen(true)}
      onClose={() => {
        setOpen(false);
        setCopied(false);
      }}
      position="top center"
      inverted={!!darkMode}
      className="chatLinkMenu"
      trigger={
        <a
          href={href}
          className="chatLink"
          onClick={(e) => {
            e.preventDefault();
          }}>
          {children}
        </a>
      }>
      <div className="chatLinkMenuContent">
        <div className="chatLinkUrl" title={href}>
          {href}
        </div>
        <Button.Group size="tiny" fluid className={darkMode ? "inverted" : ""}>
          <Button compact basic onClick={openTab} className={darkMode ? "inverted" : ""}>
            <Icon name="external alternate" />
            {label("Open in New Tab")}
          </Button>
          <Button compact basic onClick={copyUrl} className={darkMode ? "inverted" : ""}>
            <Icon name={copied ? "check" : "copy"} />
            {copied ? label("Copied") : label("Copy URL")}
          </Button>
        </Button.Group>
      </div>
    </Popup>
  );
}

function linkifyPlainUrls(markdown) {
  const source = String(markdown || "");
  let inFence = false;

  return source
    .split("\n")
    .map((line) => {
      if (/^\s*```/.test(line)) {
        inFence = !inFence;
        return line;
      }

      if (inFence) return line;

      return line
        .split(/(`[^`]*`)/g)
        .map((part) => {
          if (part.startsWith("`") && part.endsWith("`")) return part;

          return part.replace(bareUrlPattern, (url, offset, text) => {
            const before = text.slice(0, offset);
            const after = text.slice(offset + url.length);

            if (before.endsWith("](") || before.endsWith("<") || after.startsWith(">")) {
              return url;
            }

            return `[${url}](${url})`;
          });
        })
        .join("");
    })
    .join("\n");
}

function preserveSoftLineBreaks(markdown) {
  const source = String(markdown || "");
  const lines = source.split("\n");
  let inFence = false;

  return lines
    .map((line, index) => {
      if (/^\s*```/.test(line)) {
        inFence = !inFence;
        return line;
      }

      if (inFence || index === lines.length - 1) {
        return line;
      }

      if (!line.trim()) {
        return "&nbsp;  ";
      }

      if (line.endsWith("  ") || line.endsWith("\\")) {
        return line;
      }

      return `${line}  `;
    })
    .join("\n");
}

export default function MarkdownText({ text = "", txt, darkMode }) {
  const markdown = preserveSoftLineBreaks(linkifyPlainUrls(text));

  return (
    <ReactMarkdown
      components={{
        a: ({ children, href }) => (
          <LinkMenu href={href} txt={txt} darkMode={darkMode}>
            {children}
          </LinkMenu>
        ),
      }}>
      {markdown}
    </ReactMarkdown>
  );
}
