<template>
    <component
        :class="['category-row', { editable }]"
        :to="`/category/${category}`"
        :is="wrapper"
    >
        <span class="index">{{ String(index + 1).padStart(2, '0') }}.</span>
        <form v-if="isEditing" @submit.prevent="onSave">
            <input
                v-model="categoryInput"
                class="category-input"
                type="text"
                ref="input"
                @blur="onSave"
            />
        </form>
        <span v-else class="title h1">{{ categoryInput }}</span>

        <button v-if="isEditing" class="save-button" @click="onSave">
            Save
        </button>
        <button v-else-if="editable" class="edit-button" @click="onEdit">
            Edit
        </button>
    </component>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { RouterLink } from 'vue-router'

const props = defineProps({
    index: Number,
    category: {
        type: String,
        default: () => '',
    },
    editable: {
        type: Boolean,
        default: () => false,
    },
})

const emit = defineEmits(['edited'])

const isEditing = ref(false)
const categoryInput = ref('')
const input = ref()

onMounted(() => {
    categoryInput.value = props.category

    if (categoryInput.value === '') {
        onEdit()
    }
})

const onEdit = async () => {
    isEditing.value = true
    await new Promise((res) => setTimeout(res, 300))

    input.value?.focus()
}
const onSave = async () => {
    isEditing.value = false
    emit('edited', categoryInput.value)
    await new Promise((res) => setTimeout(res, 300))

    input.value?.blur()
}

const wrapper = computed(() => {
    return props.editable ? 'div' : RouterLink
})
</script>

<style lang="scss">
.category-row {
    display: grid;
    grid-template-columns: 26px 1fr auto;
    align-items: flex-start;
    width: 100%;
    position: relative;
    padding: 8px 0 6px;
    border-bottom: 1px dashed currentColor;
    cursor: pointer;

    .index {
        margin-top: 19px;
        @include p;
    }
    .title {
        display: block;
        width: 100%;
        @include line-clamp(2);
    }
    .category-input {
        display: block;
        width: 100%;
        @include h1;

        &:focus {
            outline: none;
        }
    }
    .edit-button,
    .save-button {
        color: var(--grey-100);
        cursor: pointer;
        padding-right: 0.5em;
        padding-left: 0.5em;
        margin-top: 1.5em;
    }
    .edit-button {
        opacity: 0;
        pointer-events: none;
    }
    &.editable:hover {
        .edit-button {
            opacity: 1;
            pointer-events: auto;
        }
    }
    &.router-link-exact-active,
    &.editable {
        cursor: default;
    }
    &:hover:not(.router-link-exact-active):not(.editable) {
        color: var(--theme-accent);
    }
}
</style>
