<template>
  <component :is="Default || 'div'">
  <div class="container my-10 mx-auto ">

    <div
      class="flex items-end justify-between gap-4 mb-6 bg-(--second-light) dark:bg-(--main-dark) border border-(--border-light) dark:border-(--border-dark) p-4 rounded-md">
      <div class="flex items-end gap-3">
        <USelect v-model="selectedLanguage" :items="availableLangs" variant="outline" class="w-40!" valueKey="iso_code">
          <template #default="{ modelValue }">
            <div class="flex items-center gap-2">
              <span class="text-md">{{availableLangs.find(x => x.iso_code == modelValue)?.flag}}</span>
              <span class="font-medium dark:text-white text-black">{{availableLangs.find(x => x.iso_code ==
                modelValue)?.name}}</span>
            </div>
          </template>
          <template #item-leading="{ item }">
            <div class="flex items-center rounded-md cursor-pointer transition-colors">
              <span class="text-md">{{ item.flag }}</span>
              <span class="ml-2 dark:text-white text-black font-medium">{{ item.name }}</span>
            </div>
          </template>
        </USelect>
      </div>
      <UButton @click="translateToSelectedLanguage" color="primary" :loading="translating"
        class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) px-12!">
        Translate
      </UButton>
    </div>

    <div v-if="translating" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div class="flex flex-col items-center gap-4 p-8 bg-(--main-light) dark:bg-(--main-dark) rounded-lg shadow-xl">
        <UIcon name="svg-spinners:ring-resize" class="text-4xl text-primary" />
        <p class="text-lg font-medium dark:text-white text-black">Translating...</p>
      </div>
    </div>

    <div v-if="productStore.loading" class="flex items-center justify-center py-20">
      <UIcon name="svg-spinners:ring-resize" class="text-4xl text-primary" />
    </div>
    <div v-else-if="productStore.error" class="flex items-center justify-center py-20">
      <p class="text-red-500">{{ productStore.error }}</p>
    </div>
    <div v-else-if="productStore.productDescription" class="flex items-start gap-30">
      <div class="w-80 h-80 bg-(--second-light) dark:bg-gray-700 rounded-lg flex items-center justify-center">
        <span class="text-gray-500 dark:text-gray-400">Product Image</span>
      </div>
      <div class="flex flex-col gap-2">
        <p class="text-[25px] font-bold text-black dark:text-white">
          {{ productStore.productDescription.name || 'Product Name' }}
        </p>
        <p v-html="productStore.productDescription.description_short" class="text-black dark:text-white"></p>
        <div class="space-y-[10px]">
          <div class="flex items-center gap-1">
            <UIcon name="lets-icons:done-ring-round-fill" class="text-[20px] text-green-600" />
            <p class="text-[16px] font-bold text-(--accent-blue-light) dark:text-(--accent-blue-dark)">
              {{ productStore.productDescription.available_now }}
            </p>
          </div>
          <div class="flex items-center gap-1">
            <UIcon name="marketeq:car-shipping" class="text-[25px] text-green-600" />
            <p class="text-[18px] font-bold text-black dark:text-white">
              {{ productStore.productDescription.delivery_in_stock || 'Delivery information' }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <div v-if="productStore.productDescription" class="mt-16">
      <div class="flex gap-4 my-6">
        <UButton @click="activeTab = 'description'"
          :class="['cursor-pointer', activeTab === 'description' ? 'bg-blue-500 text-white' : '']" color="neutral"
          variant="outline">
          <p class="dark:text-white">Description</p>
        </UButton>

        <UButton @click="activeTab = 'usage'"
          :class="['cursor-pointer', activeTab === 'usage' ? 'bg-blue-500 text-white' : '']" color="neutral"
          variant="outline">
          <p class="dark:text-white">Usage</p>
        </UButton>
      </div>

      <div v-if="activeTab === 'usage'"
        class="px-8 py-4 border border-(--border-light) dark:border-(--border-dark) rounded-md bg-(--second-light) dark:bg-(--main-dark)">

        <div class="flex justify-end items-center gap-3 mb-4">
          <UButton v-if="!isEditing" @click="enableEdit"
            class="flex items-center gap-2 m-2 cursor-pointer bg-(--accent-blue-light)! dark:bg-(--accent-blue-dark)!">
            <p class="text-white">Change Text</p>
            <UIcon name="material-symbols-light:stylus-note-sharp" class="text-[30px] text-white!" />
          </UButton>
          <UButton v-if="isEditing" @click="saveText" color="neutral" variant="outline" class="p-2.5 cursor-pointer">
            <p class="dark:text-white text-black">Save the edited text</p>
          </UButton>
          <UButton v-if="isEditing" @click="cancelEdit" color="neutral" variant="outline" class="p-2.5 cursor-pointer">
            Cancel
          </UButton>
        </div>
        <p ref="usageRef" v-html="productStore.productDescription.usage"
          class="flex flex-col justify-center w-full text-start dark:text-white! text-black!"></p>

      </div>

      <div v-if="activeTab === 'description'"
        class="px-8 py-4 border border-(--border-light) dark:border-(--border-dark) rounded-md bg-(--second-light) dark:bg-(--main-dark)">
        <div class="flex items-center justify-end gap-3 mb-4">
          <UButton v-if="!descriptionEdit.isEditing.value" @click="enableDescriptionEdit"
            class="flex items-center gap-2 m-2 cursor-pointer bg-(--accent-blue-light)! dark:bg-(--accent-blue-dark)!">
            <p class="text-white">Change Text</p>
            <UIcon name="material-symbols-light:stylus-note-sharp" class="text-[30px] text-white!" />
          </UButton>
          <UButton v-if="descriptionEdit.isEditing.value" @click="saveDescription" color="neutral" variant="outline" class="p-2.5 cursor-pointer">
            <p class="dark:text-white text-black ">Save the edited text</p>
          </UButton>
          <UButton v-if="descriptionEdit.isEditing.value" @click="cancelDescriptionEdit" color="neutral" variant="outline" class="p-2.5 cursor-pointer">Cancel</UButton>
        </div>
        <div ref="descriptionRef" v-html="productStore.productDescription.description"
          class="flex flex-col justify-center dark:text-white text-black">
        </div>
      </div>
    </div>
  </div>
  </component>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useProductStore } from '@/stores/product'
import { useEditable } from '@/composable/useConteditable'
import { langs } from '@/router/langs'
import type { Language } from '@/types'
import Default from '@/layouts/default.vue'

const route = useRoute()
const activeTab = ref('description')
const productStore = useProductStore()
const translating = ref(false)

const isEditing = ref(false)

const availableLangs = computed(() => langs)

const selectedLanguage = ref('pl')

const currentLangId = ref(2)
const productID = ref<number>(0)

// Watch for language changes and refetch product description
watch(selectedLanguage, async (newLang: string) => {
  if (productID.value) {
    await fetchForLanguage(newLang)
  }
})

const fetchForLanguage = async (langCode: string) => {
  const lang = langs.find((l: Language) => l.iso_code === langCode)
  if (lang && productID.value) {
    await productStore.getProductDescription(lang.id, productID.value)
    currentLangId.value = lang.id
  }
}

const translateToSelectedLanguage = async () => {
  const targetLang = langs.find((l: Language) => l.iso_code === selectedLanguage.value)
  if (targetLang && currentLangId.value && productID.value) {
    translating.value = true
    try {
      await productStore.translateProductDescription(productID.value, currentLangId.value, targetLang.id)
      currentLangId.value = targetLang.id
    } finally {
      translating.value = false
    }
  }
}

onMounted(async () => {
  const id = route.params.id
  if (id) {
    productID.value = Number(id)
    await fetchForLanguage(selectedLanguage.value)
  }
})

const descriptionRef = ref<HTMLElement | null>(null)
const usageRef = ref<HTMLElement | null>(null)

const descriptionEdit = useEditable(descriptionRef)
const usageEdit = useEditable(usageRef)

const originalDescription = ref('')
const originalUsage = ref('')

const saveDescription = async () => {
  descriptionEdit.disableEdit()
  await productStore.saveProductDescription(productID.value)
}

const cancelDescriptionEdit = () => {
  if (descriptionRef.value) {
    descriptionRef.value.innerHTML = originalDescription.value
  }
  descriptionEdit.disableEdit()
}

const enableDescriptionEdit = () => {
  if (descriptionRef.value) {
    originalDescription.value = descriptionRef.value.innerHTML
  }
  descriptionEdit.enableEdit()
}

const enableEdit = () => {
  if (usageRef.value) {
    originalUsage.value = usageRef.value.innerHTML
  }
  isEditing.value = true
  usageEdit.enableEdit()
}

const saveText = () => {
  usageEdit.disableEdit()
  isEditing.value = false
  productStore.saveProductDescription(productID.value)
}

const cancelEdit = () => {
  if (usageRef.value) {
    usageRef.value.innerHTML = originalUsage.value
  }
  usageEdit.disableEdit()
  isEditing.value = false
}

</script>

<style>
.images {
  display: flex;
  align-items: center;
  gap: 70px;
  margin: 20px 0 20px 0;
}
</style>