import {Button, Container, Paper, Title,} from '@mantine/core';
import classes from './LoginPage.module.scss';
import {RootState, useAppDispatch} from "../../redux/store.ts";
import {AuthService} from "../../client";
import TelegramLoginButton, {TelegramUser} from "../../components/TelegramAuthButton/TelegramAuthButton.tsx";
import {notifications} from "../../shared/lib/notifications.ts";
import {login} from "../../features/authSlice.ts";
import {Navigate, useNavigate} from "@tanstack/react-router";
import {useSelector} from "react-redux";
import {useEffect} from "react";

const LoginPage = () => {
    const dispatch = useAppDispatch();
    const authState = useSelector((state: RootState) => state.auth);
    const navigate = useNavigate();
    useEffect(() => {
        if (authState.isAuthorized)
            // ???????????
            navigate({to: "/leads"}).then(() => {
                navigate({to: "/leads"}).then(() => {
                    notifications.success({message: "Вы успешно вошли!"})
                });
            });
    }, [authState.isAuthorized])
    if (authState.isAuthorized) {
        return (<Navigate to={"/leads"}/>)
    }

    return (

        <Container size={420} my={40}>
            <Title ta="center" className={classes.title}>
                Добро пожаловать на DENCO CRM
            </Title>
            <Paper withBorder shadow="md" p={30} mt={30} radius="md">
                <TelegramLoginButton
                    botName={"DencoFulfillmentTestBot"}
                    dataOnauth={() => {
                    }}
                    wrapperProps={{style: {display: "none"}}}
                />
                <Button fullWidth onClick={() => {
                    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                    // @ts-expect-error
                    window.Telegram.Login.auth(
                        {
                            bot_id: import.meta.env.VITE_BOT_ID,
                            request_access: true
                        },
                        (data: TelegramUser) => {
                            AuthService.loginAuthLoginPost({requestBody: data})
                                .then(({accessToken}) => {
                                    dispatch(login({accessToken: accessToken}));
                                }).catch(() => {
                                notifications.error({message: "Неудалось войти!"})
                            })
                        }
                    )

                }}>
                    Войти через Telegram
                </Button>
            </Paper>
        </Container>
    )
}
export default LoginPage