import { sanitizeExternalUrl } from "@allurereport/core-api";
import { SvgIcon, Text, allureIcons } from "@allurereport/web-components";
import type { FunctionalComponent } from "preact";
import { useState } from "preact/hooks";
import type { ClassicTestResult } from "types";

import { MetadataButton } from "@/components/MetadataButton";
import { useI18n } from "@/stores/locale";

import * as styles from "./styles.scss";

interface TestResultLinkProps {
  name: string;
  url: string;
  type: string;
}

const linksIconMap: Record<string, string> = {
  issue: allureIcons.lineDevBug2,
  link: allureIcons.lineGeneralLink1,
  tms: allureIcons.lineGeneralChecklist3,
  github: allureIcons.github,
};

const TestResultLink: FunctionalComponent<{
  link: TestResultLinkProps;
}> = ({ link }) => {
  const { url, type } = link;
  const safeUrl = sanitizeExternalUrl(url);

  return (
    <div className={styles["test-result-link"]}>
      <SvgIcon id={linksIconMap[type] ?? allureIcons.lineGeneralLink1} />
      {safeUrl ? (
        <Text
          tag={"a"}
          href={safeUrl}
          target={"_blank"}
          rel={"noopener noreferrer"}
          size={"m"}
          className={styles["test-result-link-text"]}
        >
          {url}
        </Text>
      ) : (
        <Text size={"m"} className={styles["test-result-link-text"]}>
          {url}
        </Text>
      )}
    </div>
  );
};

export type TestResultLinksProps = {
  links: ClassicTestResult["links"];
};

export const TestResultLinks: FunctionalComponent<TestResultLinksProps> = ({ links }) => {
  const [isOpened, setIsOpen] = useState(true);
  const { t } = useI18n("ui");
  const linkMap = links.map((link, index) => {
    return <TestResultLink link={link as TestResultLinkProps} key={index} />;
  });

  return (
    <div className={styles["test-result-links"]}>
      <div className={styles["test-result-links-wrapper"]}>
        <MetadataButton isOpened={isOpened} setIsOpen={setIsOpen} counter={links.length} title={t("links")} />
        {isOpened && <div className={styles["test-result-links-list"]}>{linkMap}</div>}
      </div>
    </div>
  );
};
