import {useSelector} from "react-redux";
import {getCurrPayOrder} from "@features/paySlice";
import React, {useEffect, useState} from "react";
import {useNavigate} from "react-router-dom";
import WOrderSuccess from "@widgets/WPaymentOrder/WOrderSuccess";
import styles from "./styles.module.scss";
import {formatDate, formatTime} from "@utils/helpers";
import Spring from "@components/Spring";
import {toast} from "react-toastify";
import SvgIcon from "@components/SvgIcon";
import {CopyToClipboard} from "react-copy-to-clipboard";
import {ROUTE_PATH} from "@constants/routes";
import {useThemeProvider} from "@contexts/themeContext";
import QRCode from "qrcode.react";
import c2bmembers from "@db/c2bmembers";
import {isIOS} from "@utils/helpers";
const i18n=global.i18n;
const RUPayOrder=({close})=>{
    const orderInfo=useSelector(getCurrPayOrder);
    const [leftTime,setLeftTime]=useState(0);
    const navigate=useNavigate();
    const {isMobile}=useThemeProvider();
    const [searchValue, setSearchValue] = useState("");
    const getLeftTime=()=>{
        if (orderInfo==null)return 0;
        let deadline=Number(orderInfo.deadline);
        let createAt=Number(orderInfo.createAt);
        let expireAt=createAt+deadline*1000;
        let now=Date.now();
        let left=expireAt-now;
        if (left<0)left=0;
        return left;
    }
    const updateLeftTime=(timer)=>{
        let left=getLeftTime();
        setLeftTime(left);
        if (left<=0){
            clearInterval(timer);
            timer=null;
            if (close)close();
        }
        return timer;
    }
    useEffect(()=>{
        let timer=null;
        if (orderInfo){
            setLeftTime(getLeftTime());
            timer=setInterval(()=>{
                timer=updateLeftTime(timer);
            },1000)
        }
        return () => {
            if (timer!=null){
                clearInterval(timer);
                timer=null;
            }
        };
    },[orderInfo])
    //p2p
    const onClickCustom=()=>{
        navigate(ROUTE_PATH.CUSTOMER);
    }
    const renderP2PCustomer=()=>{
        return (
            <button className={"button-green"} onClick={()=>{
                onClickCustom();
            }}>
                <SvgIcon className={styles.icon_chat} herf={"icon_Support"}></SvgIcon>
                {i18n.t("deposit.order_info_mx.btn_chat")}
            </button>
        )
    }
    const renderP2PTips=()=>{
        let arg=orderInfo.arg;
        let price=0;
        if (arg){
            price=arg.price;
        }
        return (
            <div className={styles.notice_con}>
                <div className={styles.notice_content}>
                    <span className={styles.n_title}>{i18n.t("deposit.order_info_ru.p2p.rule_title_1")}</span>
                    <span>{i18n.t("deposit.order_info_ru.p2p.content_1")}</span>
                    <span>{i18n.t("deposit.order_info_ru.p2p.content_2")}</span>
                    <span>{i18n.t("deposit.order_info_ru.p2p.content_3")}</span>
                    <span>
                    {i18n.t("deposit.order_info_ru.p2p.content_4")}
                        <span className={styles.n_title}>{orderInfo.credential}</span>
                </span>
                    <span>
                    {i18n.t("deposit.order_info_ru.p2p.content_5")}
                        <span className={styles.n_title}>{global.DOLLAR + price}</span>
                </span>
                    <span>{i18n.t("deposit.order_info_ru.p2p.content_6")}</span>
                </div>
            </div>
        )
    }
    const renderP2PBasic = () => {
        let createAt = Number(orderInfo.createAt);
        let arg = orderInfo.arg;
        let price = 0;
        if (arg) {
            price = arg.price;
        }
        return (
            <>
                <div className={styles.base_info}>
                    <div className={`${styles.info_row} ${styles.info_row_top} ${styles.info_row_light}`}>
                        <div className={styles.label}>
                            {i18n.t("deposit.order_info.create_date")}
                        </div>
                        {formatDate(createAt)}
                    </div>
                    <div className={styles.info_row}>
                        <div className={styles.label}>
                            {i18n.t("deposit.order_info.time")}
                        </div>
                        {formatTime(leftTime, true)}
                    </div>
                </div>
                <div className={styles.base_info}>
                    <CopyToClipboard text={orderInfo.bank_name} onCopy={() => {
                        toast.success(i18n.t("copy_success"),{toastId:"copy_success"});
                    }}>
                        <button className={`${styles.info_row} ${styles.info_row_top} ${styles.info_row_light}`}>
                            <div className={styles.label}>
                                {i18n.t("deposit.order_info_ru.p2p.title1")}
                            </div>
                            <div className={styles.order}>
                                {orderInfo.bank_name}
                                <SvgIcon className={styles.logo} herf={"icon_Copy"}/>
                            </div>
                        </button>
                    </CopyToClipboard>
                    <CopyToClipboard text={orderInfo.holderName} onCopy={() => {
                        toast.success(i18n.t("copy_success"),{toastId:"copy_success"});
                    }}>
                        <button className={styles.info_row}>
                            <div className={styles.label}>
                                {i18n.t("deposit.order_info_ru.p2p.title2")}
                            </div>
                            <div className={styles.order}>
                                {orderInfo.holderName}
                                <SvgIcon className={styles.logo} herf={"icon_Copy"}/>
                            </div>
                        </button>
                    </CopyToClipboard>
                    <CopyToClipboard text={price} onCopy={() => {
                        toast.success(i18n.t("copy_success"),{toastId:"copy_success"});
                    }}>
                        <button className={`${styles.info_row} ${styles.info_row_light}`}>
                            <div className={styles.label}>
                                {i18n.t("deposit.order_info_ru.p2p.title3")}
                            </div>
                            <div className={styles.order}>
                                <div className={styles.money}>
                                    {global.DOLLAR + price}
                                </div>
                                <SvgIcon className={styles.logo} herf={"icon_Copy"}/>
                            </div>
                        </button>
                    </CopyToClipboard>
                    <CopyToClipboard text={orderInfo.credential} onCopy={() => {
                        toast.success(i18n.t("copy_success"),{toastId:"copy_success"});
                    }}>
                        <button className={styles.info_row}>
                            <div className={styles.label}>
                                {i18n.t("deposit.order_info_ru.p2p.title4")}
                            </div>
                            <div className={styles.order}>
                                {orderInfo.credential}
                                <SvgIcon className={styles.logo} herf={"icon_Copy"}/>
                            </div>
                        </button>
                    </CopyToClipboard>
                </div>
            </>
        )
    }
    const renderOrderP2P = () => {
        return (
            <div className={styles.order_info}>
                {renderP2PBasic()}
                {renderP2PTips()}
                {renderP2PCustomer()}
            </div>
        )
    }
    //p2p
    //sbp
    const getLinkToPay=(paymentURL, ios, schema, pkg)=>{
        if (ios)return `${paymentURL.replace("https:", schema + ":")}`;
        else return `${paymentURL.replace(
            "https:",
            "intent:"
        )}#Intent;scheme=${schema};package=${pkg};end`
    }
    const getBankList=()=>{
        let list=[];
        if (searchValue!==""){
            let temp=searchValue.toUpperCase();
            for (let i = 0; i < c2bmembers.length; i++) {
                let item=c2bmembers[i];
                let tempName=item.bankName;
                tempName=tempName.toUpperCase();
                tempName=tempName.replaceAll(" ","");
                if (tempName.indexOf(temp)!==-1)list.push(item);
            }
        }else list=c2bmembers.slice(0);
        return list;
    }
    const onBankPay=(item)=>{
        let paymentURL=orderInfo.qr_link;
        let ios=isIOS();
        let url=getLinkToPay(paymentURL,ios,item.schema,item.package_name);
        window.open(url,"_self");
    }
    const renderBankList=()=>{
        let list=getBankList();
        return (
            <div className={styles.bank_list_con}>
                {
                    list.map((item,index)=>{
                        return (
                            <button key={index} className={styles.item_con} onClick={()=>{
                                onBankPay(item);
                            }}>
                                <div className={styles.item}>
                                    <img className={styles.icon} src={item.logoURL}/>
                                    {item.bankName}
                                </div>
                                <SvgIcon className={styles.arrow} herf={"icon_Arrow"}/>
                            </button>
                        )
                    })
                }
            </div>
        )
    }
    const renderMobileSBP=()=>{
        let arg=orderInfo.arg;
        let price=0;
        if (arg){
            price=arg.price;
        }
        return (
            <div className={styles.order_info_sbp}>
                <div className={styles.base_info}>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info_ru.p2p.title3")}</span>
                        <span className={styles.money}>{price + " " + global.DOLLAR}</span>
                    </div>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info.time")}</span>
                        <span className={styles.label}>{formatTime(leftTime, true)}</span>
                    </div>
                </div>
                <div className={styles.base_info}>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info_ru.sbp.search")}</span>
                    </div>
                    <div className={`input-control ${styles.select_search}`}>
                        <SvgIcon className={styles.icon} herf={"icon_Search"}></SvgIcon>
                        <input placeholder={i18n.t("deposit.order_info_ru.sbp.bank_name_ph")} onChange={e => setSearchValue(e.target.value)}/>
                    </div>
                    {renderBankList()}
                </div>
                <div className={styles.base_info}>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info_ru.sbp.use_qr")}</span>
                    </div>
                    <div className={styles.pay_qr_con}>
                        <QRCode className={styles.pay_qr} value={orderInfo.qr_link}/>
                    </div>
                    <div className={styles.y_tips}>
                        {i18n.t("deposit.order_info_ru.sbp.qr_tips")}
                    </div>
                </div>
            </div>
        )
    }
    const renderDeskSBP = () => {
        let arg = orderInfo.arg;
        let price = 0;
        if (arg) {
            price = arg.price;
        }
        return (
            <div className={styles.order_info_qr}>
                <div className={styles.pay_qr_con}>
                    <QRCode className={styles.pay_qr} value={orderInfo.qr_link} />
                </div>
                <div className={styles.base_info}>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info_ru.p2p.title3")}</span>
                        <span className={styles.money}>{price + " " + global.DOLLAR}</span>
                    </div>
                    <div className={styles.info_row}>
                        <span className={styles.label}>{i18n.t("deposit.order_info.time")}</span>
                        <span className={styles.label}>{formatTime(leftTime, true)}</span>
                    </div>
                </div>
                <div className={styles.y_tips}>
                    {i18n.t("deposit.order_info_ru.sbp.qr_tips")}
                </div>
            </div>
        )
    }
    const renderOrderSBP = () => {
        if (isMobile()) return renderMobileSBP();
        else return renderDeskSBP();
    }
    //sbp
    const renderOrderInfo = () => {
        let arg = orderInfo.arg;
        if (arg != null) {
            if (arg.eventType === "p2p") {
                return renderOrderP2P();
            } else if (arg.eventType === "sbp") {
                return renderOrderSBP();
            }
        }
        return (<></>);
    }
    const renderOrder=()=>{
        return (
            <Spring type="slideUp" className={styles.container}>
                {renderOrderInfo()}
            </Spring>
        )
    }
    const renderOrderRedirect=()=>{
        return (
            <iframe
                id={"order"}
                title={"order"}
                src={orderInfo.redirectURL}
                className={styles.order_frame}
                allow="fullscreen"
                sandbox='allow-scripts allow-same-origin allow-popups allow-top-navigation allow-top-navigation-by-user-activation'
            >
            </iframe>
        )
    }
    const renderView = () => {
        if (orderInfo != null) {
            if (orderInfo.status === "success") {
                return (
                    <WOrderSuccess close={close}/>
                )
            } else {
                if (orderInfo.redirectURL != null && orderInfo.redirectURL!==""){
                    return renderOrderRedirect();
                }
                else
                {
                    return renderOrder()
                }
            }
        }
        return (<></>);
    }
    return (
        <>
            {renderView()}
        </>
    )
}
export default RUPayOrder;