import MuiDrawer from '@mui/material/Drawer';
import styles from "./styles.module.scss";
import { ReactComponent as ShareIcon } from '@assets/singlesvg/share.svg';
import icon_fb from "@assets/share/facebook.png";
import icon_ws from "@assets/share/WhatsApp.png";
import icon_tg from "@assets/share/telegram.png";
import icon_twitter from "@assets/share/Twitter.png";
import icon_email from "@assets/share/email.png";
import icon_svg_ws from "@assets/share/whatsappsvg.svg";
import icon_sms from "@assets/share/sms.png";
import { useSelector } from "react-redux";
import { getNumbers, getShareUrl, getTotalAmount, getTurnplate } from "@features/turnplateSlice";
import { formatCash, stringFormat } from "@utils/helpers";
import { CopyToClipboard } from "react-copy-to-clipboard/lib/Component";
import { toast } from "react-toastify";
import { useState } from "react";
import CountUp from "react-countup";
import popup from "@assets/wheel/popup2.png";

const i18n = global.i18n;
const WShare = ({ open, onClose }) => {
    const shareUrl = useSelector(getShareUrl);
    const amount = useSelector(getTotalAmount);
    const numbers = useSelector(getNumbers);
    const shareTitle = stringFormat(i18n.t("turnplate.share_box.share_title"), [global.DOLLAR, formatCash(amount, 0)]);
    const shareText = stringFormat(i18n.t("turnplate.share_box.share_text"), [global.DOLLAR, formatCash(amount, 0)]);

    const [waPhoneIndex, setWaPhoneIndex] = useState(-1);

    const turnplate = useSelector(getTurnplate);
    // console.error(turnplate);
    // const turnplate = {
    //     "times": 0,
    //     "countdown": 259200,
    //     "total_amount": 4000,
    //     "collect_amount": 3546
    // };


    const shareMore = () => {
        try {
            navigator.share ? navigator.share({
                title: shareTitle,
                url: shareUrl,
                text: shareText
            }) : shareFb();
        } catch (t) {
            shareFb();
        }
    };
    const shareFb = () => {
        if (global.isIOS) {
            let url = "fb://share/?link=" + shareUrl;
            window.open(url);
        }
        else {
            let url = "https://www.facebook.com/sharer/sharer.php?u=" + shareUrl + "&t=" + encodeURIComponent(shareText);
            window.open(url);
        }
    };
    const shareWa = () => {
        let url = "whatsapp://send?text=" + encodeURIComponent(shareText) + encodeURIComponent("\n\n" + shareUrl) + "&via=lopscoop";
        window.open(url);
    };
    const shareTG = () => {
        let url = "https://t.me/share/url?url=" + encodeURIComponent(shareUrl) + "&text=" + encodeURIComponent(shareText);
        window.open(url);
    };
    const shareTw = () => {
        let url = "https://twitter.com/intent/tweet?text" + encodeURIComponent(shareText) + "&url=" + encodeURIComponent(shareUrl);
        window.open(url);
    };
    const shareEmail = () => {
        let url = "mailto:?body=" + encodeURIComponent(shareText + " " + shareUrl);
        window.open(url);
    };
    const shareWaMore = () => {
        if (numbers.length > 0) {
            let windex = waPhoneIndex + 1;
            if (windex >= numbers.length) windex = 0;
            setWaPhoneIndex(windex);
            let phone = numbers[windex];
            let url = "whatsapp://send?phone=+" + phone + "&text=" + encodeURIComponent("Responda OK,".concat(shareText, ".")) + encodeURIComponent("\n\n" + shareUrl) + "&via=lopscoop";
            window.open(url);
        }
    };
    const shareSms = () => {
        let text = "";
        let smsCode = "";
        if (global.isIOS) {
            text = "&body=" + shareText + " " + shareUrl;
            smsCode = "/open?addresses=" + numbers.join(", ");
        }
        else {
            text = "?body=" + encodeURIComponent(shareText) + " " + encodeURIComponent(shareUrl);
            smsCode = numbers.join(", ") + ";";
        }
        let url = "sms:" + smsCode + text;
        window.open(url);
    };
    const renderIcons = () => {
        return (
            <>
                <div className={styles.iconBox}>
                    <div className={styles.iconTitle}>
                        Hey there! You've got to check out this amazing slot game I've been using. Sign up through my link and get a $10 bonus on top!
                    </div>
                    <div className={styles.share_icon_con}>
                        <button className={styles.icon_btn} onClick={shareWa}>
                            <div className={`${styles.icon}`}>
                                <img src={icon_ws} />
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_whatsapp")}</div>
                        </button>
                        <button className={styles.icon_btn} onClick={shareTG}>
                            <div className={`${styles.icon}`}>
                                <img src={icon_tg} />
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_telegram")}</div>
                        </button>
                        <button className={styles.icon_btn} onClick={shareFb}>
                            <div className={`${styles.icon}`}>
                                <img src={icon_fb} />
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_facebook")}</div>
                        </button>

                        {/* <button className={styles.icon_btn} onClick={shareTw}>
                            <div className={`${styles.icon}`}>
                                <img src={icon_twitter} />
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_twitter")}</div>
                        </button>
                        <button className={styles.icon_btn} onClick={shareEmail}>
                            <div className={`${styles.icon}`}>
                                <img src={icon_email} />
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_email")}</div>
                        </button>

                        <button className={styles.icon_btn} onClick={shareMore}>
                            <div className={`${styles.icon} ${styles.more}`}>
                                <ShareIcon className={styles.s_icon}></ShareIcon>
                            </div>
                            <div>{i18n.t("turnplate.share_box.btn_more")}</div>
                        </button> */}


                        <CopyToClipboard text={shareUrl} onCopy={() => {
                            toast.success(i18n.t("copy_success"),{toastId: "copy_success"});
                        }}>
                            <button className={styles.icon_btn} >
                                <div className={`${styles.icon} ${styles.more}`}>
                                    <ShareIcon className={styles.s_icon}></ShareIcon>
                                </div>
                                <div>{i18n.t("turnplate.share_box.btn_copy")}</div>
                            </button>
                        </CopyToClipboard>
                    </div>

                </div>
            </>
        );
    };
    const renderShareUrl = () => {
        return (
            <CopyToClipboard text={shareUrl} onCopy={() => {
                toast.success(i18n.t("copy_success"),{toastId: "copy_success"});
            }}>
                <button className={styles.share_url_con}>
                    <div className={styles.share_url}>
                        {shareUrl}
                    </div>
                    <div className={styles.copy}>{i18n.t("turnplate.share_box.btn_copy")}</div>
                </button>
            </CopyToClipboard>
        );
    };
    const renderRandomPlayers = () => {
        return (
            <div className={styles.share_random_con}>
                <div className={styles.content}>
                    {
                        numbers.map((item, index) => {
                            return (
                                <div key={index} className={`${styles.item} ${index <= waPhoneIndex ? styles.active : ''}`}>{item}</div>
                            );
                        })
                    }
                </div>
                <div className={styles.btn_con}>
                    <button className={styles.btn_send} onClick={shareWaMore}>
                        <div className={styles.text_con}>
                            <div>{i18n.t("turnplate.share_box.send_title")}</div>
                            <div className={styles.text_app}>
                                <div>{i18n.t("turnplate.share_box.send_on")}</div>
                                <div className={styles.name}>{i18n.t("turnplate.share_box.btn_whatsapp")}</div>
                            </div>
                        </div>
                        <img className={styles.icon} src={icon_svg_ws} />
                    </button>
                    <button className={styles.btn_send} onClick={shareSms}>
                        <img className={styles.icon} src={icon_sms} />
                        <div className={styles.text_con}>
                            <div>{i18n.t("turnplate.share_box.send_title")}</div>
                            <div className={styles.text_app}>
                                <div className={styles.name}>{i18n.t("turnplate.share_box.btn_sms")}</div>
                            </div>
                        </div>
                    </button>
                </div>
            </div>
        );
    };

    const renderProgress = () => {
        let collect = turnplate?.collect_amount;
        let total = turnplate?.total_amount;
        let left = total - collect;
        
        let isEnableCash = collect > 0;
        let progress = ((collect / total) * 100).toFixed(2);
        let canWithdraw = collect >= total;
        
        if (progress > 100) progress = 100;
        

        return (
            <div className={styles.cash_main_con}>
                <div className={styles.cash_main}>
                    {/* <div className={styles.have_cash}>
                        <CountUp
                            start={!open ? Number(formatCash(collect)) : 0}
                            end={Number(formatCash(collect))}
                            duration={1}
                            separator=" "
                            decimals={2}
                            prefix={global.DOLLAR + " "}
                            startOnMount

                        >
                            {({ countUpRef, start }) => {
                                return (
                                    <div ref={(ref) => {
                                        countUpRef.current = ref;
                                        if (open) {
                                            start();
                                        }
                                    }} className={styles.cash_text} />
                                );
                            }}
                        </CountUp>
                    </div> */}
                    <div className={styles.need_cash}>
                        {/* <div>{i18n.t("turnplate.need_tip")}</div>
                        <div className={styles.need_txt}>{formatCash(left)}</div>
                        <div>{i18n.t("turnplate.need_tip_1")}</div> */}
                        <img src={popup} alt="" />
                        {
                            canWithdraw ? (
                                // <>
                                //     Withdraw <div className={styles.need_txt}>${formatCash(collect)}</div> now.
                                // </>

                                <div className={styles.text}>Withdraw <span>${formatCash(collect)}</span> now.</div>
                            ) : (
                                <div className={styles.text}>I only need <span>${formatCash(left)}</span> to withdraw <span>${total / 100}</span></div>
                            )
                        }

                    </div>

                    <div className={styles.progress}>
                        <div className={styles.progressTip}>{progress + "%"}</div>
                        <div className={styles.bar}>
                            <span className={styles.dot} style={{ width: progress + "%" }}>
                                <div className={styles.custor}></div>
                            </span>
                        </div>
                    </div>

                </div>
            </div>
        );
    };
    const renderShare = () => {
        return (
            <div className={styles.container}>
                {/* <div className={styles.title}>{i18n.t("turnplate.share_box.title_1")}</div> */}
                <div className={styles.title}>SHARE WITH FRIENDS</div>
                {renderProgress()}
                {renderIcons()}
                {/* {renderShareUrl()} */}
                {/* <div className={styles.title}>{i18n.t("turnplate.share_box.title_2")}</div> */}
                {/* {renderRandomPlayers()} */}
            </div>
        );
    };
    return (
        <MuiDrawer open={open}
            anchor={"bottom"}
            sx={{
                zIndex: "1400",
                "& .MuiDrawer-paper": {
                    height: "auto",
                    boxSizing: "border-box",
                    overflow: 'visible !important',
                    backgroundColor: 'var(--standard);',
                    boxShadow: 'var(--widget-shadow);',
                    borderTopLeftRadius: '1rem',
                    borderTopRightRadius: '1rem'
                },
            }}
            variant="temporary"
            onClose={() => {
                if (onClose) onClose();
            }}>
            {renderShare()}
        </MuiDrawer>
    );
};
export default WShare;
