import { useRef, useState } from "react"
import FilledButton from "../md-components/FilledButton"
import TextField from "../md-components/TextField"
import axios from "axios"
import { useNavigate } from "react-router"
import { toast } from "react-toastify"
import { useSearchParams } from "react-router-dom"

const AuthPage = () => {
    const widthStyle = {width: "100%"}
    const [login, setLogin] = useState("")
    const [password, setPassword] = useState("")
    const submitRef = useRef()
    const [loading, setLoading] = useState(false)

    const navigate = useNavigate()
    const [searchParams] = useSearchParams()

    function makeLogin() {
        if (loading) return
        setLoading(true)
        axios.post("/auth", {login: login, password: password})
        .then(() => {
            axios.get("/user")
            .then(res => {localStorage.setItem("userInfo", JSON.stringify(res.data))})
            if (searchParams.get("to") !== null) {
                navigate(searchParams.get("to"))
            } else {
                navigate("/")
            }
        })
        .catch(() => {toast.error("Неверный логин или пароль!");setLoading(false)})
    }
    function handleSubmit(e) {
        if(e.key==="Enter"){
            submitRef.current.click()
        }
    }
    return <div style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        flexDirection: "column",
        gap: "15px",
        margin: "0 15px"
    }}>
        <h2>Вход</h2>
        <form onSubmit={(e) => {e.preventDefault();makeLogin()}}
            id="form-id"
            style={{
            display: "flex",
            flexDirection: "column",
            gap: "15px",
            width: "100%",
            maxWidth: "400px",
            alignItems: "center",
        }}>
            <TextField
                style={widthStyle}
                label="Логин"
                required
                onInput={e => setLogin(e.target.value.toLowerCase())}
                value={login}
                onKeyDown={handleSubmit}
                disabled={loading}
            />
            <TextField
                style={widthStyle}
                label="Пароль"
                required
                type="password"
                onInput={e => setPassword(e.target.value)}
                value={password}
                onKeyDown={handleSubmit}
                disable={loading}
            />
            <FilledButton
                type="submit"
                style={widthStyle}
                ref={submitRef}
                disabled={loading}
            >Войти</FilledButton>
        </form>
    </div>
}

export default AuthPage