<script lang="ts">
    import CardWrapper from "../CardWrapper.svelte"
    import { login, newNotification } from "../../../../store"
    import Address from "./Address.svelte"
    import AddressForm from "../AddressForm.svelte"
    import Icon from "../../../widgets/Icon.svelte"
    import { mdiPlusCircleOutline } from "@mdi/js"
    import { createEmptyAddress, removeAllErrors, validateAddress } from "../helper"
    import {
        updateCustomerAddress,
        addCustomerAddress,
        deleteCustomerAddress,
        getCustomerAddresses,
    } from "../../../../functions/CommerceAPIs/tibiEndpoints/customer"
    import Loader from "../../Loader.svelte"

    async function updateAddress(editedAddress: BigCommerceAddress, addresses: BigCommerceAddress[]) {
        if (editedAddress.id) {
            await updateCustomerAddress($login.tokenData.tibiId, editedAddress).then((updatedAddress) => {
                const index = addresses.findIndex((a) => a.id === updatedAddress.id)
                addresses[index] = updatedAddress
            })
        } else {
            const identicalAddress = addresses.find((a) => {
                return (
                    a.address1 === editedAddress.address1 &&
                    a.address2 === editedAddress.address2 &&
                    a.city === editedAddress.city &&
                    a.state_or_province === editedAddress.state_or_province &&
                    a.postal_code === editedAddress.postal_code &&
                    a.country_code === editedAddress.country_code
                )
            })
            if (identicalAddress) {
                newNotification({
                    class: "warning",
                    html: "Diese Adresse ist bereits gespeichert!",
                })
                return
            }

            await addCustomerAddress($login.tokenData.tibiId, editedAddress).then((newAddress) => {
                addresses.push(newAddress)
            })
        }
    }
    let editedAddress: BigCommerceAddress = undefined
    let form: HTMLFormElement
    let rerender = 0
</script>

<div class="wrapper">
    <CardWrapper>
        <div class="inner-wrapper">
            <h3>
                {editedAddress
                    ? !editedAddress.id
                        ? "Adresse hinzufügen"
                        : "Adresse bearbeiten"
                    : "Gespeicherte Adressen"}
            </h3>
            {#await getCustomerAddresses($login.tokenData.tibiId)}
                <Loader
                    size="4"
                    type="circle"
                />
            {:then addresses}
                <div class="inner-body">
                    {#if editedAddress}
                        <form bind:this="{form}">
                            <div class="address">
                                <AddressForm bind:address="{editedAddress}" />
                            </div>
                            <div class="action-button-line">
                                <button
                                    class="cta primary"
                                    on:click|stopPropagation|preventDefault="{() => {
                                        editedAddress = undefined
                                        removeAllErrors(form)
                                    }}">{editedAddress.id ? "Änderungen" : "Adresse"} verwerfen</button
                                >
                                <button
                                    class="cta secondary"
                                    on:click|stopPropagation|preventDefault="{() => {
                                        const isValid = validateAddress(editedAddress)
                                        if (isValid)
                                            updateAddress(editedAddress, addresses).then(
                                                () => (editedAddress = undefined)
                                            )
                                    }}">{editedAddress.id ? "Änderungen" : "Adresse"} speichern</button
                                >
                            </div>
                        </form>
                    {:else}
                        <ul>
                            {#key rerender}
                                {#each addresses as address, i}
                                    {#if address}
                                        <Address
                                            showDelete="{addresses.length > 1}"
                                            address="{address}"
                                            on:edit="{() => {
                                                editedAddress = JSON.parse(JSON.stringify(address))
                                            }}"
                                            on:delete="{() => {
                                                deleteCustomerAddress($login.tokenData.tibiId, address.id).then(() => {
                                                    let addressIndex = addresses.findIndex((a) => a.id === address.id)
                                                    addresses.splice(addressIndex, 1)
                                                    rerender += 1
                                                })
                                            }}"
                                        />
                                    {/if}
                                {/each}{/key}
                        </ul>
                        <button
                            class="action-line"
                            on:click|stopPropagation|preventDefault="{() => {
                                editedAddress = createEmptyAddress()
                            }}"
                        >
                            <p>Neue Adresse hinzufügen</p>
                            <span><Icon path="{mdiPlusCircleOutline}" /> </span>
                        </button>
                    {/if}
                </div>
            {/await}
        </div>
    </CardWrapper>
</div>

<style lang="less">
    @import "../../../../assets/css/variables.less";
    .wrapper {
        display: flex;
        width: 100%;
        height: 100%;
        flex-grow: 1;
        .inner-wrapper {
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            gap: 1.2rem;
            height: 100%;
            h3 {
                padding: 0px 1.2rem;
                color: var(--text-invers-100);
                margin-bottom: 0.6rem;
            }
            .inner-body {
                flex-direction: column;
                display: flex;
                gap: 1.2rem;
                flex-grow: 1;
                justify-content: space-between;
                form {
                    .address {
                        width: 100%;
                        display: flex;
                        flex-direction: column;
                        gap: 1.2rem;
                    }

                    width: 100%;
                    display: flex;
                    flex-direction: column;
                    gap: 2.4rem;
                }
                ul {
                    display: grid;
                    grid-template-columns: 1fr 1fr;
                    @media @mobile {
                        grid-template-columns: 1fr;
                    }
                    padding: 0px 2.4rem;
                    gap: 1.2rem;
                }
                .action-button-line,
                .action-line {
                    display: flex;
                    flex-direction: row;
                    align-items: center;
                    justify-content: space-between;
                }
                .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;
                    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>
