<template>
  <AdminLayout>
    <Breadcrumb currentPageText="Popup Listesi" go="/"/>
    <section class="section-list">
      <list-table-content
        :tableHeader="tableHeader"
        :rowAction="updateAction"
        :addAction="addAction"
        icon="sitemanagement"
        title="Popup Listesi"
        listText="Popup"
        :tableData="popups"
        apiText="Popup Listesi"
        apiList="Popup"
        v-model:refresh="refresh"
        :rowActions="rowActions"
        :rowActionStyle="'width:10%;'" />
    </section>
    <panel-wrapper
      v-if="panel"
      v-model="panel"
      :panel-title="isUpdate ? 'Popup Düzenle' : 'Popup Ekle'">
      <template #panelContent>
        <form-input v-model="panelPopup.baslik" label="Başlık" />
        <form-input v-model="panelPopup.url" label="Url" />
        <form-file
          v-model="panelPopup.resimUrl"
          label="Resim Url"
          :fileTypes="['png', 'jpg', 'jpeg']"
          elclass="panel-documents-item"
          fileType="img" />
        <div class="image-preview-wrapper" v-if="resimPreview">
          <img :src="resimPreview" alt="Seçilen Resim" />
        </div>
        <form-checkbox
          :listData="Checker"
          listText="label"
          listVal="val"
          v-model="panelPopup.durum">
          <template #checktext0>
            <span>Aktif</span>
          </template>
        </form-checkbox>
      </template>
      <template #footerButton>
        <div class="button-c button-save" @click="save">
          {{ isUpdate ? 'Kaydet' : 'Ekle' }}
        </div>
      </template>
    </panel-wrapper>
  </AdminLayout>
</template>
<script setup lang="ts">
  import { ref, computed } from 'vue'
  import AdminLayout from '@/layouts/AdminLayout.vue'
  import { Breadcrumb } from '@/components/global'
  import router from '@/router'
  import { useDataStore } from '@/stores/dataStore'
  import PanelWrapper from '@/components/PanelWrapper.vue'
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()
  import { useDialogStore } from '@/components/global/dialogStore'
  const dialogStore = useDialogStore()

  const Checker = ref([
    {
      label: '',
      val: 'durum'
    }
  ])
  const dataStore = useDataStore()
  const panel = ref<boolean>(false)
  const isUpdate = ref<boolean>(false)

  const refresh = ref<boolean>(false)
  const panelPopup = ref<Record<string, any>>({})
  const popups = ref<Record<string, any>[]>([])

  const tableHeader = ref<Record<string, any>[]>([
    {
      name: 'baslik',
      title: 'Başlık',
      sort: true
    },
    {
      name: 'resimUrl',
      title: 'Resim Url',
      computeHtml: (v: Record<string, any>) => {
        if (v.resimUrl !== null && v.resimUrl !== undefined) {
          return `<a href="${ v.resimUrl }" target="_blank" onclick="event.stopPropagation()"><img class="table-cell-image" src="${ v.resimUrl }" /></a>`
        }
      }
    },
    {
      name: 'url',
      title: 'Url'
    },
    {
      name: 'durum',
      title: 'Durum',
      computeHtml: (v: Record<string, any>): string => {
        if (v.durum) {
          return `<span class="back-grad back-grad-ok">
                Aktif
              </strong>`
        } else {
          return ``
        }
      }
    }
  ])

  const DeleteRowPop = (data: Record<string, any>, i: number) => {
    dialogStore.CreateDialog({
      title: 'Popup Sil',
      id: 'deletepop',
      content: 'Popup silmek istediğinize emin misiniz?',
      closeText: 'Vazgeç',
      buttons: [
        {
          label: 'Popup Sil',
          type: 'alert',
          function: () => DeleteRow(data.id)
        }
      ]
    })
  }

  const DeleteRow = async (id: number | string) => {
    var dt = await dataStore.dataDelete('Popup/' + id)

    if (dt !== 'errorfalse') {
      dialogStore.CloseDialog('deletepop')
      refresh.value = true
    }
  }

  const rowActions = ref<Record<string, any>[]>([
    {
      text: 'Sil',
      class: 'alert',
      action: DeleteRowPop
    }
  ])

  const resimPreview = computed(() => {
    if (!panelPopup.value.resimUrl) return null

    if (typeof panelPopup.value.resimUrl === 'string') {
      return panelPopup.value.resimUrl
    }

    // Eğer dosya ise
    return URL.createObjectURL(panelPopup.value.resimUrl)
  })

  const OpenMenu = (row: any) => {
    router.push('slider-yonetimi/' + row.id)
  }
  const addAction = async () => {
    isUpdate.value = false
    panelPopup.value = {
      baslik: '',
      resimUrl: '',
      url: '',
      durum: false
    }
    panel.value = true
  }
  const updateAction = (row: any) => {
    Object.assign(panelPopup.value,row)
    panel.value = true
    isUpdate.value = true
  }

  const save = async () => {
    if (isUpdate.value) {
      const formData = new FormData()
      formData.append('Baslik', panelPopup.value.baslik)
      formData.append('Durum', panelPopup.value.durum)
      formData.append('Url', panelPopup.value.url)
      if (panelPopup.value.resimUrl instanceof File) {
        formData.append('ResimUrl', panelPopup.value.resimUrl)
      }

      let update: any = dataStore.dataPut('Popup/' + panelPopup.value.id, {
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      if (update !== 'errorfalse') {
        panel.value = false
        isUpdate.value = false
        refresh.value = true
      }
    } else {
      let add = await dataStore.dataPost('Popup', {
        data: panelPopup.value,
        headers: { 'Content-Type': 'multipart/form-data' }
      })
      if (add !== 'errorfalse') {
        panel.value = false
        isUpdate.value = false
        refresh.value = true
      }
    }
  }
</script>
<style>
  .image-preview-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f8f9fa;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 12px;
    margin: 12px 20px;
    width: 100%;
    max-width: 100%;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }

  .image-preview-wrapper img {
    display: block;
    max-width: 100%;
    max-height: 250px;
    object-fit: cover;
    border-radius: 8px;
  }
</style>
