import React, { useEffect, useState } from "react"

import { A_ELEMENT_TAG_REST_ATTRS } from "@/constants/common"
import { isLeaveSite } from "@/utils/site"
import { Link } from "gatsby"

interface IProps {
  children: React.ReactNode | React.ReactNode[]
  linkTo: string
  className?: string
  attrs?: { [key: string]: string | boolean | { [key: string]: string } }
}

type State = typeof A_ELEMENT_TAG_REST_ATTRS | null
const getAttrs = (url: string, attrs?: { [key: string]: string }) => {
  return isLeaveSite(url) ? { ...A_ELEMENT_TAG_REST_ATTRS, ...attrs } : null
}
export default function CustomLink(props: IProps) {
  const { children, linkTo, className, attrs } = props
  const [aRestAttrs, setARestAttrs] = useState<State>(A_ELEMENT_TAG_REST_ATTRS)
  useEffect(() => {
    const newValue = getAttrs(linkTo)
    setARestAttrs(newValue)
  }, [linkTo])
  return (
    <a
      {...aRestAttrs}
      href={linkTo.includes("/case?") ? `${linkTo}#case` : linkTo}
      className={className ?? ""}
      {...attrs}
    >
      {children}
    </a>
  )
}
