<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { SetupHandle, SetSize, ResetPosition, ClearWindow } from '@/services/Windows';
import WindowHandle from './partials/WindowHandle.vue';
import Server from '~/services/Server';
import { emitter } from '~/services/Emitter';

const handle = ref(null);
const wrapper = ref(null);

const props = defineProps(['data']);
const data = props.data;

let id = data.id;

const newName = ref('');

onMounted(() => {
    newName.value = data.title || '';
    SetupHandle(id, handle);
    SetSize(id, { width: 420, height: 200 });
    ResetPosition(id, 'center');
});

onBeforeUnmount(() => {
    ClearWindow({ type: 'rename_note' });
});

function confirmRename() {
    if (!newName.value.trim()) {
        return;
    }
    Server().post('/note/update', {
        id: data.key,
        title: newName.value.trim(),
    }).then((response) => {
        if (response.data.status !== 'ok') {
            return;
        }
        emitter.emit('note-renamed', { key: data.key, title: newName.value.trim() });
        ClearWindow({ id });
    }).catch(() => {});
}
</script>

<template>
    <div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper">
        <WindowHandle :window="id" ref="handle"></WindowHandle>

        <div class="body">
            <h3>Rename Note</h3>
            <form v-on:submit.prevent="confirmRename">
                <div class="form-field">
                    <input
                        type="text"
                        v-model="newName"
                        placeholder="Note title"
                        autofocus
                        autocomplete="off"
                    >
                </div>
                <div class="form-actions">
                    <button class="btn-primary sound-click" type="submit">Save</button>
                </div>
            </form>
        </div>
    </div>
</template>

<style scoped>
.window-wrapper {
    display: flex;
    align-items: center;
    flex-direction: column;
}

.body {
    width: 100%;
    padding: 10px;
}

h3 {
    margin: 0 0 10px 10px;
    font-family: MrEavesRemake;
}

form {
    margin-left: 10px;
    margin-right: 10px;
}

.form-field {
    display: flex;
    flex-direction: row;
    width: 100%;
}

.form-field > * {
    flex-grow: 1;
}

input {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid var(--color-border);
    border-radius: 6px;
    background: var(--color-background-soft);
    color: var(--color-text);
    font-size: 14px;
}

input:focus {
    outline: none;
    border-color: var(--color-accent);
}

.form-actions {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}

.form-actions button {
    width: 100%;
    max-width: 200px;
}
</style>
