import { View, Text } from "@tarojs/components";
import Buttons from '@/components/basic/Buttons'
import Texts from '@/components/basic/Texts'
import './ChooseAuth.scss'
import { ButtonType, ComponentStatus, TextType } from "../../utils/types";
import Taro, { useReady } from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import { wxLogin } from "@/services/user";
import { ColorType } from "@/context/themes/color";
import { ChooseScenarioBtn } from "@/features/common/SpecBtns";
import { useTranslation } from "react-i18next";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { loginSuccess } from "@/store/user";
import RequestType, { thirdPartRequest } from "@/services/thirdPartRequest";

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}


export default function Page() {
    const [btnDisable, setBtnDisable] = useState(false)
    const [code, setCode] = useState('')
    const dispatch = useDispatch();
    const { t } = useTranslation()

    const user = useSelector((state: any) => state.user);
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        if (navigation) {
            navigation.setOptions({
                headerTitle: '',
            });
        }
        if (user.isLogin) {
            if (user.is_new_user) {
                console.log('new user')
                if (user.scenario_select_count == 0) {
                    console.log('new')
                    Taro.redirectTo({
                        url: '/pages/clock/ChooseScenario?trigger_event=SETUP_UPON_ACCOUNT_CREATION'
                    })
                    setTimeout(() => {
                        Taro.navigateTo({
                            url: '/pages/account/ProfileSetting?newuser=1'
                        })
                    }, 100)
                }
                else {
                    console.log('replace')
                    Taro.redirectTo({
                        url: '/pages/account/ProfileSetting?newuser=1'
                    })
                }


            }
            else {
                console.log('old user')
                // if (user.scenario_select_count > 0) {
                //     Taro.navigateBack({
                //         delta: 1
                //     })
                // }
                // else {
                //     Taro.redirectTo({
                //         url: '/pages/clock/ChooseScenario'
                //     })
                // }
            }


        }
    }, [user.isLogin])

    useReady(() => {
        // getCode()

    })

    function getCode() {
        setBtnDisable(true)
        if (process.env.TARO_ENV === 'weapp') {
            thirdPartRequest(RequestType.RequestTypeWXLogin).then(res => {
                login((res as any).code)
            }).catch(err => {
                Taro.showToast({
                    title: '登录失败，请稍等重试',
                    icon: 'none'
                })
                setBtnDisable(false)
            })

            // Taro.login().then(res => {
            //     setCode(res.code)
            //     login(res.code)
            //     // setBtnDisable(false)
            // }).catch(e => {
            //     console.log(e)
            //     // getCode()
            //     setBtnDisable(false)
            // })
        }
    }

    async function login(strCode) {
        setBtnDisable(true)
        wxLogin(strCode).then(res => {
            console.log(res)
            dispatch(loginSuccess(res));
            setBtnDisable(false)
            if (!(res as any).is_new_user){
                Taro.navigateBack({
                    delta: 1
                })
            }

            // if (!(res as any).is_new_user){
            //     if ((res as any).scenario_select_count > 0) {
            //         console.log('choose auth navi back')
            //         Taro.navigateBack({
            //             delta: 1
            //         })
            //     }
            //     else {
            //         debugger
            //         Taro.redirectTo({
            //             url: '/pages/clock/ChooseScenario?trigger_event=SETUP_UPON_ACCOUNT_CREATION'
            //         })
            //     }
            // }
        }).catch(e => {
            setBtnDisable(false)
        })
        // dispatch(wxLogin(code) as any);
        // try {
        //     const { encryptedData, iv } = await Taro.getUserProfile({
        //         desc: '获取用户信息',
        //     });

        //     dispatch(wxLogin(code, encryptedData, iv) as any);

        //     // 在这里处理用户信息
        // } catch (error) {
        //     console.log('获取用户信息失败:', error);
        // }
    }

    function createAccount1() {
        jumpPage('/pages/account/Auth', 'Auth', navigation)
    }

    function login1() {
        jumpPage('/pages/account/Auth', 'Auth', navigation, { isLogin: true })
    }

    return <View className="container choose_container">
        <Texts text='fast16cc' type={TextType.big} />
        <Text className="slogan">{t('page.choose_auth.slogan')}</Text>
        {
            process.env.TARO_ENV == 'weapp' ? <ChooseScenarioBtn disable={btnDisable} title={t('page.choose_auth.btn_wechat')} onClick={getCode} background={ColorType.fast} /> :
                <ChooseScenarioBtn disable={btnDisable} title={t('page.choose_auth.btn_login')} onClick={login1} background={ColorType.fast} />
            // <Text style={{color:'red'}} onClick={createAccount1}>{t('page.choose_auth.btn_signup')}</Text>
        }

        <View style={{ height: 30 }} />
        {
            process.env.TARO_ENV == 'rn' && <ChooseScenarioBtn disable={btnDisable} title={t('page.choose_auth.btn_signup')} onClick={createAccount1} background={ColorType.fast} />
        }
        {/* <ChooseScenarioBtn title={t('page.choose_auth.btn_wechat')} onClick={login} background={ColorType.fast} /> */}
        {/* <View style={{ height: 100 }} /> */}

        {/* <Buttons title='微信登录' onClick={login} btnStyle={{ width: 289, marginBottom: 30,backgroundColor:ColorType.fast }} /> */}
        {/* <Buttons title='Create account' type={ButtonType.outline} onClick={createAccount} btnStyle={{ width: 289, marginBottom: 30 }} /> */}
    </View>;
}