<script setup>
import { string, date } from 'alga-js'
import { AttachBox } from 'tedir-dropzone'
import { toast } from 'bulma-toast'

const config = useRuntimeConfig()
const user = useCookie('logship_user')

const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')

// Use a computed property that will be reactive
const isFulCustomer = computed(() => getMenuType())


const props = defineProps({
  modelValue: Boolean,
  target: String,
  info: Object,
  shipperId: [String, Number],
  attachmentTrackingnumber: String
})

const emit = defineEmits(['update:modelValue', 'trackingNumberSaved', 'saved'])

const entries = ref([])
const form = ref({
  id: props.info?.id || '',
  uid: props.info?.uid || '',
  organizationId: props.info?.organizationId || '',
  attachments: [],
  strapiAttachmentId: '',
  strapiAttachmentDocumentId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

// Tracking number modal state
const showTrackingNumberModal = ref(false)
const trackingNumberInputs = ref(['']) // Array for multiple tracking numbers
const pendingFiles = ref([])
const isCheckingShipper = ref(false)

// Add a new tracking number input field
const addTrackingNumberField = () => {
  trackingNumberInputs.value.push('')
}

// Remove a tracking number input field
const removeTrackingNumberField = (index) => {
  if (trackingNumberInputs.value.length > 1) {
    trackingNumberInputs.value.splice(index, 1)
  }
}

// Get language for translations
const userLang = useCookie('lang')
const currentLang = computed(() => userLang.value || 'en-US')

const trackingNumberLabel = computed(() => {
  return currentLang.value === 'de-DE'
    ? 'Bitte geben Sie die Sendungsverfolgungsnummer ein'
    : 'Please enter Trackingnumber'
})

// Check if shipper requires tracking number
const checkShipperRequiresTracking = async () => {
  if (!props.shipperId) return false

  try {
    const res = await $fetch(`/api/materials/shippers/${props.shipperId}`, {
      headers: useRequestHeaders(['cookie'])
    })
    return res?.isPickupTrackingNumberMandatory === true
  } catch (error) {
    console.error('Failed to check shipper settings:', error)
    return false
  }
}

// Save tracking number to order
const saveTrackingNumber = async (trackingNumber) => {
  if (!props.info?.id || !trackingNumber) return false

  try {
    const res = await $fetch('/api/orders/update', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: props.info.id,
        attachmentTrackingnumber: trackingNumber
      }
    })
    if (res?.status === 200) {
      emit('trackingNumberSaved', trackingNumber)
      return true
    }
    return false
  } catch (error) {
    console.error('Failed to save tracking number:', error)
    return false
  }
}

// Handle tracking number submission
const submitTrackingNumber = async () => {
  // Filter out empty entries and trim whitespace
  const validTrackingNumbers = trackingNumberInputs.value
    .map(t => t.trim())
    .filter(t => t.length > 0)

  if (validTrackingNumbers.length === 0) {
    toast({
      message: currentLang.value === 'de-DE'
        ? 'Sendungsverfolgungsnummer ist erforderlich'
        : 'Tracking number is required',
      type: 'is-danger',
      duration: 2000
    })
    return
  }

  // Join multiple tracking numbers with comma
  const trackingNumbersString = validTrackingNumbers.join(',')

  const saved = await saveTrackingNumber(trackingNumbersString)
  if (saved) {
    showTrackingNumberModal.value = false
    // Now proceed with the file upload
    await processFileUpload(pendingFiles.value)
    pendingFiles.value = []
    trackingNumberInputs.value = [''] // Reset to single empty input
  } else {
    toast({
      message: currentLang.value === 'de-DE'
        ? 'Fehler beim Speichern der Sendungsverfolgungsnummer'
        : 'Failed to save tracking number',
      type: 'is-danger',
      duration: 2000
    })
  }
}

// Cancel tracking number input
const cancelTrackingNumber = () => {
  showTrackingNumberModal.value = false
  pendingFiles.value = []
  trackingNumberInputs.value = [''] // Reset to single empty input
}

const strapiConnection = async () => {
  if(!form.value.strapiAttachmentId && form.value.id) {
    const getAttachmentRecord = await $fetch(`/api/attachments/${props.target}/${form.value.id}`)
    if(getAttachmentRecord?.Strapi_Attachment_ID && getAttachmentRecord?.Strapi_Attachment_documentId) {
      form.value.strapiAttachmentId = getAttachmentRecord.Strapi_Attachment_ID
      form.value.strapiAttachmentDocumentId = getAttachmentRecord.Strapi_Attachment_documentId
    } else {
      const resAttachmentRecord = await $fetch(`/api/attachments/${props.target}/${form.value.id}`, {
        method: 'POST',
        headers: useRequestHeaders(['cookie']),
        body: {
          uid: form.value.uid,
          organizationId: form.value.organizationId,
          data: 'TG9nc2hpcCBBdHRhY2htZW50IEV4YW1wbGU='
        }
      })
      if(resAttachmentRecord?.Strapi_Attachment_ID && resAttachmentRecord?.Strapi_Attachment_documentId) {
        form.value.strapiAttachmentId = resAttachmentRecord.Strapi_Attachment_ID
        form.value.strapiAttachmentDocumentId = resAttachmentRecord.Strapi_Attachment_documentId
      }
    }
  }
}

const retrieve = async () => {
  entries.value = []
  await strapiConnection()

  if(form.value.strapiAttachmentDocumentId) {
    const res = await $fetch(`/api/attachments/${props.target}/${form.value.strapiAttachmentDocumentId}/files`, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res
    }
  }
}
onMounted(async () => {
  await retrieve()
  defaultSideBarMenu.value = getMenuType()

})

watch(() => props.info, () => {
  form.value.id = props.info?.id || ''
  form.value.uid = props.info?.uid || ''
  form.value.organizationId = props.info?.organizationId || ''
  retrieve()
})

const showAttachmentModal = ref(props.modelValue || false)
const showAttachmentViewer = ref(false)
const showAttachmentViewerData = ref({})
const closeAttachmentModal = () => {
  showAttachmentModal.value = false
  showAttachmentViewer.value = false
  emit('update:modelValue', false)
}
const viewAttachmentViewer = (fileData) => {
  showAttachmentViewer.value = true
  showAttachmentViewerData.value = fileData
  console.log(showAttachmentViewerData.value)
}
watch(() => props.modelValue, () => {
  showAttachmentModal.value = props.modelValue
  retrieve()
})

/*const onlyBase64Code = (val) => {
  const base64Val = val.split(',')[1]
  if(base64Val) {
    form.value.image = base64Val
  }
}*/

const progressPercentage = ref({})
const progressSize = ref({})
const progressTimer = ref(undefined)

// Process the actual file upload
const processFileUpload = async (files) => {
  form.value.attachments = []
  await strapiConnection()

  if(form.value.strapiAttachmentId) {
    files.forEach(async (file, index) => {
      const formData = new FormData()
      formData.append('field', 'attachment')
      formData.append('ref', 'api::ad-attachment.ad-attachment')
      formData.append('refId', form.value.strapiAttachmentId)
      formData.append(`files`, file)
      formData.append('fileInfo', JSON.stringify({
        caption: String(form.value.id),
        alternativeText: String(form.value.uid),
      }))

      clearTimeout(progressTimer.value)
      const uniqId = string.uniqid()
      entries.value.push({
        id: uniqId,
        name: file.name,
        hash: file.name,
        ext: '',
        isProgress: true
      })
      progressPercentage.value[file.name] = 0
      progressSize.value[file.name] = (file.size / 1048576).toFixed(2)

      const progressInterval = setInterval(() => {
        if(progressPercentage.value[file.name] < 95) {
          progressPercentage.value[file.name] += Math.floor((Math.random() * 4) + 4)
        }
      }, 1000)

      const res = await fetch(config.public.strapi+'/media-api/upload', {
        method: 'POST',
        headers: {
          Authorization: 'Bearer '+config.public.strapitoken
        },
        body: formData
      })
      if(res) {
        progressTimer.value = setTimeout(() => {
          progressPercentage.value[file.name] = 100
          clearInterval(progressInterval)
          retrieve()
          emit('saved', { name: file.name })
        }, 1000)
      }
    })
  }
}

// Handler that checks for tracking number requirement before upload
const handler = async (files) => {
  // Only check for C_Order target
  if (props.target === 'C_Order' && props.shipperId && !props.attachmentTrackingnumber) {
    isCheckingShipper.value = true
    const requiresTracking = await checkShipperRequiresTracking()
    isCheckingShipper.value = false

    if (requiresTracking) {
      // Show tracking number modal and store files for later
      pendingFiles.value = files
      showTrackingNumberModal.value = true
      return
    }
  }

  // No tracking number required, proceed with upload
  await processFileUpload(files)
  /*for(let file of files) {
    const reader = new FileReader();
    reader.onload = async (evt) => {
      //console.log(evt.target.result);
      const base64Val = file.base64.split(';base64,')[1]
      if(base64Val) {
        await $fetch(`/api/attachments/${props.target}/${form.value.id}`, {
          method: 'POST',
          headers: useRequestHeaders(['cookie']),
          body: {
            name: file.name,
            data: base64Val
          }
        })
        entries.value.push({name: file.name})
      }
    }
    reader.readAsDataURL(file)
  }*/
}

const destroy = async (entry, index) => {
  //entries.value.splice(index, 1)

  if(entry.id) {
    const res = await $fetch(`/api/attachments/${props.target}/${entry.id}`, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const serverSidePrinting = async (content, type) => {
  let newUrl = '/api/print/'
  if(type === 'label') {
    newUrl = '/api/print/attachment-labels'
  }
  const res = await $fetch(newUrl, {
    method: 'POST',
    body: content
  })
  if(res) {
    //console.log(res)
    if(res?.stdout) {
      toast({
        message: `The attachment has been printed via server side printing!`,
        type: 'is-success',
        duration: 2000
      })
    }
  }
}

const printInLabelSize = async (attachment) => {
  //console.log(attachment)
  const response = await fetch(config.public.strapi+'/files-api/'+attachment.hash + attachment.ext);
  if(response) {
    const blob = await response.blob();
    //const urlb = URL.createObjectURL(blob)
    const reader = new FileReader();
    reader.onloadend = () => {
      serverSidePrinting({
        pathName: `attachments/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+attachment.documentId+'-')}-ATTACHMENTS-${user.value?.Name || 'SUPERUSER'}.pdf`,
        fileContent: reader.result.split(',')[1]
      }, 'label')
    }
    reader.onerror = (e) => {
      console.log(reader.error)
    }
    reader.readAsDataURL(blob);
  }
}

const printInNormalSize = async (attachment) => {
  //console.log(attachment)
  const response = await fetch(config.public.strapi+'/files-api/'+attachment.hash + attachment.ext);
  if(response) {
    const blob = await response.blob();
    //const urlb = URL.createObjectURL(blob)
    const reader = new FileReader();
    reader.onloadend = () => {
      serverSidePrinting({
        pathName: `attachments/${new Date().getFullYear()}`,
        fileName: `${date.now().replace(/\-|\:/g, '_').replace(' ', '-'+attachment.documentId+'-')}-ATTACHMENTS-${user.value?.Name || 'SUPERUSER'}.pdf`,
        fileContent: reader.result.split(',')[1]
      }, 'normal')
    }
    reader.onerror = (e) => {
      console.log(reader.error)
    }
    reader.readAsDataURL(blob);
  }
}
</script>

<template>
  <div class="modal" :class="{'active': showAttachmentModal}" :style="{display: showAttachmentModal ? 'block' : 'none'}">
    <div class="modalDialog modalCenter" @click.self="closeAttachmentModal">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">Attachments</h3>
          <div class="cursor-pointer" @click="closeAttachmentModal">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="mb-3 mt-0"> <!--  v-if="info?.docStatusId !== 'CO'" -->
            <div class="d-flex gap-10px">
              <AttachBox v-model="form.attachments" :base64="true" :uniqid="true" @handler="handler">
                <button type="button" class="button pointerEvents-none">Upload Files</button>
              </AttachBox>
            </div>
          </div>
          <div class="tableResponsive">
            <table class="table tableList tableFlush">
              <thead>
                <tr>
                  <th>File Name</th>
                  <th>Size</th>
                  <th>Type</th>
<!--                  <th>Created</th>-->
                  <th class="w-100px">Action</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(entry, index) in entries" :key="index">
                  <td>{{ entry.name }}</td>
                  <td><span v-if="entry.size">{{ (entry.size / 1000).toFixed(2) || 0 }} MB</span></td>
                  <td>
                    <i v-if="entry.ext === '.jpg' || entry.ext === '.png' || entry.ext === '.jpeg' || entry.ext === '.webp'" class="menu-icon tf-icons ti ti-image"></i>
                    <i v-else-if="entry.ext === '.mpeg' || entry.ext === '.avi' || entry.ext === '.m4v' || entry.ext === '.mp4'" target="_blank" class="menu-icon tf-icons ti ti-video"></i>
                    <i v-else-if="entry.ext === '.pdf'" class="menu-icon tf-icons ti ti-pdf"></i>
                    <i v-else-if="entry.ext === '.webm' || entry.ext === '.wav' || entry.ext === '.mp3' || entry.ext === '.ogg' || entry.ext === '.m4a'" class="menu-icon tf-icons ti ti-volume"></i>
                  </td>
<!--                  <td>{{ entry?.createdAt }}</td>-->
                  <td>
                    <template v-if="entry.isProgress">
                      <UProgress :value="progressPercentage[entry.name]" />
                      <div>{{ progressSize[entry.name] || 0 }} MB</div>
                    </template>
                    <div v-else class="d-flex justify-flexEnd gap-5px">
                      <a :href="config.public.strapi+'/files-api/'+entry.hash + entry.ext" download target="_blank" class="cursor-pointer fg-info">
                        <i class="menu-icon tf-icons ti ti-download"></i>
                      </a>
                      <span v-if="defaultSideBarMenu !== 'c'" class="cursor-pointer fg-success" @click="printInLabelSize(entry)">
                        <i class="menu-icon tf-icons ti ti-script"></i>
                      </span>
                      <span v-if="defaultSideBarMenu !== 'c'" class="cursor-pointer fg-success" @click="printInNormalSize(entry)">
                        <i class="menu-icon tf-icons ti ti-printer"></i>
                      </span>
                      <span v-if="entry.id" @click="viewAttachmentViewer(entry)" class="cursor-pointer fg-danger">
<!--                   View Image in new Modal Popup-->
                       <i v-if="entry.ext === '.jpg' || entry.ext === '.png' || entry.ext === '.jpeg' || entry.ext === '.webp'" class="menu-icon tf-icons ti ti-eye"></i>
<!--                   Play Video in new Modal Popup-->
                       <i v-else-if="entry.ext === '.mpeg' || entry.ext === '.avi' || entry.ext === '.m4v' || entry.ext === '.mp4'" class="menu-icon tf-icons ti ti-eye"></i>
<!--                   View PDF in new Modal Popup-->
                       <i v-else-if="entry.ext === '.pdf'" class="menu-icon tf-icons ti ti-eye"></i>
<!--                   Play Audio in new Modal Popup-->
                       <i v-else-if="entry.ext === '.webm' || entry.ext === '.wav' || entry.ext === '.mp3' || entry.ext === '.ogg' || entry.ext === '.m4a'" class="menu-icon tf-icons ti ti-player-play"></i>
                      </span>
                      <span v-if="entry.id && defaultSideBarMenu !== 'c'" @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                        <i class="menu-icon tf-icons ti ti-trash"></i>
                      </span>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="retrieve">Refresh</button>
            <button type="button" class="button" @click="closeAttachmentModal">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <AttachmentViewer v-model="showAttachmentViewer" :type="showAttachmentViewerData?.mime ?? ''" :source="(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url) ? config.public.strapi+'/files-api/'+(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url).replace('/uploads/', '') : ''" :title="showAttachmentViewerData?.name ?? ''" :width="showAttachmentViewerData?.width ?? 1366" :height="showAttachmentViewerData?.height ?? 768" />

  <!-- Tracking Number Modal -->
  <div class="modal" :class="{'active': showTrackingNumberModal}" :style="{display: showTrackingNumberModal ? 'block' : 'none'}">
    <div class="modalDialog modalCenter" @click.self="cancelTrackingNumber">
      <div class="modalContent" style="max-width: 400px;">
        <div class="modalHeader">
          <h3 class="modalTitle">{{ currentLang === 'de-DE' ? 'Sendungsverfolgungsnummer' : 'Tracking Number' }}</h3>
          <div class="cursor-pointer" @click="cancelTrackingNumber">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="mb-3">
            <label class="form-label">{{ trackingNumberLabel }}</label>
            <div v-for="(trackingNum, index) in trackingNumberInputs" :key="index" class="d-flex gap-5px mb-2 align-items-center">
              <input
                v-model="trackingNumberInputs[index]"
                type="text"
                class="form-control"
                :placeholder="currentLang === 'de-DE' ? 'Sendungsverfolgungsnummer eingeben...' : 'Enter tracking number...'"
                @keyup.enter="submitTrackingNumber"
              />
              <button
                v-if="trackingNumberInputs.length > 1"
                type="button"
                class="button button-sm"
                @click="removeTrackingNumberField(index)"
                :title="currentLang === 'de-DE' ? 'Entfernen' : 'Remove'"
              >
                <span class="tf-icon ti ti-minus"></span>
              </button>
              <button
                v-if="index === trackingNumberInputs.length - 1"
                type="button"
                class="button button-sm button-primary"
                @click="addTrackingNumberField"
                :title="currentLang === 'de-DE' ? 'Weitere hinzufügen' : 'Add another'"
              >
                <span class="tf-icon ti ti-plus"></span>
              </button>
            </div>
          </div>
        </div>
        <div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="cancelTrackingNumber">
              {{ currentLang === 'de-DE' ? 'Abbrechen' : 'Cancel' }}
            </button>
            <button type="button" class="button button-primary" @click="submitTrackingNumber">
              {{ currentLang === 'de-DE' ? 'Speichern & Hochladen' : 'Save & Upload' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modalContent {
  width: auto;
  /* never wider than the viewport — keeps the modal fully on-screen on phones */
  max-width: calc(100vw - 1rem);
}
/* let the attachments table scroll horizontally instead of pushing the modal off-screen */
.modalContent :deep(.tableResponsive) {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}
@media (max-width: 600px) {
  .modalContent {
    width: calc(100vw - 0.5rem);
    max-width: calc(100vw - 0.5rem);
  }
}
</style>