﻿<template>
  <div class="card">
    <div class="card-title">
      Bannière
    </div>

    <div class="card-content">
      <img
          :src="fileUrl || fallbackUrl"
          alt="Aperçu de la bannière"
          class="mb-5 transition duration-200 ease-in-out transform  w-[1024px] h-[256px]"
      />

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

    <div class="card-actions">
      <button class="secondary"
              @click="cancel">
        Annuler
      </button>
      <button class="primary"
              @click="publish">
        Enregistrer
      </button>
    </div>

  </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)

    const response = await client.post(
        `/api/creators/${props.creator.id}/banner`,
        formData
    )

    props.creator.images.banner = `${response.data.blobUrl}?t=${Date.now()}`
    emits('closeRequested')
  } catch (error) {
    console.error(error)
  }
}

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