import { useRouter } from "next/router";
import { FC, useEffect, useState } from "react";

type ShareButtonProps = { btnSize?: string };

const ShareButton: FC<ShareButtonProps> = ({ btnSize = "" }) => {
  const { locale, asPath } = useRouter();
  const [currentUrl, setCurrentUrl] = useState("");

  useEffect(() => {
    if (typeof window !== "undefined") {
      setCurrentUrl(`${window.location.origin}${asPath}`);
    }
  }, [asPath]);

  const socialLinks = [
    {
      id: 1,
      title: "Twitter",
      url: `https://twitter.com/intent/tweet?url=${encodeURIComponent(
        currentUrl
      )}`,
      icon: "uil-twitter",
    },
    {
      id: 2,
      title: "Facebook",
      url: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(
        currentUrl
      )}`,
      icon: "uil-facebook-f",
    },
    {
      id: 3,
      title: "Messenger",
      url: `fb-messenger://share?link=${encodeURIComponent(currentUrl)}`,
      icon: "uil-facebook-messenger",
    },
    {
      id: 4,
      title: "WhatsApp",
      url: `https://api.whatsapp.com/send?text=${encodeURIComponent(
        currentUrl
      )}`,
      icon: "uil-whatsapp",
    },
  ];

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(currentUrl);
      alert("¡Enlace copiado!");
    } catch (err) {
      console.error("Error al copiar", err);
    }
  };

  return (
    <div className="dropdown share-dropdown btn-group">
      <button
        aria-haspopup="true"
        aria-expanded="false"
        data-bs-toggle="dropdown"
        className={` tw-border-2 w-9 h-9 tw-text-2xl hover:tw-opacity-50 tw-font-normal tw-border-main-color tw-rounded-full tw-flex tw-items-center tw-justify-center tw-text-main-color`}
      >
        <i className="uil uil-share-alt" />
      </button>

      <div className="dropdown-menu">
        {socialLinks.map(({ id, title, icon, url }) => (
          <a
            key={id}
            className="dropdown-item flex gap-2 items-center"
            href={url}
            target="_blank"
            rel="noopener noreferrer"
          >
            <i className={`uil ${icon}`} />
            {title}
          </a>
        ))}
        <button
          onClick={handleCopy}
          className="dropdown-item flex gap-2 items-center"
        >
          <i className="uil uil-copy" />
          {locale === "es" ? "Copiar enlace" : "Copy link"}
        </button>
      </div>
    </div>
  );
};

export default ShareButton;
