﻿<template>
  <h2 class="text-2xl font-semibold mb-4 flex justify-center">
    Logo
  </h2>

  <div class="flex justify-center mb-5">
    <img
        :src="fileUrl || fallbackUrl"
        class="w-full transition duration-200 ease-in-out transform max-w-[400px]"
        alt="Aperçu du logo"
    />
  </div>

  <v-file-input
      v-model="selectedFile"
      variant="outlined"
      accept="image/*"
      label="Votre logo"
      @change="onFileSelected"
  ></v-file-input>

  <div class="flex justify-end space-x-4">
    <v-btn color="black" variant="text" @click="cancel">Annuler</v-btn>
    <v-btn color="#A6147D" @click="publish">Enregistrer</v-btn>
  </div>

</template>


<script setup>
import {ref} from 'vue'
import {useClient} from '@/plugins/api.js'

const props = defineProps({
  creator: {
    required: true
  }
})

const emits = defineEmits(['closeRequested'])

const selectedFile = ref("")
const fileUrl = ref(props.creator.images.logo)
const fallbackUrl = '/images/usersmedia/HutopyProfile/profilepictures/profileHutopyProfile01.png' // Chemin de votre image de secours

const onFileSelected = () => {
  if (selectedFile.value) {
    const reader = new FileReader()
    reader.onload = (event) => {
      fileUrl.value = event.target.result
    }
    reader.readAsDataURL(selectedFile.value)
  } else {
    fileUrl.value = null
  }
}

const client = useClient()
const publish = async () => {
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value)

    await client.post(
        `/api/creators/${props.creator.id}/logo`,
        formData)

    props.creator.images.logo = fileUrl.value;
    emits('closeRequested');
  } catch (error) {
    console.error(error)
  }
}

const cancel = () => {
  emits('closeRequested')
}
</script>

