<template>
  <div>
    <div class="card">
      <div class="card-body ratio ratio-21x9 bg-dark overflow-hidden">
        <div
          class="d-flex justify-content-center text-center rounded-2"
          :style="bgStyle"
        ></div>
        <div
          class="position-absolute w-100 h-100 d-flex justify-content-center text-center"
        >
          <div v-if="isUploading || !isLoaded" class="align-self-center">
            <div class="spinner-border text-light" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
          </div>
          <div v-else class="align-self-center">
            <input
              type="file"
              @change="handleFileChange"
              accept="image/*"
              ref="fileInput"
              style="display: none"
            />
            <button class="btn btn-primary" @click="openFileInput">
              {{ getButtonName }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import route from "ziggy-js/src/js/index";

export default {
  name: "NativeImageBlock",
  props: {
    inputImage: {
      type: String,
      default: null,
    },
  },
  data: () => ({
    isLoaded: false,
    isUploading: false,
    imgSrc: null,
    placeholderSrc: "https://placekitten.com/g/2100/900",
  }),
  computed: {
    getButtonName() {
      if (this.imgSrc != null && this.imgSrc?.length > 0) {
        return "Change featured image";
      } else {
        return "Upload featured image";
      }
    },
    getBlurPx() {
      return this.imgSrc ? 0 : 12;
    },
    bgStyle() {
      return {
        backgroundImage: `url(${this.getImgSrc})`,
        backgroundPosition: "center",
        backgroundSize: "cover",
        filter: `blur(${this.getBlurPx}px)`,
        webkitFilter: `blur(${this.getBlurPx}px)`,
      };
    },
    getImgSrc() {
      if (this.imgSrc != null && this.imgSrc?.length > 0) {
        return this.imgSrc;
      }
      return this.placeholderSrc;
    },
  },
  methods: {
    openFileInput() {
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.uploadImage(file);
      }
    },
    uploadImage(file) {
      this.isUploading = true;
      const formData = new FormData();
      formData.append("file", file);

      axios
        .post(route("api.admin.upload.cloud.image"), formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((response) => {
          if (
            response.data.success === 1 &&
            response.data.file &&
            response.data.file.url
          ) {
            this.imgSrc = response.data.file.url;
            this.$emit("saved", response.data.file.url);
          } else {
            console.error("Image upload failed. Invalid response format.");
          }
        })
        .catch((error) => {
          console.error("Image upload failed:", error.response); // Log the full response
        })
        .finally(() => {
          this.isUploading = false;
        });
    },
    setInputImage() {
      if (this.inputImage != null && this.inputImage?.length > 0) {
        this.imgSrc = this.inputImage;
      }
      this.isLoaded = true;
    },
  },
  mounted() {
    this.isUploading = false;

    setTimeout(
      function () {
        this.setInputImage();
        this.isLoaded = true;
      }.bind(this),
      3000
    );
  },
};
</script>

<style scoped>
/* Add your custom styles here */
</style>
