import { useState } from "react";
import Button from "./Button";
import CheckIcon from "../icons/CheckIcon";
import LoaderIcon from "../icons/LoaderIcon";

export default function LinkShare({ link }: { link: string }) {
  const [shareState, setShareState] = useState<"default" | "loading" | "done">(
    "default"
  );

  function handleCopy() {
    setShareState("loading");
    navigator.clipboard.writeText(link);

    setTimeout(() => {
      setShareState("done");
    }, 500);
  }

  return (
    <div className="flex flex-col 2xl:gap-[0.556vw] gap-2">
      <div className="w-full 2xl:h-[3.75vw] h-[54px] bg-[#F3F3F3] flex items-center justify-between 2xl:gap-[0.833vw] gap-3 2xl:px-[1.111vw] px-4 2xl:rounded-[1.111vw] rounded-2xl relative">
        <span
          className="text-ellipsis text-s hover:cursor-pointer overflow-hidden text-nowrap"
          onClick={handleCopy}
        >
          {link}
        </span>

        {shareState === "default" && (
          <Button
            variant="cta"
            size="medium"
            className="2xl:translate-x-[0.556vw] translate-x-2 shrink-0"
            onClick={handleCopy}
          >
            Копировать
          </Button>
        )}

        {shareState === "loading" && (
          <div className="2xl:size-[1.389vw] size-5 text-[#7B60F3] animate-spin shrink-0">
            <LoaderIcon />
          </div>
        )}

        {shareState === "done" && (
          <div className="2xl:size-[1.389vw] size-5 text-[#7B60F3] shrink-0">
            <CheckIcon />
          </div>
        )}
      </div>
      {shareState === "done" && (
        <div className="caption-s absolutea 2xl:bottom-[-1.25vw] bottom-[-18px] text-[#29AF61] left-0">
          Ссылка скопирована
        </div>
      )}
    </div>
  );
}
