import {Button, Space, Spin, Typography} from "@douyinfe/semi-ui";
import {useTranslation} from 'react-i18next';
import {useEffect} from "react";
import {useSetState} from "ahooks";
import styled from "@emotion/styled";
import {useNavigate, useSearchParams} from "react-router-dom";

import useConfig from "@/hooks/useConfig.ts";
import AppLogo from "@/assets/AppLogo";
import useAuth from "@/hooks/useAuth.ts";
import {getAppUrl} from "@/hooks/useAppUrl";


const LoginContainer = styled.div({
    backgroundColor: '#fff',
    borderRadius: 10,
    padding: 40
})
const LogoContainer = styled.div({
    display: "flex",
    alignItems: 'center',
    justifyContent: 'center'
})
const SubmitContainer = styled.div({
    textAlign: 'center',
    width: 300,
    margin: '70px auto 20px'
})

const LoginURL = getAppUrl() + '/login?action=auth'
const AuthLogin = () => {
    const {login, mockLogin} = useAuth();
    const navigate = useNavigate();
    const [state, setState] = useSetState({
        showLogin: false,
        loading: false
    })

    const {t} = useTranslation();
    const {appName} = useConfig()
    const [query] = useSearchParams()

    useEffect(() => {
        const code = query.get('code'),
            state = query.get('state');

        if (query.get('action') == 'auth' && state && code) {
            setState({loading: true})
            // 授权回调
            login(code, state).then(() => {
                navigate('/dashboard')
            }).catch(() => {
                // 获取登录凭证失败 重新显示登录按钮
                setTimeout(() => {
                    setState({showLogin: true})
                }, 2000)
            }).finally(() => {
                setTimeout(() => {
                    setState({loading: false})
                }, 2000)
            })
        } else {
            // 正常登录 - 显示登录按钮
            setState({
                showLogin: true
            })
        }
    }, [])

    const handleMockLogin = () => {
        mockLogin().then(() => {
            navigate('/dashboard')
        })
    }

    return (<LoginContainer>
        <LogoContainer>
            <Space spacing={10} vertical>
                <AppLogo style={{fontSize: 40}}/>
                <Typography.Title heading={2}>{appName}</Typography.Title>
            </Space>
        </LogoContainer>
        <SubmitContainer>
            {state.loading && <Space>
                <Spin/><span>Authing ...</span>
            </Space>}
            {state.showLogin && <div style={{marginTop: 5}}>
                <a
                    className="btn-auth-login semi-button semi-button-primary semi-button-block"
                    href={`${AppConfig.SSO_AUTH_URL}/authorize?response_type=code&scope=openid%20profile%20email&client_id=${AppConfig.SSO_AUTH_CLIENT_KEY}&state=${Date.now()}&redirect_uri=${encodeURIComponent(LoginURL)}`}
                >
                    <span className="semi-button-content" x-semi-prop="children">{t('login.submit')}</span>
                </a>
                <Button theme='solid' type='warning' block onClick={handleMockLogin} style={{marginTop: 5}}>MOCK
                    LOGIN</Button>
            </div>}
        </SubmitContainer>
    </LoginContainer>)
}

export default AuthLogin