import { useTranslations } from "@/hooks/translations";
import styles from "./styles.module.scss";
import { ELocalesPlacement } from "@/locales";
import { useSelector } from "react-redux";
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";

function YourAccessCode(): JSX.Element {
    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}>
            <div className={styles.header}>
                <span>{translate("/try-app.your_access_code")}</span>
            </div>
            <div className={styles.body} onClick={handleCopy} title={translate("/try-app.copy-code-title")}>
                <div className={styles.codeContainer}>
                    <div className={styles.code}>
                        <span>{code}</span>
                    </div>
                    <div className={styles.copy}>
                        <img src={images("copy-icon.png")} alt="Copy code" />
                        <span>{translate("/try-app.copy")}</span>
                    </div>
                </div>
            </div>
            {isCopied && <Toast variant="success" classNameContainer={styles.toast}>
                {translate("/try-app.code-copied")}
            </Toast>}
        </div>
    );
}

export default YourAccessCode;
