import Link from "next/link";

export function validURL(str) {
  var pattern = new RegExp(
    "^(https?:\\/\\/)?" + // protocol
      "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
      "((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
      "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
      "(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
      "(\\#[-a-z\\d_]*)?$",
    "i"
  ); // fragment locator
  return !!pattern.test(str);
}

export function renderPossibleURLField(field) {
  if (validURL(field)) {
    return (
      <Link href={field}>
        <a className="p-2 text-center overflow-clip overflow-auto ring-2 ring-werefox-grey-light dark:ring-werefox-grey-darker rounded-lg bg-werefox-grey-lighter dark:bg-werefox-grey-dark hover:text-werefox-blue-dark dark:hover:text-werefox-blue">
          {field}
        </a>
      </Link>
    );
  } else {
    return (
      <p className="p-2 text-center overflow-clip overflow-auto ring-2 ring-werefox-grey-light dark:ring-werefox-grey-darker rounded-lg bg-werefox-grey-lighter dark:bg-werefox-grey-dark">
        {field}
      </p>
    );
  }
}

export default function LoveCard({ src, alt, url, fields, bio, user }) {
  const finalsrc = Boolean(src) ? src : "/images/logo.png";
  const isMe =
    user == "Shadow8t4"
      ? "text-werefox-blue-dark dark:text-werefox-blue"
      : "text-werefox-pink-dark dark:text-werefox-pink";

  return (
    <div className="rounded-lg min-w-full flex ring-2 ring-werefox-grey-lightest dark:ring-werefox-grey-darker bg-werefox-grey-lighter dark:bg-werefox-grey-dark">
      <Link href={url}>
        <a>
          <div className="flex-1 pt-4 pb-4 pl-4">
            {" "}
            <img
              className="rounded-lg sm:w-32 w-16"
              src={finalsrc}
              alt={alt}
            />{" "}
          </div>
        </a>
      </Link>{" "}
      <div className={`flex-5 p-4 sm:text-sm text-xs text-center ${isMe}`}>
        <div className="grid grid-cols-1 gap-2">
          <div className="ring-2 ring-werefox-grey-lightest dark:ring-werefox-grey-darker rounded-lg p-2 grid grid-cols-2 grid-rows-1 gap-2 bg-werefox-grey-light dark:bg-werefox-grey">
            {Object.keys(fields).map((field) => (
              <>
                {renderPossibleURLField(field)}
                {renderPossibleURLField(fields[field])}
              </>
            ))}
          </div>
          <div className="ring-2 ring-werefox-grey-lightest dark:ring-werefox-grey-darker rounded-lg p-2 bg-werefox-grey-light dark:bg-werefox-grey">
            <p className="overflow-auto">
              {bio}
              <br />
              {"- "}
              <Link href={url}>
                <a className="hover:text-werefox-blue-dark dark:hover:text-werefox-blue" target="_blank">{`@${user}`}</a>
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
