﻿<template>
  <h2 class="text-2xl font-semibold mb-4">
    Bannière
  </h2>

  <img
      :src="fileUrl || fallbackUrl"
      class="mb-5 w-full transition duration-200 ease-in-out transform"
      alt="Aperçu de la bannière"
  >

  <v-file-input
      v-model="selectedFile"
      variant="outlined"
      accept="image/*"
      label="Votre bannière"
      @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?.banner)
const fallbackUrl = '/images/hutopymedia/banners/hutopyul.png'

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}/banner`,
        formData
    )

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

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