<script setup lang="ts">
import { ref, Transition } from 'vue';
import { Save } from 'lucide-vue-next';
import Button from '../ui/button/Button.vue';
import Input from '../ui/input/Input.vue';
import { Form } from '@inertiajs/vue3';
import { httpApi } from '@/lib/utils';
import { Resume } from '@/types/resume';


const props = defineProps<{
    resume: Resume,
    resumeTitle: string,
}>();

const emit = defineEmits(['update:resume-title']);

const originalTitle = ref<string>(props.resumeTitle);
const titleChanged = ref<boolean>(false);

function saveTitle() {
    const resume = { ...props.resume, name: props.resumeTitle };
    resume['components_placements'] = null;

    httpApi(route('resumes.update', props.resume), {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
            'Accept': 'application/json'
        },
        body: JSON.stringify({ ...resume, _method: 'PUT' })
    }).then(() => {
        location.reload();
    });
}
</script>

<template>
    <div class="flex gap-1" >
        <Input type="text" v-model="props.resumeTitle" placeholder="Sans titre" class="border p-2 rounded" @input="(event) => {emit('update:resume-title', event.target.value); titleChanged = (event.target.value !== originalTitle)}" />
        <Transition>
            <Button v-if="titleChanged" variant="outline" class="cursor-pointer transition" @click="saveTitle"><Save /></Button>
        </Transition>
    </div>
</template>

<style lang="css" scoped>
    .v-enter-active,
    .v-leave-active {
    transition: opacity 0.3s ease;
    }

    .v-enter-from,
    .v-leave-to {
    opacity: 0;
    }
</style>
