import { useSelector } from "react-redux";
import styles from "./styles.module.scss";
import { selectors } from "@/store";
import { images } from "@/components/CompatibilityV2/data";
import { useEffect, useState } from "react";
import { copyToClipboard } from "@/services/data";
import Toast from "@/components/pages/ABDesign/v1/components/Toast";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

interface ICopyCodeProps {
    variant?: "default" | "black";
}

function CopyCode({
    variant = "default"
}: ICopyCodeProps) {
    const { translate } = useTranslations(ELocalesPlacement.CompatibilityV2);
    const code = useSelector(selectors.selectAuthCode);
    const [isCopied, setIsCopied] = useState(false);

    const handleCopy = async () => {
        const isCopied = await copyToClipboard(code);
        setIsCopied(isCopied);
    };

    useEffect(() => {
        if (!isCopied) return;

        const timeout = setTimeout(() => {
            setIsCopied(false);
        }, 4000);

        return () => clearTimeout(timeout);
    }, [isCopied]);

    return (
        <>
            <div
                className={`${styles.container} ${styles[variant]}`}
                onClick={handleCopy}
                title={translate("/try-app.copy-code-title")}
            >
                <span>{code}</span>
                {variant === "default" && <img className={styles.copyIcon} src={images("copy-icon.png")} alt="Copy code" />}
                {variant === "black" && <img className={styles.copyIcon} src={images("copy-icon-white.png")} alt="Copy code" />}
            </div>
            {isCopied && <Toast variant="success" classNameContainer={styles.toast}>
                {translate("/try-app.code-copied")}
            </Toast>}
        </>
    )
}

export default CopyCode;