<template>
  <AdminLayout>
    <Breadcrumb currentPageText="Slider Listesi" />
    <section class="section-list">
      <list-table-content
        :tableHeader="tableHeader"
        :rowAction="updateAction"
        :addAction="addAction"
        icon="sitemanagement"
        title="Slider Listesi"
        listText="Slider"
        :tableData="sliders"
        apiText="Slider Listesi"
        apiList="Slider"
        v-model:refresh="refresh"
        :rowActions="rowActions"
        :rowActionStyle="'width:10%;'" />
    </section>
    <panel-wrapper
      v-if="panel"
      v-model="panel"
      :panel-title="isUpdate ? 'Slider Düzenle' : 'Slider Ekle'">
      <template #panelContent>
        <form-input required v-model="panelSlider.baslik" label="Başlık" />
        <form-file
          v-model="panelSlider.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-input required v-model="panelSlider.url" label="Url" />
        <form-input required v-model="panelSlider.sira" label="Sıra" />
      </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, onMounted, 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 { useDialogStore } from '@/components/global/dialogStore'
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()

  const dialogStore = useDialogStore()

  const dataStore = useDataStore()
  const panel = ref<boolean>(false)
  const isUpdate = ref<boolean>(false)
  const refresh = ref<boolean>(false)
  const panelSlider = ref<Record<string, any>>({})
  const sliders = ref<Record<string, any>[]>([])

  const tableHeader = ref<Record<string, any>[]>([
    {
      name: 'baslik',
      title: 'Başlık',
      sort: true
    },
    {
      name: 'sira',
      title: 'Sıra',
      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',
      sort: true
    }
  ])

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

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

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

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

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

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

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

  const OpenMenu = (row: any) => {
    router.push('slider-yonetimi/' + row.id)
  }
  const addAction = async () => {
    isUpdate.value = false
    panelSlider.value = {
      baslik: '',
      resimUrl: '',
      url: '',
      sira: 1
    }
    panel.value = true
  }
  const updateAction = (row: any) => {
    panelSlider.value = sliders.value.find((x) => x.id == row.id) || {}
    panel.value = true
    isUpdate.value = true
  }
  const loadSliders = async () => {
    const data = await dataStore.dataGet('Slider')
    sliders.value = data
  }

  const save = async () => {
    if (isUpdate.value) {
      const formData = new FormData()
      formData.append('Baslik', panelSlider.value.baslik)
      formData.append('Url', panelSlider.value.url)
      formData.append('Sira', panelSlider.value?.sira)
      if (panelSlider.value.resimUrl instanceof File) {
        formData.append('ResimUrl', panelSlider.value.resimUrl)
      }

      let update: any = dataStore.dataPut('Slider/' + panelSlider.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('Slider/CreateSlider', {
        data: panelSlider.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>
