﻿<template>
  <div v-if="creatorProfileStore.creator?.id === brandingStore.value.id" class="flex justify-end space-x-2 mb-5 pa-1">
    <!-- Bouton principal : Éditer ou Enregistrer -->
    <button
        v-if="isLoggedIn"
        @click="isEditMode ? saveChanges() : toggleEditMode()"
        class="px-4 py-2 rounded-md hover:opacity-90"
        :style="{ backgroundColor: brandingStore.colors.secondary, color: brandingStore.colors.onSecondary }"
    >
      {{ isEditMode ? 'Enregistrer' : 'Éditer la page' }}
    </button>

    <button
        v-if="isEditMode && isLoggedIn"
        @click="cancelEdit"
        class="px-4 py-2 rounded-md hover:opacity-90 bg-red-500 text-white"
    >
      Annuler
    </button>
  </div>

  <!-- MainPage -->
  <div v-if="!isEditMode" class="rounded-2xl flex flex-col space-y-6">

    <!-- Main image -->
    <div v-if="mainTitle || mainImageUrl || mainImageText " class="py-4" :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onPrimary }">
      <div v-if="mainTitle">
        <h1 class="text-4xl font-bold text-center py-4 mb-4">{{ mainTitle }}</h1>
      </div>

      <img
          v-if="mainImageUrl"
          :src="mainImageUrl"
          alt="Image principale"
          class="rounded-2xl  max-w-full h-auto cursor-pointer"
          @click="openFullscreen(mainImageUrl)"/>

      <p v-if="mainImageText" class="text-lg text-justify pa-6">
        {{ mainImageText }}
      </p>
    </div>

    <!-- Main video -->
    <div v-if="videoSubtitleMain || videoUrlMain || mainVideoText " :style="{ backgroundColor: brandingStore.colors.surface, color: brandingStore.colors.onSurface }">
      <h2 v-if="videoSubtitleMain" class="text-3xl font-semibold text-center py-6">
        {{ videoSubtitleMain }}
      </h2>

      <div v-if="videoUrlMain" class="video-container">
        <iframe
            :src="videoUrlMain"
            title="YouTube video player"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen
            class="video-frame">
        </iframe>
      </div>
      <p v-if="mainVideoText" class="text-lg text-justify pa-6 mb-4">
        {{ mainVideoText }}
      </p>
    </div>

    <!-- Images  -->
    <div v-if="imagesSubtitle || image1Url || image2Url || image3Url || image4Url || imagesText " :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onPrimary }">
      <div>
        <h2 v-if="imagesSubtitle" class="text-xl font-semibold text-center mb-6">
          {{ imagesSubtitle }}
        </h2>
      </div>

      <!--        images-->
      <div class="pa-2">
        <FullscreenImage ref="fullscreenImage" :image-url="currentImage"/>
        <div>
          <!-- Affichage des images -->
          <div class="flex flex-wrap gap-4">
            <!-- Première image -->
            <div class="relative w-full sm:flex-1 sm:min-w-[calc(25%-1rem)]" v-if="image1Url"
                 @click="openFullscreen(image1Url)">
              <img :src="image1Url" alt="Image 1" class="rounded-md max-w-full h-auto cursor-pointer"/>
            </div>

            <!-- Deuxième image -->
            <div class="relative w-full sm:flex-1 sm:min-w-[calc(25%-1rem)]" v-if="image2Url"
                 @click="openFullscreen(image2Url)">
              <img :src="image2Url" alt="Image 2" class="rounded-md max-w-full h-auto cursor-pointer"/>
            </div>

            <!-- Troisième image -->
            <div class="relative w-full sm:flex-1 sm:min-w-[calc(25%-1rem)]" v-if="image3Url"
                 @click="openFullscreen(image3Url)">
              <img :src="image3Url" alt="Image 3" class="rounded-md max-w-full h-auto cursor-pointer"/>
            </div>

            <!-- Quatrième image -->
            <div class="relative w-full sm:flex-1 sm:min-w-[calc(25%-1rem)]" v-if="image4Url"
                 @click="openFullscreen(image4Url)">
              <img :src="image4Url" alt="Image 4" class="rounded-md max-w-full h-auto cursor-pointer"/>
            </div>
          </div>
        </div>
      </div>

      <div>
        <p v-if="imagesText" class="text-lg text-justify pa-6">
          {{ imagesText }}
        </p>
      </div>

    </div>

    <!--SecondVideo-->
    <div v-if="videoSubtitle || videoUrl || videoText " :style="{ backgroundColor: brandingStore.colors.surface, color: brandingStore.colors.onSurface }">
      <h2 v-if="videoSubtitle" class="text-xl font-semibold text-center py-6">
        {{ videoSubtitle }}
      </h2>

      <div class="flex justify-center items-center h-full">
        <iframe
            v-if="videoUrl"
            :src="videoUrl"
            title="YouTube video player"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowfullscreen
            class="rounded-md"
            style="width: 600px; height: 337px;"
        ></iframe>
      </div>

      <p v-if="videoText" class="text-lg text-justify pa-6">
        {{ videoText }}
      </p>
    </div>

    <!-- Contact Info-->
    <div v-if="editablePhoneNumber || editableEmail" class="mb-6" :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onPrimary }">
      <!--      mobile-->
      <div v-if="smAndDown">
        <div class="flex flex-col space-y-10 justify-center items-center">
          <!-- Affichage du téléphone -->
          <div v-if="editablePhoneNumber" class="flex items-center space-x-2">
            <i class="mdi mdi-phone-outline text-2xl"></i>
            <span>{{ editablePhoneNumber }}</span>
          </div>
          <!-- Affichage de l'email -->
          <div v-if="editableEmail" class="flex items-center space-x-2">
            <i class="mdi mdi-email-outline text-2xl"></i>
            <a
                :href="`mailto:${editableEmail}`"
                class="no-underline text-current"
            >
              {{ editableEmail }}
            </a>
          </div>
        </div>
      </div>

      <!--pc-->
      <div v-if="!smAndDown">
        <div class="flex space-x-64 space-y-4 justify-center items-center">
          <!-- Affichage du téléphone -->
          <div v-if="editablePhoneNumber" class="flex items-center space-x-2">
            <i class="mdi mdi-phone-outline text-2xl"></i>
            <span>{{ editablePhoneNumber }}</span>
          </div>
          <!-- Affichage de l'email -->
          <div v-if="editableEmail" class="flex items-center space-x-2">
            <i class="mdi mdi-email-outline text-2xl"></i>
            <a
                :href="`mailto:${editableEmail}`"
                class="no-underline text-current"
            >
              {{ editableEmail }}
            </a>
          </div>
        </div>
      </div>


    </div>
  </div>


  <!--  Editmode-->
  <div v-if="isEditMode" class="space-y-10">

    <!--Main image-->
    <div class="rounded-2xl"
         :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onPrimary }">
      <div v-if="isEditMode">
        <div class="text-2xl pa-4">Image principale</div>
        <v-text-field label="Titre" variant="outlined" v-model="editableMainTitle" class="w-full p-2"></v-text-field>
      </div>

      <div class="relative flex justify-center">
        <label v-if="isEditMode">
          <input type="file" @change="updateImage('mainImageUrl', $event)" class="hidden"/>
          <img :src="mainImageUrl || fallbackImage"
               alt="Image principale"
               class=" max-w-full h-auto cursor-pointer"/>
        </label>

        <button v-if="isEditMode" @click="deleteImage('mainImageUrl')"
                class="absolute top-10 right-2 px-2 py-1 bg-red-500 text-white  hover:bg-red-600">
          X
        </button>
      </div>

      <v-textarea label="Description" variant="outlined" v-model="editableMainImageText"
                  class="w-full p-2 py-6 "></v-textarea>

    </div>

    <!--Main VideoUrl-->
    <div class="rounded-2xl"
         :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onSurface}">
      <!--Titre Video-->
      <div class="text-2xl pa-4">Vidéo Princpiale</div>
      <v-text-field
          label="Titre"
          variant="outlined"
          v-model="editableVideoSubtitleMain"
          class="w-full p-2 border rounded-md"></v-text-field>

      <!--urlvideo-->
      <v-text-field
          label="URL Video"
          variant="outlined"
          v-if="isEditMode"
          type="text"
          v-model="editableVideoUrlMain"
          class="w-full p-2 rounded-md"

      />


      <!-- Texte sous video principale -->
      <v-text-field
          label="Description"
          v-model="editableMainVideoText" class="w-full p-2  rounded-md h-24"
          variant="outlined"
      ></v-text-field>
    </div>

    <!--  4 images-->
    <div class="rounded-2xl"
         :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onSurface}">

      <div v-if="isEditMode">
        <div class="text-2xl pa-4">Galerie d'images</div>
        <v-text-field label="Titre" variant="outlined" v-model="editableImagesSubtitle" class="w-full p-2 rounded-md"></v-text-field>
      </div>

      <!--images-->
      <div class=" text-2xl pa-2
        ">Images
      </div>
      <div class="pa-2 grid grid-cols-1 gap-4 md:grid-cols-4">
        <!-- Première image -->
        <div class="relative">
          <label>
            <input type="file" @change="updateImage('image1Url', $event)" class="hidden"/>
            <img :src="image1Url || fallbackImage"
                 alt="Image 1"
                 class="rounded-md max-w-full h-auto cursor-pointer"/>
          </label>
          <button @click="deleteImage('image1Url')"
                  class="absolute top-2 right-2 px-2 py-1 bg-red-500 text-white hover:bg-red-600">
            X
          </button>
        </div>

        <!-- Deuxième image -->
        <div class="relative">
          <label>
            <input type="file" @change="updateImage('image2Url', $event)" class="hidden"/>
            <img :src="image2Url || fallbackImage"
                 alt="Image 2"
                 class="rounded-md max-w-full h-auto cursor-pointer"/>
          </label>
          <button @click="deleteImage('image2Url')"
                  class="absolute top-2 right-2 px-2 py-1 bg-red-500 text-white hover:bg-red-600">
            X
          </button>
        </div>

        <!-- Troisième image -->
        <div class="relative">
          <label>
            <input type="file" @change="updateImage('image3Url', $event)" class="hidden"/>
            <img :src="image3Url || fallbackImage"
                 alt="Image 3"
                 class="rounded-md max-w-full h-auto cursor-pointer"/>
          </label>
          <button @click="deleteImage('image3Url')"
                  class="absolute top-2 right-2 px-2 py-1 bg-red-500 text-white hover:bg-red-600">
            X
          </button>
        </div>

        <!-- Quatrième image -->
        <div class="relative">
          <label>
            <input type="file" @change="updateImage('image4Url', $event)" class="hidden"/>
            <img :src="image4Url || fallbackImage"
                 alt="Image 4"
                 class="rounded-md max-w-full h-auto cursor-pointer"/>
          </label>
          <button @click="deleteImage('image4Url')"
                  class="absolute top-2 right-2 px-2 py-1 bg-red-500 text-white hover:bg-red-600">
            X
          </button>
        </div>
      </div>

      <!-- Description-->
      <div class="text-2xl pa-2"> Description</div>
      <v-textarea variant="outlined" v-model="editableImagesText" class="w-full p-2 border rounded-md"></v-textarea>

    </div>

    <!-- Second Video -->
    <div class="rounded-2xl"
         :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onSurface }">
      <div class="text-2xl pa-4">Vidéo Secondaire</div>

      <v-text-field
          label="Titre"
          variant="outlined"
          v-model="editableVideoSubtitle"
          class="w-full p-2"
      ></v-text-field>

      <v-text-field
          label="URL Vidéo"
          variant="outlined"
          v-if="isEditMode"
          v-model="editableVideoUrl"
          class="w-full p-2"
      ></v-text-field>

      <v-textarea
          label="Description"
          variant="outlined"
          v-model="editableVideoText"
          class="w-full p-2 py-6"
      ></v-textarea>
    </div>

    <!-- Informations de Contact -->
    <div class="rounded-2xl"
         :style="{ backgroundColor: brandingStore.colors.primary, color: brandingStore.colors.onSurface }">
      <div class="text-2xl pa-4">Informations de Contact</div>

      <v-text-field
          label="Numéro de Téléphone"
          variant="outlined"
          v-model="editablePhoneNumber"
          class="w-full p-2"
      ></v-text-field>

      <v-text-field
          label="Adresse Email"
          variant="outlined"
          v-model="editableEmail"
          class="w-full p-2"
      ></v-text-field>
    </div>
  </div>


</template>

<script setup>
import {ref, onMounted} from "vue";
import {useClient} from "@/plugins/api.js";
import {useBrandingStore} from "@/stores/brandingStore.js";
import {useCreatorProfileStore} from "@/stores/creatorProfileStore.js";
import {useDisplay} from "vuetify";
import {watch} from "vue";
import FullscreenImage from "@/views/creators/FullscreenImage.vue";

const {smAndDown} = useDisplay();
const isMobileView = ref(smAndDown.value);


const creatorProfileStore = useCreatorProfileStore();
const brandingStore = useBrandingStore();
const client = useClient();

const isLoading = ref(true);
const isLoggedIn = true;
const isEditMode = ref(false);


const currentImage = ref("");
const fullscreenImage = ref(null);

function openFullscreen(imageUrl) {
  currentImage.value = imageUrl;
  fullscreenImage.value.open();
}

watch(smAndDown, (newVal) => {
  isMobileView.value = newVal;
});

// Image de fallback pour l'éditeur
const fallbackImage = "https://via.placeholder.com/300?text=Image+non+disponible";

// Variables réactives pour les données
const editablePhoneNumber = ref("");
const editableEmail = ref("");
const mainTitle = ref("");
const mainImageUrl = ref("");
const mainImageText = ref("");
const mainVideoText = ref("");
const imagesSubtitle = ref("");
const image1Url = ref("");
const image2Url = ref("");
const image3Url = ref("");
const image4Url = ref("");
const imagesText = ref("");
const videoSubtitle = ref("");
const videoSubtitleMain = ref("");
const videoUrlMain = ref("");
const videoUrl = ref("");
const videoText = ref("");
const phoneNumber = ref("");
const email = ref("");


const editableImages = ref([null, null, null, null]);


// Editable fields
const editableMainTitle = ref("");
const editableMainImageText = ref("");
const editableMainVideoText = ref("");
const editableImagesSubtitle = ref("");
const editableImagesText = ref("");
const editableVideoSubtitle = ref("");
const editableVideoSubtitleMain = ref("");
const editableVideoText = ref("");
const editableVideoUrlMain = ref("");
const editableVideoUrl = ref("");

// Activer/désactiver le mode édition
function toggleEditMode() {
  isEditMode.value = !isEditMode.value;
  if (isEditMode.value) {
    // Charger les valeurs pour l'édition
    editableMainTitle.value = mainTitle.value;
    editableMainImageText.value = mainImageText.value;
    editableMainVideoText.value = mainVideoText.value;
    editableImagesSubtitle.value = imagesSubtitle.value;
    editableImagesText.value = imagesText.value;
    editableVideoSubtitle.value = videoSubtitle.value;
    editableVideoSubtitleMain.value = videoSubtitleMain.value;
    editableVideoText.value = videoText.value;
    editableVideoUrlMain.value = videoUrlMain.value;
    editableVideoUrl.value = videoUrl.value;
    editablePhoneNumber.value = phoneNumber.value;
    editableEmail.value = email.value;
  } else {
    // Sauvegarder les modifications ou réinitialiser les URLs des images supprimées
    mainTitle.value = editableMainTitle.value;
    mainImageText.value = editableMainImageText.value;
    mainVideoText.value = editableMainVideoText.value;
    imagesSubtitle.value = editableImagesSubtitle.value;
    imagesText.value = editableImagesText.value;
    videoSubtitle.value = editableVideoSubtitle.value;
    videoSubtitleMain.value = editableVideoSubtitleMain.value;
    videoText.value = editableVideoText.value;
    videoUrlMain.value = editableVideoUrlMain.value;
    videoUrl.value = editableVideoUrl.value;
    phoneNumber.value = editablePhoneNumber.value;
    email.value = editableEmail.value;

    // Réinitialisation des images supprimées à des strings vides si nécessaire
    if (mainImageUrl.value === null) mainImageUrl.value = "";
    if (image1Url.value === null) image1Url.value = "";
    if (image2Url.value === null) image2Url.value = "";
    if (image3Url.value === null) image3Url.value = "";
    if (image4Url.value === null) image4Url.value = "";
  }
}


// Supprimer une image
function deleteImage(field) {
  switch (field) {
    case "mainImageUrl":
      mainImageUrl.value = ""; // Remplace par un string vide
      break;
    case "image1Url":
      image1Url.value = ""; // Remplace par un string vide
      break;
    case "image2Url":
      image2Url.value = ""; // Remplace par un string vide
      break;
    case "image3Url":
      image3Url.value = ""; // Remplace par un string vide
      break;
    case "image4Url":
      image4Url.value = ""; // Remplace par un string vide
      break;
  }
}


// Mettre à jour une image
function updateImage(field, event) {
  const file = event.target.files[0];
  if (file) {
    // Stocker le fichier dans editableImages pour l'envoi
    switch (field) {
      case "mainImageUrl":
        editableImages.value[0] = file;
        mainImageUrl.value = URL.createObjectURL(file);
        break;
      case "image1Url":
        editableImages.value[1] = file;
        image1Url.value = URL.createObjectURL(file);
        break;
      case "image2Url":
        editableImages.value[2] = file;
        image2Url.value = URL.createObjectURL(file);
        break;
      case "image3Url":
        editableImages.value[3] = file;
        image3Url.value = URL.createObjectURL(file);
        break;
      case "image4Url":
        editableImages.value[4] = file;
        image4Url.value = URL.createObjectURL(file);
        break;
    }
  }
}


// Charger les données au montage
onMounted(() => {
  mainTitle.value = brandingStore.presentationInfos.title;
  mainImageUrl.value = brandingStore.presentationInfos.mainImageUrl;
  mainImageText.value = brandingStore.presentationInfos.mainImageText;
  mainVideoText.value = brandingStore.presentationInfos.mainVideoText;
  imagesSubtitle.value = brandingStore.presentationInfos.imagesSubtitle;
  image1Url.value = brandingStore.presentationInfos.image1Url;
  image2Url.value = brandingStore.presentationInfos.image2Url;
  image3Url.value = brandingStore.presentationInfos.image3Url;
  image4Url.value = brandingStore.presentationInfos.image4Url;
  imagesText.value = brandingStore.presentationInfos.imagesText;
  videoSubtitle.value = brandingStore.presentationInfos.videoSubtitle;
  videoSubtitleMain.value = brandingStore.presentationInfos.videoSubtitleMain;
  videoUrl.value = brandingStore.presentationInfos.videoUrl;
  videoUrlMain.value = brandingStore.presentationInfos.videoUrlMain;
  videoText.value = brandingStore.presentationInfos.videoText;
  editablePhoneNumber.value = brandingStore.presentationInfos.phoneNumber;
  editableEmail.value = brandingStore.presentationInfos.email;
  phoneNumber.value = brandingStore.presentationInfos.phoneNumber;
  email.value = brandingStore.presentationInfos.email;
});

async function saveChanges() {
  if (!creatorProfileStore.creator.id) {
    console.error("L'ID du créateur est manquant !");
    return;
  }

  const formData = new FormData();

  // Ajout des champs textuels
  formData.append("PhoneNumber", editablePhoneNumber.value || "");
  formData.append("Email", editableEmail.value || "");
  formData.append("Title", editableMainTitle.value || "");
  formData.append("MainImageText", editableMainImageText.value || "");
  formData.append("MainVideoText", editableMainVideoText.value || "");
  formData.append("ImagesSubtitle", editableImagesSubtitle.value || "");
  formData.append("ImagesText", editableImagesText.value || "");
  formData.append("VideoSubtitle", editableVideoSubtitle.value || "");
  formData.append("VideoSubtitleMain", editableVideoSubtitleMain.value || "");
  formData.append("VideoUrlMain", editableVideoUrlMain.value || "");
  formData.append("VideoUrl", editableVideoUrl.value || "");
  formData.append("VideoText", editableVideoText.value || "");

  // Ajout des URLs d'images supprimées
  formData.append("MainImageUrl", mainImageUrl.value || ""); // Peut contenir un string vide
  formData.append("Image1Url", image1Url.value || "");
  formData.append("Image2Url", image2Url.value || "");
  formData.append("Image3Url", image3Url.value || "");
  formData.append("Image4Url", image4Url.value || "");

  // Ajout des fichiers d'images téléversées
  if (editableImages.value[0]) formData.append("MainImage", editableImages.value[0]);
  if (editableImages.value[1]) formData.append("Image1", editableImages.value[1]);
  if (editableImages.value[2]) formData.append("Image2", editableImages.value[2]);
  if (editableImages.value[3]) formData.append("Image3", editableImages.value[3]);
  if (editableImages.value[4]) formData.append("Image4", editableImages.value[4]);

  try {
    // Désactiver le bouton de sauvegarde pour éviter les clics multiples
    isLoading.value = true;

    // Envoyer les données au backend
    const response = await client.post(
        `/api/creators/${creatorProfileStore.creator.id}/presentation-infos`,
        formData,
        {headers: {"Content-Type": "multipart/form-data"}}
    );

    // Mettre à jour les valeurs locales pour refléter les changements
    mainTitle.value = editableMainTitle.value;
    mainImageText.value = editableMainImageText.value;
    mainVideoText.value = editableMainVideoText.value;
    imagesSubtitle.value = editableImagesSubtitle.value;
    imagesText.value = editableImagesText.value;
    videoSubtitle.value = editableVideoSubtitle.value;
    videoSubtitleMain.value = editableVideoSubtitleMain.value;
    videoText.value = editableVideoText.value;
    videoUrlMain.value = editableVideoUrlMain.value;
    videoUrl.value = editableVideoUrl.value;
    phoneNumber.value = editablePhoneNumber.value;
    email.value = editableEmail.value;

    console.log("Données sauvegardées :", response.data);

    // Réinitialiser le mode édition
    isEditMode.value = false;

    // Rafraîchir après une légère pause pour s'assurer des mises à jour visuelles

  } catch (error) {
    console.error("Erreur lors de la sauvegarde :", error);
  } finally {
    // Réactiver les interactions
    isLoading.value = false;
  }
}


function cancelEdit() {
  // Restaurer les valeurs d'origine
  editableMainTitle.value = mainTitle.value;
  editableMainImageText.value = mainImageText.value;
  editableMainVideoText.value = mainVideoText.value;
  editableImagesSubtitle.value = imagesSubtitle.value;
  editableImagesText.value = imagesText.value;
  editableVideoSubtitle.value = videoSubtitle.value;
  editableVideoSubtitleMain.value = videoSubtitleMain.value;
  editableVideoText.value = videoText.value;
  editableVideoUrlMain.value = videoUrlMain.value;
  editableVideoUrl.value = videoUrl.value;
  editablePhoneNumber.value = phoneNumber.value;
  editableEmail.value = email.value;

  // Désactiver le mode édition
  isEditMode.value = false;
}

</script>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* Ratio 16:9 (9/16 = 0.5625) */
}

.video-frame {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
  border-radius: 0.5rem; /* Pour les bords arrondis */
}
</style>
