import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import {
  Card,
  CardHeader,
  CardContent,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  ListItemIcon,
  IconButton,
  Link,
  Tooltip
} from "@material-ui/core";
import style from "../styles";
import { LinkOutlined, FileCopyOutlined } from "@material-ui/icons";
import { useToast, useResourceSecurity } from "../../../../hooks";
import { useTranslation } from "react-i18next";

const useStyles = makeStyles(style);

const LinksComponent = ({ urls, secured }) => {
  const classes = useStyles();
  const { t } = useTranslation();
  const { info } = useToast();
  const { secureUrl } = useResourceSecurity();

  const handleToggle = (url) => () => {
    const urlMustBeSecured = secured || url.includes("id=");
    const link = urlMustBeSecured ? secureUrl(url) : url;
    navigator.clipboard.writeText(link);
    info(t("Resource.List.Actions.LinkCopiedToClipboard"));
  };
  const preventDefault = (event) => event.preventDefault();

  return (
    <Card className={classes.linksCard}>
      <CardHeader
        className={classes.linksHeader}
        title={t("Resource.Links.Title")}
        subheader={t("Resource.Links.SubTitle")}
      />
      <CardContent>
        <List>
          {urls.map((value, index) => {
            return (
              <ListItem
                key={`url-${index}`}
                dense
                button
                onClick={handleToggle(value)}
              >
                <ListItemIcon>
                  <LinkOutlined />
                </ListItemIcon>
                <ListItemText
                  primary={
                    <Link href={value} onClick={preventDefault}>
                      {value}
                    </Link>
                  }
                />
                <ListItemSecondaryAction>
                  <Tooltip title={"Copy"}>
                    <IconButton
                      edge="end"
                      aria-label="comments"
                      size="small"
                      onClick={handleToggle(value)}
                    >
                      <FileCopyOutlined />
                    </IconButton>
                  </Tooltip>
                </ListItemSecondaryAction>
              </ListItem>
            );
          })}
        </List>
      </CardContent>
    </Card>
  );
};

LinksComponent.propTypes = {
  urls: PropTypes.array.isRequired,
  secured: PropTypes.bool.isRequired
};

export default LinksComponent;
