<script lang="ts">
    import { mdiPencil } from "@mdi/js"
    import Icon from "../../../widgets/Icon.svelte"
    import { checkPassword, onChange, removeAllErrors, validateEmail, validateField, validateUsername } from "../helper"
    import Input from "../../blocks/form/Input.svelte"
    import CardWrapper from "../CardWrapper.svelte"
    import { login, newNotification } from "../../../../store"
    import {
        changeEmail,
        changePassword,
        changeUsername,
    } from "../../../../functions/CommerceAPIs/tibiEndpoints/customer"
    import { createEventDispatcher } from "svelte"
    export let customer: BigCommerceCustomer
    const dispatch = createEventDispatcher()
    const passwordChangeDetails = {
        currentPassword: "",
        password1: "",
        password2: "",
    }
    const emailChangeDetails = {
        email: "",
        currentPassword: "",
    }

    const usernameChangeDetails = {
        username: "",
        currentPassword: "",
    }
    function changePasswordValidator() {
        const validations = [
            { id: "password1", value: passwordChangeDetails.password1, validator: checkPassword },
            { id: "password2", value: passwordChangeDetails.password2, validator: checkPassword },
        ]
        let isValid = true

        for (const { id, value, validator } of validations) {
            // @ts-ignore
            if (!validateField(id, value, validator)) isValid = false
        }
        if (passwordChangeDetails.password1 !== passwordChangeDetails.password2) {
            isValid = false
            newNotification({ html: "Passwörter stimmen nicht überein", class: "error" })
        }
        return isValid
    }

    function changeEmailValidator() {
        const validations = [{ id: "eMail", value: emailChangeDetails.email, validator: validateEmail }]
        let isValid = true

        for (const { id, value, validator } of validations) {
            // @ts-ignore
            if (!validateField(id, value, validator)) isValid = false
        }
        return isValid
    }

    function changeUsernameValidator() {
        const validations = [{ id: "username", value: usernameChangeDetails.username, validator: validateUsername }]
        let isValid = true

        for (const { id, value, validator } of validations) {
            // @ts-ignore
            if (!validateField(id, value, validator)) isValid = false
        }
        return isValid
    }

    let form: HTMLFormElement
    let editMode: "" | "password" | "email" | "username" = ""
</script>

<div class="wrapper">
    <CardWrapper>
        <form
            bind:this="{form}"
            class:editMode="{editMode}"
        >
            <h3>Identifizierende Daten</h3>
            {#if editMode}
                {#if editMode === "password"}
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{passwordChangeDetails.currentPassword}"
                            placeholder="Aktuelles Passwort"
                            id="currentPassword"
                            type="password"
                        />
                    </div>
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{passwordChangeDetails.password1}"
                            placeholder="Neues Passwort"
                            id="password1"
                            type="password"
                        />
                        <Input
                            onChange="{onChange}"
                            bind:value="{passwordChangeDetails.password2}"
                            placeholder="Neues Passwort wiederholen"
                            id="password2"
                            type="password"
                        />
                    </div>
                {:else if editMode === "email"}
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{emailChangeDetails.currentPassword}"
                            placeholder="Aktuelles Passwort"
                            id="currentPassword"
                            type="password"
                        />
                    </div>
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{emailChangeDetails.email}"
                            placeholder="Neue E-Mail"
                            id="eMail"
                            type="text"
                        />
                    </div>
                {:else if editMode == "username"}
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{usernameChangeDetails.currentPassword}"
                            placeholder="Aktuelles Passwort"
                            id="currentPassword"
                            type="password"
                        />
                    </div>
                    <div class="row">
                        <Input
                            onChange="{onChange}"
                            bind:value="{usernameChangeDetails.username}"
                            placeholder="Neuer Nutzername"
                            id="username"
                            type="text"
                        />
                    </div>
                {/if}
            {:else}
                <div class="row">
                    <div class="details">
                        <div class="row">
                            <Input
                                onChange="{() => {}}"
                                value="{customer.email}"
                                placeholder="E-Mail"
                                id="eMail"
                                disabled="{true}"
                                type="{editMode ? 'text' : 'noInput'}"
                            />
                            <Input
                                placeholder="Passwort"
                                id="password"
                                onChange="{onChange}"
                                type="noInput"
                                value=""
                            />
                        </div>
                        <div class="row">
                            <Input
                                onChange="{() => {}}"
                                value="{customer.form_fields.find((field) => field.name === 'username')?.value}"
                                placeholder="Nutzername"
                                id="userName"
                                type="noInput"
                                disabled="{true}"
                            />
                        </div>
                    </div>
                </div>
            {/if}
            {#if editMode}
                <div class="action-button-line">
                    <button
                        class="cta primary"
                        on:click|stopPropagation|preventDefault="{() => {
                            editMode = ''
                            removeAllErrors(form)
                        }}">Änderungen verwerfen</button
                    >
                    <button
                        class="cta secondary"
                        on:click|stopPropagation|preventDefault="{async () => {
                            if (editMode === 'password') {
                                if (changePasswordValidator()) {
                                    const res = await changePassword(
                                        $login.tokenData.tibiId,
                                        passwordChangeDetails.currentPassword,
                                        passwordChangeDetails.password1
                                    )
                                    if (res) {
                                        editMode = ''
                                        passwordChangeDetails.currentPassword = ''
                                        passwordChangeDetails.password1 = ''
                                        passwordChangeDetails.password2 = ''
                                        dispatch('update')
                                    }
                                }
                            } else if (editMode === 'email') {
                                if (changeEmailValidator()) {
                                    const res = await changeEmail(
                                        $login.tokenData.tibiId,
                                        emailChangeDetails.email,
                                        emailChangeDetails.currentPassword
                                    )
                                    if (res) {
                                        editMode = ''
                                        customer.email = emailChangeDetails.email
                                        emailChangeDetails.email = ''
                                        emailChangeDetails.currentPassword = ''
                                        location.reload()
                                        dispatch('update')
                                    }
                                }
                            } else if (editMode === 'username') {
                                if (changeUsernameValidator()) {
                                    const res = await changeUsername(
                                        $login.tokenData.tibiId,
                                        usernameChangeDetails.username,
                                        usernameChangeDetails.currentPassword
                                    )
                                    if (res) {
                                        editMode = ''
                                        const index = customer.form_fields.findIndex(
                                            (field) => field.name === 'username'
                                        )
                                        if (index !== -1) {
                                            customer.form_fields[index].value = usernameChangeDetails.username
                                        } else if (customer.form_fields) {
                                            customer.form_fields.push({
                                                name: 'username',
                                                value: usernameChangeDetails.username,
                                            })
                                        } else {
                                            customer.form_fields = [
                                                { name: 'username', value: usernameChangeDetails.username },
                                            ]
                                        }
                                        usernameChangeDetails.username = ''
                                        usernameChangeDetails.currentPassword = ''
                                        //location.reload()
                                        dispatch('update')
                                    }
                                }
                            }
                        }}">Änderungen speichern</button
                    >
                </div>
            {:else}
                <div class="action-line">
                    <button
                        on:click|stopPropagation|preventDefault="{() => {
                            editMode = 'email'
                        }}"
                    >
                        <p>Email</p>

                        <span><Icon path="{mdiPencil}" /> </span></button
                    >

                    <button
                        on:click|stopPropagation|preventDefault="{() => {
                            editMode = 'password'
                        }}"
                    >
                        <p>Passwort</p>

                        <span><Icon path="{mdiPencil}" /> </span></button
                    >
                    <button
                        on:click|stopPropagation|preventDefault="{() => {
                            editMode = 'username'
                        }}"
                    >
                        <p>Nutzername</p>

                        <span><Icon path="{mdiPencil}" /> </span></button
                    >
                </div>
            {/if}
        </form>
    </CardWrapper>
</div>

<style lang="less">
    @import "../../../../assets/css/variables.less";
    .wrapper {
        display: flex;
        width: 100%;
        flex-grow: 1;
        form {
            h3 {
                padding: 0px 2.4rem;
                color: var(--text-invers-100);
            }
            display: flex;
            flex-direction: column;
            gap: 1.2rem;
            .row {
                padding: 0px 2.4rem;
                display: flex;
                gap: 1.2rem;
                @media (max-width: 500px) {
                    gap: 1.2rem;
                    &:first-of-type {
                        flex-wrap: wrap;
                    }
                }
                .details {
                    display: flex;
                    flex-direction: column;
                    gap: 1.2rem;
                    .row {
                        padding: 0px;
                    }
                }
            }
            &.editMode {
                @media (max-width: 500px) {
                    .row {
                        flex-direction: column;
                    }
                }
            }
            .action-button-line,
            .action-line {
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                button {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    gap: 10px;
                    width: 0px;
                    flex-grow: 1;
                    @media (max-width: 500px) {
                        flex-grow: unset;
                        width: fit-content;
                        gap: 7px;
                        flex-direction: column;
                    }
                }
            }
            .action-line {
                background: var(--bg-100);
                padding: 0.6rem 3.3rem 0.6rem 3.3rem;
                display: flex;
                flex-direction: row;
                align-items: center;
                min-height: 2.4rem;
                justify-content: space-between;
                @media (max-width: 500px) {
                    padding: 1.2rem 3.3rem 1.2rem 3.3rem;
                    height: 3.6rem;
                }
                p,
                span {
                    color: var(--neutral-white);
                }
            }

            .action-button-line {
                min-height: 2.4rem;
                display: flex;
                width: 100%;
                button {
                    width: 0px;
                    height: 100%;
                    flex-grow: 1;
                }
            }
        }
    }
</style>
