<template>
  <component :is="Default || 'div'">
    <div class="flex items-center gap-2 mb-4">
      <UIcon name="line-md:arrow-left" class="text-(--text-sky-light) dark:text-(--text-sky-dark)" />
      <p class="cursor-pointer text-(--text-sky-light) dark:text-(--text-sky-dark)" @click="backFromProduct()">
        Back to products</p>
    </div>
    <div class="container mx-auto ">
      <div
        class="gap-4 mb-6 bg-slate-50 dark:bg-(--main-dark) border border-(--border-light) dark:border-(--border-dark) p-4 rounded-md">
        <div class="flex items-center justify-between">
          <div class="flex flex-col items-center gap-3" v-if="!isTranslations">
            <USelectMenu v-model="toLangId" :items="langs" value-key="id"
              class="w-48 bg-(--main-light) dark:bg-(--black) rounded-md shadow-sm" :searchInput="false">
              <template #default>
                <div class="flex flex-col items-start leading-tight">
                  <span class="text-xs text-gray-400">
                    Selected language
                  </span>
                  <span class="font-medium dark:text-white text-black">
                    {{langs.find(l => l.id === toLangId)?.name || 'Select language'}}
                  </span>
                </div>
              </template>

              <template #item-leading="{ item }">
                <div class="flex items-center gap-2 cursor-pointer">
                  <span class="text-lg">{{ item.flag }}</span>
                  <span class="font-medium dark:text-white text-black">
                    {{ item.name }}
                  </span>
                </div>
              </template>
            </USelectMenu>
          </div>

          <div v-if="toLangId !== settingStore.shopDefaultLanguage && !isTranslations" class="flex gap-7">
            <UButton @click="translateToSelectedLanguage" color="info" :loading="translating">
              Translate from Polish to {{langs.find(l => l.id === toLangId)?.name}}
            </UButton>
          </div>
          <div v-if="isTranslations" class="flex gap-3 w-full justify-end">
            <UButton @click="() => {
              toLangId = settingStore.shopDefaultLanguage
              isTranslations = false
            }" color="info" variant="outline">
              Cancel and back to Polish
            </UButton>
            <UButton color="info" @click="productStore.saveProductDescription(productID, toLangId)">
              Save translations
            </UButton>
          </div>


          <!-- <div class="flex gap-7">
            <div v-if="isTranslations === false">
              <UButton @click="() => {
                fetchForLanguage(toLangId)
                isShowProductView = true
              }" class="text-(--accent-blue-light) dark:text-(--accent-blue-dark)"
                color="neutral" variant="outline">
                <p class="dark:text-white"> Show product</p>
              </UButton>
              <UButton @click="translateToSelectedLanguage" color="primary" :loading="translating"
                class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark) flex items-center! justify-center! px-12">
                Translate
              </UButton>
            </div>
            <div v-else class="flex gap-3">
              <UButton @click="() => {
                toLangId = settingStore.shopDefaultLanguage
                isTranslations = false
              }" color="primary" class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark)">
                Cancel
              </UButton>
              <UButton color="primary" @click="productStore.saveProductDescription(productID, toLangId)"
                class="text-white bg-(--accent-blue-light) dark:bg-(--accent-blue-dark)">
                Save
              </UButton>
            </div>
          </div> -->
        </div>
      </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="">
        <div 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] light:text-(--accent-green-light) dark:text-(--accent-green-dark)" />
                <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] light:text-(--accent-green-light) dark:text-(--accent-green-dark)" />
                <p class="text-[18px] font-bold text-black dark:text-white">
                  {{ productStore.productDescription.delivery_in_stock || 'Delivery information' }}
                </p>
              </div>
            </div>
          </div>
        </div>

        <UTabs :items="items" v-model="activeTab" color="info" :content="true" :ui="{
          list : 'w-auto!'
        }">
          <template #description>
            <div v-if="!isTranslations" class="flex justify-end items-center gap-3 mb-4">
              <UButton v-if="!isEditing" @click="activeTab === 'usage' ? enableEdit() : 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="isEditing" @click="activeTab === 'usage' ? saveText : 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="isEditing" @click="activeTab === 'usage' ? cancelEdit : cancelDescriptionEdit"
                color="neutral" variant="outline" class="p-2.5 cursor-pointer">
                Cancel
              </UButton>
            </div>
            <UEditor v-if="isTranslations" v-slot="{ editor }" v-model="productStore.productDescription.description"
              content-type="html" :ui="{ base: 'p-8 sm:px-16' }" class="w-full min-h-74" placeholder="Write there ...">
              <UEditorToolbar :editor="editor" :items="toolbarItems" class="sm:px-8">
                <template #link>
                  <EditorLinkPopover :editor="editor" auto-open />
                </template>
              </UEditorToolbar>
            </UEditor>
            <p v-else v-html="productStore.productDescription.description" class="text-black dark:text-white"></p>
          </template>

          <template #usage>
            <div class="px-7">
              <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>

              <UEditor v-if="isTranslations" v-slot="{ editor }" v-model="productStore.productDescription.usage"
                content-type="html" :ui="{ base: 'p-8 sm:px-16' }" class="w-full min-h-74" placeholder="Write there ...">
                <UEditorToolbar :editor="editor" :items="toolbarItems" class="sm:px-8">
                  <template #link>
                    <EditorLinkPopover :editor="editor" auto-open />
                  </template>
                </UEditorToolbar>
              </UEditor>
              <p v-else v-html="productStore.productDescription.usage" class="text-black dark:text-white"></p>
            </div>
          </template>
        </UTabs>
      </div>
    </div>
  </component>
</template>

<script setup lang="ts">
import { useEditable } from '@/composable/useConteditable';
import Default from '@/layouts/default.vue';
import { langs } from '@/router/langs';
import { useProductStore } from '@/stores/product';
import { useSettingsStore } from '@/stores/settings';
import type { EditorToolbarItem } from '@nuxt/ui';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const toolbarItems: EditorToolbarItem[][] = [
  // History controls
  [{
    kind: 'undo',
    icon: 'i-lucide-undo',
    tooltip: { text: 'Undo' }
  }, {
    kind: 'redo',
    icon: 'i-lucide-redo',
    tooltip: { text: 'Redo' }
  }],
  // Block types
  [{
    icon: 'i-lucide-heading',
    tooltip: { text: 'Headings' },
    content: {
      align: 'start'
    },
    items: [{
      kind: 'heading',
      level: 1,
      icon: 'i-lucide-heading-1',
      label: 'Heading 1'
    }, {
      kind: 'heading',
      level: 2,
      icon: 'i-lucide-heading-2',
      label: 'Heading 2'
    }, {
      kind: 'heading',
      level: 3,
      icon: 'i-lucide-heading-3',
      label: 'Heading 3'
    }, {
      kind: 'heading',
      level: 4,
      icon: 'i-lucide-heading-4',
      label: 'Heading 4'
    }]
  }, {
    icon: 'i-lucide-list',
    tooltip: { text: 'Lists' },
    content: {
      align: 'start'
    },
    items: [{
      kind: 'bulletList',
      icon: 'i-lucide-list',
      label: 'Bullet List'
    }, {
      kind: 'orderedList',
      icon: 'i-lucide-list-ordered',
      label: 'Ordered List'
    }]
  }, {
    kind: 'blockquote',
    icon: 'i-lucide-text-quote',
    tooltip: { text: 'Blockquote' }
  }, {
    kind: 'codeBlock',
    icon: 'i-lucide-square-code',
    tooltip: { text: 'Code Block' }
  }, {
    kind: 'horizontalRule',
    icon: 'i-lucide-separator-horizontal',
    tooltip: { text: 'Horizontal Rule' }
  }],
  // Text formatting
  [{
    kind: 'mark',
    mark: 'bold',
    icon: 'i-lucide-bold',
    tooltip: { text: 'Bold' }
  }, {
    kind: 'mark',
    mark: 'italic',
    icon: 'i-lucide-italic',
    tooltip: { text: 'Italic' }
  }, {
    kind: 'mark',
    mark: 'underline',
    icon: 'i-lucide-underline',
    tooltip: { text: 'Underline' }
  }, {
    kind: 'mark',
    mark: 'strike',
    icon: 'i-lucide-strikethrough',
    tooltip: { text: 'Strikethrough' }
  }, {
    kind: 'mark',
    mark: 'code',
    icon: 'i-lucide-code',
    tooltip: { text: 'Code' }
  }],
  // Link
  [{
    kind: 'link',
    icon: 'i-lucide-link',
    tooltip: { text: 'Link' }
  }],
  // Text alignment
  [{
    icon: 'i-lucide-align-justify',
    tooltip: { text: 'Text Align' },
    content: {
      align: 'end'
    },
    items: [{
      kind: 'textAlign',
      align: 'left',
      icon: 'i-lucide-align-left',
      label: 'Align Left'
    }, {
      kind: 'textAlign',
      align: 'center',
      icon: 'i-lucide-align-center',
      label: 'Align Center'
    }, {
      kind: 'textAlign',
      align: 'right',
      icon: 'i-lucide-align-right',
      label: 'Align Right'
    }, {
      kind: 'textAlign',
      align: 'justify',
      icon: 'i-lucide-align-justify',
      label: 'Align Justify'
    }]
  }]
]

const router = useRouter()
function backFromProduct() {
  let path = localStorage.getItem('back_from_product')

  if (path) {
    let res = JSON.parse(path)
    router.push({
      name: res.name,
      params: res.params,
      query: res.query
    })

    localStorage.removeItem('back_from_product')
  } else {
    router.push({
      name: 'customer-products',
    })
  }
}

const route = useRoute()
const settingStore = useSettingsStore()
const productStore = useProductStore()
const isTranslations = ref(false)

const toLangId = ref<number>(settingStore.shopDefaultLanguage)
const productID = ref<number>(0)
const translating = ref(false)

const activeTab = ref('description')
const usageRef = ref<HTMLElement | null>(null)
const originalUsage = ref('')
const isEditing = ref(false)
const usageEdit = useEditable(usageRef)
const descriptionRef = ref<HTMLElement | null>(null)
const descriptionEdit = useEditable(descriptionRef)
const originalDescription = ref('')

const translateToSelectedLanguage = async () => {
  if (toLangId.value && productID.value) {
    translating.value = true
    try {
      await productStore.translateProductDescription(productID.value, toLangId.value)
    } finally {
      translating.value = false
      enableEdit()
      enableDescriptionEdit()
    }
  }
  if (productStore.productDescription) {
    isTranslations.value = true
  }
}

const fetchForLanguage = async (langId: number | null) => {
  if (productID.value) {
    await productStore.getProductDescription(langId, productID.value)
    removeInlineStylesFromAll(productStore.productDescription)
  }
}

watch(toLangId, () => {
  fetchForLanguage(toLangId.value)
})

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

const items = ref([
  { label: 'Description', slot: 'description', name: 'description' },
  { label: 'Usage', slot: 'usage', name: 'usage' }
])

// text edit
const enableEdit = () => {
  console.log(usageRef.value, 'usageRef');

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

const enableDescriptionEdit = () => {
  console.log(usageRef.value, 'usageRef');

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

const saveText = () => {
  if (usageRef.value) {
    productStore.productDescription.usage = usageRef.value.innerHTML
  }

  usageEdit.disableEdit()
  isEditing.value = false

  productStore.saveProductDescription(productID.value, toLangId.value)
}

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

const saveDescription = async () => {
  if (descriptionRef.value) {
    productStore.productDescription.description = descriptionRef.value.innerHTML
  }

  descriptionEdit.disableEdit()

  await productStore.saveProductDescription(productID.value, toLangId.value)
  toLangId.value = settingStore.shopDefaultLanguage
  isTranslations.value = false
}

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

function removeInlineStylesFromAll(product) {
  if (!product) return
  const removeStyles = (html: string) => {
    if (!html) return ''
    const div = document.createElement('div')
    div.innerHTML = html

    div.querySelectorAll('*').forEach(el => {
      const bg = el.style.background || el.style.backgroundColor
      if (bg) {
        el.style.background = ''
        el.style.backgroundColor = ''
      }
    })
    div.querySelectorAll('p').forEach(p => {
      if (p.querySelector('img')) {
        p.style.display = 'flex'
        p.style.gap = '20px'
        p.style.padding = '30px 0'
      }
    })
    div.querySelectorAll('table').forEach(table => {
      table.querySelectorAll('tbody').forEach(tbody => {
        tbody.style.setProperty('background-color', '#F8FAFC', 'important')
        tbody.querySelectorAll('tr').forEach(tr => {
          tr.querySelectorAll('td').forEach(td => {
            td.style.setProperty('padding', '10px', 'important')
            td.style.setProperty('border-top', '1pt solid black', 'important')
            td.style.setProperty('border-left', '1pt solid black', 'important')
            td.style.setProperty('border-bottom', '1pt solid black', 'important')
            td.style.setProperty('border-right', '1pt solid black', 'important')

            td.querySelectorAll('p').forEach(p => {
              p.style.setProperty('display', 'flex', 'important')
              p.style.setProperty('padding', '0px', 'important')
              p.style.setProperty('align-items', 'start', 'important')
              p.style.setProperty('color', 'black', 'important')
              p.style.setProperty('font-size', '14px', 'important')
              p.querySelectorAll('span').forEach(span => {
                span.style.setProperty('color', 'black', 'important')
                span.style.setProperty('font-size', '14px', 'important')
              })
            })
          })
        })
      })
    })
    return div.innerHTML
  }
  product.description = removeStyles(product.description)
  product.description_short = removeStyles(product.description_short)
  product.usage = removeStyles(product.usage)
}
</script>
