---
import LoggedIn from '../../layouts/LoggedIn.astro';
import User from '../../lib/classes/User';
import format from '../../lib/utils/format';
import { getName, getSupportedLanguages } from '../../lib/utils/langDriver';

const { token, lang } = Astro.locals;
const user: User = Astro.locals.user;

const availableLanguages = await getSupportedLanguages();

if(Astro.request.method === "POST") {
    const body = await Astro.request.formData();
    const selectedLanguage = body.get('language')?.toString() ?? null;

    if(!selectedLanguage) return Astro.redirect('/profile');

    if(!availableLanguages.map(l => l.id).includes(selectedLanguage)) return Astro.redirect('/profile');

    Astro.cookies.set('language', selectedLanguage, {
        path: '/',
        maxAge: 60 * 60 * 24 * 365,
        sameSite: 'lax',
        secure: true
    });
}
const currentLanguage = Astro.cookies.get('language')?.value ?? "en";
---
<LoggedIn id="profile" title="Profile">
    {token}
    <div class="wrapper">
        <h3>{format(getName(lang, 'general', 'user-creation-date'), user?.createdAt.toISOString().slice(0, 19).replace(/-/g, "/").replace("T", " ").toString() ?? "")}</h3>
        <a href="/logout" class="a-button">{getName(lang, 'general', 'nav-logout')}</a>
    </div>
    <form id="changeUsernameForm" class="data-form">
        <input class="data-form-input" type="text" name="username" placeholder={getName(lang, 'general', 'input-placeholder-new-username')} />
        <input class="data-form-input" type="password" name="password" placeholder={getName(lang, 'general', 'input-placeholder-password')} />
        <input class="data-form-button" type="button" value={getName(lang, 'general', 'change-username')} />
    </form>
    <form id="changeEmailForm" class="data-form">
        <input class="data-form-input" type="email" name="email" placeholder={getName(lang, 'general', 'input-placeholder-new-email')} />
        <input class="data-form-input" type="password" name="password" placeholder={getName(lang, 'general', 'input-placeholder-password')} />
        <input class="data-form-button" type="button" value={getName(lang, 'general', 'change-email')} />
    </form>
    <form id="changePasswordForm" class="data-form">
        <input class="data-form-input" type="password" name="oldPassword" placeholder={getName(lang, 'general', 'input-placeholder-old-password')} />
        <input class="data-form-input" type="password" name="password1" placeholder={getName(lang, 'general', 'input-placeholder-new-password')} />
        <input class="data-form-input" type="password" name="password2" placeholder={getName(lang, 'general', 'input-placeholder-new-password-verify')} />
        <input class="data-form-button" type="button" value={getName(lang, 'general', 'change-password')} />
    </form>
    <form id="changeLanguageForm" class="data-form" method="post">
        <h3>{getName(lang, 'general', 'current-language')}: {availableLanguages.find(l => l.id === currentLanguage)?.name ?? "N/A"}</h3>
        <select class="data-form-input" name="language">
            {availableLanguages.map((lang) => (
                <option value={lang.id}>{lang.name}</option>
            ))}
        </select>
        <input type="submit" class="data-form-button" value={getName(lang, 'general', 'change-language')} />
    </form>
</LoggedIn>
<style>
h3 {
    color: white;
}

.data-form {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 2rem;
}

.data-form-input {
    color: black;
}

.data-form-button {
    color: red;
    font-weight: 700;
}

.wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 2rem;
    color: white;
}

.a-button {
	text-decoration: none;
	color: green;
}

.a-button:hover {
	color: lime;
}
</style>
<script>
    const changeUsernameForm = document.getElementById('changeUsernameForm');
    if(changeUsernameForm === null) console.error("changeUsernameForm is null");
    else {
        changeUsernameForm.querySelector('input[type="button"]')?.addEventListener("click", async () => {
            const newUsername = (changeUsernameForm.querySelector('input[name="username"]') as HTMLInputElement).value;
            const password = (changeUsernameForm.querySelector('input[name="password"]') as HTMLInputElement).value;
    
            const request = await fetch('/api/auth/changeUserData/username', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    newUsername,
                    password
                })
            });

            const response = await request.json();
            console.log(response);

            window.location.reload();
        });
    }

    const changeEmailForm = document.getElementById('changeEmailForm');
    if(changeEmailForm === null) console.error("changeEmailForm is null");
    else {
        changeEmailForm.querySelector('input[type="button"]')?.addEventListener("click", async () => {
            const newEmail = (changeEmailForm.querySelector('input[name="email"]') as HTMLInputElement).value;
            const password = (changeEmailForm.querySelector('input[name="password"]') as HTMLInputElement).value;
    
            const request = await fetch('/api/auth/changeUserData/email', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    newEmail,
                    password
                })
            });

            const response = await request.json();
            console.log(response);

            window.location.reload();
        });
    }

    const changePasswordForm = document.getElementById('changePasswordForm');
    if(changePasswordForm === null) console.error("changePasswordForm is null");
    else {
        changePasswordForm.querySelector('input[type="button"]')?.addEventListener("click", async () => {
            const oldPassword = (changePasswordForm.querySelector('input[name="oldPassword"]') as HTMLInputElement).value;
            const password1 = (changePasswordForm.querySelector('input[name="password1"]') as HTMLInputElement).value;
            const password2 = (changePasswordForm.querySelector('input[name="password2"]') as HTMLInputElement).value;

            if(password1 !== password2) return alert("Passwords don't match");
            else {
                const request = await fetch('/api/auth/changeUserData/password', {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        password: oldPassword,
                        newPassword: password1
                    })
                });

                const response = await request.json();
                console.log(response);

                window.location.reload();
            }
        });
    }
</script>