<script setup lang="ts">
import { __ } from '@wordpress/i18n'
import { onMounted, ref, computed, watch } from 'vue'
import {
  Combobox,
  ComboboxInput,
  ComboboxOptions,
  ComboboxOption,
  Popover,
  PopoverButton,
  PopoverPanel,
} from '@headlessui/vue'
import {
  getI18n,
  setParamValue,
} from '@/helper'
import { useUserSearch } from '@/composables/useUserSearch'
import {
  Search,
  Plus,
  Heart,
  ExternalLink,
  Sparkles,
  ArrowRight,
  Eye,
  Trash,
  ChevronsUpDown,
  Check,
  X,
  Columns3,
} from 'lucide-vue-next'
import { ICollectionPayload } from '@/types'
import { useCollectionsStore } from '@/api'

// Components.
import { Header } from '@/apps/partials'
import Notification from '@/helper/Notification.vue'
import Confirmation from '@/helper/Confirmation.vue'
import SortHeader from './SortHeader.vue'

const emit = defineEmits<{
  (e: 'loadItems', record: any, index: number): void
}>()

const EMPTY_FILTER_HIDE_NON_ADMIN = 'hide_non_admin'
const COLUMN_VISIBILITY_STORAGE_KEY = 'stwlite_admin_wishlist_columns'

type ColumnKey = 'name' | 'user' | 'status' | 'created_at' | 'updated_at'

interface ColumnDefinition {
  key: ColumnKey
  label: string
  weight: number
}

const columnDefinitions: ColumnDefinition[] = [
  { key: 'name', label: getI18n('column_name', __( 'Name', 'saveto-wishlist-lite-for-woocommerce' )), weight: 2 },
  { key: 'user', label: getI18n('column_user', __( 'User', 'saveto-wishlist-lite-for-woocommerce' )), weight: 2 },
  { key: 'status', label: getI18n('column_status', __( 'Status', 'saveto-wishlist-lite-for-woocommerce' )), weight: 1 },
  { key: 'created_at', label: getI18n('date_created', __( 'Date Created', 'saveto-wishlist-lite-for-woocommerce' )), weight: 2 },
  { key: 'updated_at', label: getI18n('last_updated', __( 'Last Updated', 'saveto-wishlist-lite-for-woocommerce' )), weight: 2 },
]

const loadColumnVisibility = (): Record<ColumnKey, boolean> => {
  const defaults = columnDefinitions.reduce((acc, col) => {
    acc[col.key] = true
    return acc
  }, {} as Record<ColumnKey, boolean>)
  try {
    const stored = localStorage.getItem(COLUMN_VISIBILITY_STORAGE_KEY)
    if (!stored) {
      return defaults
    }
    const parsed = JSON.parse(stored)
    // Spread merges stored values over defaults. `isColumnVisible` only reads
    // keys defined in `columnDefinitions`, so stale keys from removed/renamed
    // columns are harmless today — but when changing the column schema, bump
    // `COLUMN_VISIBILITY_STORAGE_KEY` to invalidate old admin localStorage.
    return { ...defaults, ...parsed }
  } catch {
    return defaults
  }
}

const columnVisibility = ref<Record<ColumnKey, boolean>>(loadColumnVisibility())

watch(columnVisibility, (value) => {
  try {
    localStorage.setItem(COLUMN_VISIBILITY_STORAGE_KEY, JSON.stringify(value))
  } catch {
    // ignore storage errors (private mode, quota, etc.)
  }
}, { deep: true })

const isColumnVisible = (key: ColumnKey) => columnVisibility.value[key] !== false

const toggleColumn = (key: ColumnKey) => {
  const next = !isColumnVisible(key)
  const visibleCount = columnDefinitions.filter((col) => isColumnVisible(col.key)).length
  if (!next && visibleCount <= 1) {
    return
  }
  columnVisibility.value = { ...columnVisibility.value, [key]: next }
}

const rowGridTemplate = computed(() => {
  const visibleWeights = columnDefinitions
    .filter((col) => isColumnVisible(col.key))
    .map((col) => `${col.weight}fr`)
  return `1fr ${visibleWeights.join(' ')} 2fr`
})

const { getCollections, deleteCollections } = useCollectionsStore()
const collections = ref<any>({
  data: [],
  total: 0,
  currentPage: 1,
})
const dataSource = ref<ICollectionPayload[]>([])
const paginationConfig = ref<any>({
  current: 1,
  pageSize: 10,
  total: 0,
  totalPages: 0,
})
const fetchingItems = ref<boolean>(false)
const searchWishlist = ref<string>('')
const statusFilter = ref<string>('')
const emptyFilter = ref<string>(EMPTY_FILTER_HIDE_NON_ADMIN)
const selectedUserFilter = ref<any>(null)
const sortColumn = ref<string>('id')
const sortOrder = ref<'ASC' | 'DESC'>('DESC')
const dateField = ref<'created_at' | 'updated_at'>('created_at')
const dateFrom = ref<string>('')
const dateTo = ref<string>('')
const {
  query: userFilterSearch,
  options: userFilterOptions,
  fetching: fetchingUserFilter,
  search: searchUserFilter,
  reset: resetUserFilter,
} = useUserSearch()
const isConfirmationOpen = ref<boolean>(false)
const confirmationMessage = ref<string>('')
const confirmDeleteItem = ref<any>(null)
const confirmActionType = ref<string>('delete')
const isConfirming = ref<boolean>(false)
const tableInfo = getI18n('table_info', __( 'Showing %1$s-%2$s of %3$s items', 'saveto-wishlist-lite-for-woocommerce' ))
const notificationMessage = ref<string>('')
const notificationType = ref<string>('')
const notificationMessageTitle = ref<string>('')

const infoData = {
  title: getI18n('wishlist_lists', __( 'Wishlist Lists', 'saveto-wishlist-lite-for-woocommerce' )),
  description: getI18n('wishlist_lists_description', __( 'Manage customer wishlists and preferences', 'saveto-wishlist-lite-for-woocommerce' )),
}

const tableSelectedRows = ref<any[]>([])

const dateFilterParams = computed(() => {
  if (!dateFrom.value && !dateTo.value) {
    return {}
  }
  const prefix = dateField.value === 'updated_at' ? 'updated' : 'created'
  return {
    [`${prefix}_from`]: dateFrom.value,
    [`${prefix}_to`]: dateTo.value,
  }
})

const fetchCollections = async () => {
  fetchingItems.value = true

  await getCollections({
    page: paginationConfig.value.current,
    posts_per_page: paginationConfig.value.pageSize,
    search: searchWishlist.value,
    status: statusFilter.value,
    user_id: selectedUserFilter.value?.value || '',
    sort_column: sortColumn.value,
    sort_order: sortOrder.value,
    ...dateFilterParams.value,
    hide_empty_non_admin: emptyFilter.value === EMPTY_FILTER_HIDE_NON_ADMIN ? 1 : '',
  }).then((response: any) => {
    collections.value = response

    fetchingItems.value = false

    // Pagination
    paginationConfig.value = {
      ...paginationConfig.value,
      total: collections.value.total,
      totalPages: Math.ceil(collections.value.total / paginationConfig.value.pageSize),
    }

    // Table data
    dataSource.value = collections.value.data.map((item: any) => ({
      ...item,
      status: item.status,
    }))

  }).catch(e => {
    if (e.error?.message) {
      notificationMessage.value = e.error?.message
      notificationMessageTitle.value = getI18n('error', __( 'Error', 'saveto-wishlist-lite-for-woocommerce' ))
      notificationType.value = 'error'
    }
  })
}

const handlePageChange = (page: number, pageSize: number) => {
  paginationConfig.value = {
    ...paginationConfig.value,
    current: page,
    pageSize: pageSize,
  }

  fetchCollections()
}

const handleSearch = () => {
  paginationConfig.value = {
    ...paginationConfig.value,
    current: 1,
  }

  fetchCollections()
}

const addNewWishlist = () => {
  setParamValue('add', 'new')
  emit('loadItems', 'new', 0)
}

const editWishlist = (record: any, index: number) => {
  emit('loadItems', record, index)
}

const deleteWishlist = async (record: any, index: number) => {
  confirmationMessage.value = getI18n('confirmDeleteText', __('Are you sure you want to delete this item?', 'saveto-wishlist-lite-for-woocommerce'))
  confirmDeleteItem.value = record.id
  confirmActionType.value = 'delete'
  isConfirmationOpen.value = true
}

const deleteSelected = async () => {
  confirmationMessage.value = getI18n('confirmDeleteItemsText', __('Are you sure you want to delete these items?', 'saveto-wishlist-lite-for-woocommerce'))
  confirmActionType.value = 'deleteSelected'
  isConfirmationOpen.value = true
}

const closeConfirmation = () => {
  isConfirmationOpen.value = false
  confirmActionType.value = ''
  confirmDeleteItem.value = null
  isConfirming.value = false
}

const surfaceSkippedDeletion = (response: any) => {
  const skipped = Array.isArray(response?.skipped) ? response.skipped : []
  if (skipped.length === 0) {
    return
  }
  notificationMessage.value = response?.message
    || getI18n('cannot_delete_last_wishlist_some', __('Some wishlists were skipped because each is the owner\'s only wishlist and would be recreated automatically.', 'saveto-wishlist-lite-for-woocommerce'))
  notificationMessageTitle.value = getI18n('cannot_delete_last_wishlist_title', __('Wishlist cannot be deleted', 'saveto-wishlist-lite-for-woocommerce'))
  notificationType.value = 'error'
}

const confirmAction = async () => {
  isConfirming.value = true

  if (confirmActionType.value === 'delete') {
    await deleteCollections([confirmDeleteItem.value]).then((response: any) => {
      surfaceSkippedDeletion(response)
      fetchCollections()

      confirmDeleteItem.value = null
      isConfirmationOpen.value = false
      confirmActionType.value = ''
      isConfirming.value = false
    })
  } else if (confirmActionType.value === 'deleteSelected') {
    const ids = tableSelectedRows.value.map((item: number) => item)
    await deleteCollections(ids).then((response: any) => {
      surfaceSkippedDeletion(response)
      fetchCollections()

      // Reset table selected rows.
      tableSelectedRows.value = []

      isConfirmationOpen.value = false
      confirmActionType.value = ''
      isConfirming.value = false
    })
  } else {
    isConfirmationOpen.value = false
    confirmActionType.value = ''
    isConfirming.value = false
  }
}

const toggleAll = (e: any) => {
  if (e.target.checked) {
    tableSelectedRows.value = dataSource.value.map((item: any) => item.id)
  } else {
    tableSelectedRows.value = []
  }
}

const toggleSingle = (id: number) => {
  if (tableSelectedRows.value.includes(id)) {
    tableSelectedRows.value = tableSelectedRows.value.filter((item: number) => item !== id)
  } else {
    tableSelectedRows.value = [...tableSelectedRows.value, id]
  }
}

const handleUserFilterChange = (user: any) => {
  selectedUserFilter.value = user
  handleSearch()
}

const handleSort = (column: string) => {
  if (sortColumn.value === column) {
    sortOrder.value = sortOrder.value === 'ASC' ? 'DESC' : 'ASC'
  } else {
    sortColumn.value = column
    sortOrder.value = 'DESC'
  }
  handleSearch()
}

const handleDateFilterChange = () => {
  handleSearch()
}

const clearDateFilter = () => {
  dateFrom.value = ''
  dateTo.value = ''
  handleSearch()
}

const formatDate = (value: string | null | undefined): string => {
  if (!value) {
    return '—'
  }
  const date = new Date(value.replace(' ', 'T'))
  if (Number.isNaN(date.getTime())) {
    return '—'
  }
  return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })
}

const clearUserFilter = () => {
  selectedUserFilter.value = null
  resetUserFilter()
  handleSearch()
}

const closeNotification = () => {
  notificationMessage.value = ''
}

const allSelected = computed(() => {
  return tableSelectedRows.value.length === dataSource.value.length
})

const paginationItems = computed(() => {
  const current = paginationConfig.value.current
  const totalPages = paginationConfig.value.totalPages
  const items: (number | string)[] = []

  if (totalPages <= 0) {
    return items
  }

  if (totalPages <= 7) {
    // Show all pages if 7 or fewer
    for (let i = 1; i <= totalPages; i++) {
      items.push(i)
    }
  } else {
    // Always show first page
    items.push(1)

    // Calculate the range around current page
    const delta = 1 // Number of pages to show on each side of current
    let start = Math.max(2, current - delta)
    let end = Math.min(totalPages - 1, current + delta)

    // Adjust if we're near the start
    if (current <= 3) {
      end = Math.min(5, totalPages - 1)
    }

    // Adjust if we're near the end
    if (current >= totalPages - 2) {
      start = Math.max(2, totalPages - 4)
    }

    // Add ellipsis after first page if needed
    if (start > 2) {
      items.push('ellipsis-start')
    }

    // Add page numbers in the range
    for (let i = start; i <= end; i++) {
      items.push(i)
    }

    // Add ellipsis before last page if needed
    if (end < totalPages - 1) {
      items.push('ellipsis-end')
    }

    // Always show last page
    if (totalPages > 1) {
      items.push(totalPages)
    }
  }

  return items
})

onMounted(() => {
  fetchCollections()
})
</script>

<template>
  <div class="wishlist-lists">
    <div class="stwlite-tw-bg-gray-50">
      <Header
        :infoData="infoData"
        :showButton="true"
        buttonIcon="plus"
        :buttonText="getI18n('add_new', __( 'Add New', 'saveto-wishlist-lite-for-woocommerce' ))"
        @trigger-button="addNewWishlist"
      />

      <div class="stwlite-tw-max-w-7xl stwlite-tw-mx-auto stwlite-tw-px-4 sm:stwlite-tw-px-6 lg:stwlite-tw-px-8 stwlite-tw-py-8">
        <div class="stwlite-tw-bg-white stwlite-tw-rounded-lg stwlite-tw-shadow-sm stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-mb-6 stwlite-tw-border-solid">
          <div class="stwlite-tw-px-6 stwlite-tw-py-4 stwlite-tw-border-0 stwlite-tw-border-b stwlite-tw-border-gray-200 stwlite-tw-border-solid">
            <div class="savetowishlist-tw-filters stwlite-tw-flex stwlite-tw-flex-col sm:stwlite-tw-flex-row sm:stwlite-tw-items-center sm:stwlite-tw-justify-between stwlite-tw-gap-4">
              <div class="stwlite-tw-flex stwlite-tw-flex-col sm:stwlite-tw-flex-row stwlite-tw-gap-4">

                <!-- Delete Selected -->
                <button v-if="tableSelectedRows.length > 0" type="button" class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-transparent stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-white stwlite-tw-bg-red-600 hover:stwlite-tw-bg-red-700 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-red-500 stwlite-tw-transition-colors stwlite-tw-duration-200" @click="deleteSelected"> 
                  <Trash class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2" />
                  {{ getI18n('delete', __( 'Delete', 'saveto-wishlist-lite-for-woocommerce' )) }}
                </button>

                <!-- Status Filter -->
                <select
                  v-model="statusFilter"
                  @change="handleSearch"
                  class="stwlite-tw-block stwlite-tw-w-[340px] stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm focus:stwlite-tw-outline-none focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-border-solid"
                >
                  <option value="" class="stwlite-tw-italic">{{ getI18n('select_status', __('Select Status', 'saveto-wishlist-lite-for-woocommerce')) }}</option>
                  <option value="publish">{{ getI18n('publish', __('Publish', 'saveto-wishlist-lite-for-woocommerce')) }}</option>
                  <option value="draft">{{ getI18n('draft', __('Draft', 'saveto-wishlist-lite-for-woocommerce')) }}</option>
                </select>

                <!-- Empty Wishlist Filter -->
                <select
                  v-model="emptyFilter"
                  @change="handleSearch"
                  :aria-label="getI18n('empty_filter_label', __('Empty wishlist visibility', 'saveto-wishlist-lite-for-woocommerce'))"
                  class="stwlite-tw-block stwlite-tw-w-[340px] stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm focus:stwlite-tw-outline-none focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-border-solid"
                >
                  <option value="">{{ getI18n('empty_filter_show_all', __('Show all wishlists', 'saveto-wishlist-lite-for-woocommerce')) }}</option>
                  <option :value="EMPTY_FILTER_HIDE_NON_ADMIN">{{ getI18n('empty_filter_hide_non_admin', __('Hide empty (non-admin)', 'saveto-wishlist-lite-for-woocommerce')) }}</option>
                </select>

                <!-- User Filter -->
                <div class="stwlite-tw-relative stwlite-tw-w-[340px]">
                  <Combobox v-model="selectedUserFilter" @update:model-value="handleUserFilterChange">
                    <div class="stwlite-tw-relative">
                      <div class="stwlite-tw-relative stwlite-tw-w-full stwlite-tw-cursor-default stwlite-tw-overflow-hidden stwlite-tw-rounded-md stwlite-tw-border-solid stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-bg-white stwlite-tw-text-left stwlite-tw-shadow-sm sm:stwlite-tw-text-sm">
                        <ComboboxInput
                          class="stwlite-tw-w-full stwlite-tw-border-0 stwlite-tw-py-2 stwlite-tw-pl-3 stwlite-tw-pr-16 stwlite-tw-leading-5 stwlite-tw-text-gray-500 stwlite-tw-text-sm"
                          :display-value="(user: any) => user?.label || ''"
                          :placeholder="getI18n('select_user', __('Select User', 'saveto-wishlist-lite-for-woocommerce'))"
                          autocomplete="off"
                          @change="(e: Event) => searchUserFilter((e.target as HTMLInputElement).value)"
                        />
                        <div class="stwlite-tw-absolute stwlite-tw-inset-y-0 stwlite-tw-right-0 stwlite-tw-flex stwlite-tw-items-center stwlite-tw-pr-2">
                          <button
                            v-if="selectedUserFilter"
                            type="button"
                            @click.prevent="clearUserFilter"
                            :aria-label="getI18n('clear_user_filter', __('Clear user filter', 'saveto-wishlist-lite-for-woocommerce'))"
                            class="stwlite-tw-p-1 stwlite-tw-text-gray-400 hover:stwlite-tw-text-gray-600 stwlite-tw-border-0 stwlite-tw-bg-transparent stwlite-tw-cursor-pointer"
                          >
                            <X class="stwlite-tw-h-4 stwlite-tw-w-4" />
                          </button>
                          <ChevronsUpDown v-else class="stwlite-tw-h-5 stwlite-tw-w-5 stwlite-tw-text-gray-400" aria-hidden="true" />
                        </div>
                      </div>

                      <div
                        v-if="fetchingUserFilter"
                        class="stwlite-tw-absolute stwlite-tw-z-10 stwlite-tw-mt-1 stwlite-tw-w-full stwlite-tw-bg-white stwlite-tw-py-2 stwlite-tw-px-3 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-rounded-md stwlite-tw-shadow"
                      >
                        {{ getI18n('searching', __('Searching...', 'saveto-wishlist-lite-for-woocommerce')) }}
                      </div>

                      <ComboboxOptions
                        v-else-if="userFilterOptions.length > 0"
                        class="stwlite-tw-absolute stwlite-tw-z-10 stwlite-tw-mt-1 stwlite-tw-max-h-60 stwlite-tw-w-full stwlite-tw-overflow-auto stwlite-tw-rounded-md stwlite-tw-bg-white stwlite-tw-py-1 stwlite-tw-text-base stwlite-tw-shadow-lg stwlite-tw-ring-1 stwlite-tw-ring-black stwlite-tw-ring-opacity-5 focus:stwlite-tw-outline-none sm:stwlite-tw-text-sm"
                      >
                        <ComboboxOption
                          v-for="user in userFilterOptions"
                          :key="user.value"
                          :value="user"
                          class="stwlite-tw-relative stwlite-tw-cursor-default stwlite-tw-select-none stwlite-tw-py-2 stwlite-tw-pl-10 stwlite-tw-pr-4"
                          v-slot="{ selected }"
                        >
                          <span class="stwlite-tw-block stwlite-tw-truncate" :class="selected ? 'stwlite-tw-font-medium' : 'stwlite-tw-font-normal'">
                            {{ user.label }}
                          </span>
                          <span v-if="selected" class="stwlite-tw-absolute stwlite-tw-inset-y-0 stwlite-tw-left-0 stwlite-tw-flex stwlite-tw-items-center stwlite-tw-pl-3 stwlite-tw-text-blue-600">
                            <Check class="stwlite-tw-h-5 stwlite-tw-w-5" aria-hidden="true" />
                          </span>
                        </ComboboxOption>
                      </ComboboxOptions>

                      <p
                        v-else-if="userFilterSearch && !fetchingUserFilter && userFilterOptions.length === 0"
                        class="stwlite-tw-absolute stwlite-tw-z-10 stwlite-tw-mt-1 stwlite-tw-w-full stwlite-tw-bg-white stwlite-tw-py-2 stwlite-tw-px-3 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-rounded-md stwlite-tw-shadow"
                      >
                        {{ getI18n('no_users_found', __('No users found', 'saveto-wishlist-lite-for-woocommerce')) }}
                      </p>
                    </div>
                  </Combobox>
                </div>
              </div>
              
              <div class="stwlite-tw-relative">
                <div class="stwlite-tw-absolute stwlite-tw-inset-y-0 stwlite-tw-left-0 stwlite-tw-pl-3 stwlite-tw-flex stwlite-tw-items-center stwlite-tw-pointer-events-none">
                  <Search class="stwlite-tw-h-4 stwlite-tw-w-4 stwlite-tw-text-gray-400" />
                </div>
                <input
                  type="text"
                  v-model="searchWishlist"
                  :placeholder="getI18n('search_wishlist', __( 'Search Wishlist', 'saveto-wishlist-lite-for-woocommerce' ))"
                  @input="handleSearch"
                  class="stwlite-tw-block stwlite-tw-w-full sm:stwlite-tw-w-64 stwlite-tw-pl-10 stwlite-tw-pr-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-leading-5 stwlite-tw-bg-white stwlite-tw-placeholder-gray-500 focus:stwlite-tw-outline-none focus:stwlite-tw-placeholder-gray-400 focus:stwlite-tw-ring-1 focus:stwlite-tw-ring-blue-500 focus:stwlite-tw-border-blue-500 stwlite-tw-text-sm"
                />
              </div>
            </div>

            <!-- Date Range Filter -->
            <div class="stwlite-tw-flex stwlite-tw-flex-col sm:stwlite-tw-flex-row sm:stwlite-tw-items-center stwlite-tw-gap-4 stwlite-tw-mt-4">
              <span class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-font-medium">
                {{ getI18n('filter_by_date', __( 'Filter by date', 'saveto-wishlist-lite-for-woocommerce' )) }}
              </span>
              <select
                v-model="dateField"
                @change="handleDateFilterChange"
                class="stwlite-tw-block stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm focus:stwlite-tw-outline-none focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-border-solid"
              >
                <option value="created_at">{{ getI18n('date_created', __( 'Date Created', 'saveto-wishlist-lite-for-woocommerce' )) }}</option>
                <option value="updated_at">{{ getI18n('last_updated', __( 'Last Updated', 'saveto-wishlist-lite-for-woocommerce' )) }}</option>
              </select>
              <input
                v-model="dateFrom"
                type="date"
                :max="dateTo || undefined"
                @change="handleDateFilterChange"
                :aria-label="getI18n('date_from', __( 'From date', 'saveto-wishlist-lite-for-woocommerce' ))"
                class="stwlite-tw-block stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm focus:stwlite-tw-outline-none focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-border-solid"
              />
              <span class="stwlite-tw-text-sm stwlite-tw-text-gray-500">
                {{ getI18n('to', __( 'to', 'saveto-wishlist-lite-for-woocommerce' )) }}
              </span>
              <input
                v-model="dateTo"
                type="date"
                :min="dateFrom || undefined"
                @change="handleDateFilterChange"
                :aria-label="getI18n('date_to', __( 'To date', 'saveto-wishlist-lite-for-woocommerce' ))"
                class="stwlite-tw-block stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm focus:stwlite-tw-outline-none focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-text-sm stwlite-tw-text-gray-500 stwlite-tw-border-solid"
              />
              <button
                v-if="dateFrom || dateTo"
                type="button"
                @click="clearDateFilter"
                class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-2 stwlite-tw-py-1 stwlite-tw-text-xs stwlite-tw-text-gray-500 hover:stwlite-tw-text-gray-700 stwlite-tw-bg-transparent stwlite-tw-border-0 stwlite-tw-cursor-pointer"
              >
                <X class="stwlite-tw-w-3 stwlite-tw-h-3 stwlite-tw-mr-1" />
                {{ getI18n('clear', __( 'Clear', 'saveto-wishlist-lite-for-woocommerce' )) }}
              </button>

              <!-- Columns Visibility -->
              <Popover class="stwlite-tw-relative sm:stwlite-tw-ml-auto">
                <PopoverButton
                  class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-solid stwlite-tw-border-gray-300 stwlite-tw-rounded-md stwlite-tw-shadow-sm stwlite-tw-bg-white stwlite-tw-text-sm stwlite-tw-text-gray-700 hover:stwlite-tw-bg-gray-50 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-1 focus:stwlite-tw-ring-gray-500 focus:stwlite-tw-border-gray-500 stwlite-tw-cursor-pointer"
                >
                  <Columns3 class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2" />
                  {{ getI18n('columns', __( 'Columns', 'saveto-wishlist-lite-for-woocommerce' )) }}
                </PopoverButton>
                <PopoverPanel
                  class="stwlite-tw-absolute stwlite-tw-right-0 stwlite-tw-z-10 stwlite-tw-mt-1 stwlite-tw-w-56 stwlite-tw-bg-white stwlite-tw-rounded-md stwlite-tw-shadow-lg stwlite-tw-ring-1 stwlite-tw-ring-black stwlite-tw-ring-opacity-5 focus:stwlite-tw-outline-none"
                >
                  <div class="stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-text-xs stwlite-tw-font-medium stwlite-tw-text-gray-500 stwlite-tw-uppercase stwlite-tw-tracking-wider stwlite-tw-border-0 stwlite-tw-border-b stwlite-tw-border-solid stwlite-tw-border-gray-200">
                    {{ getI18n('show_columns', __( 'Show columns', 'saveto-wishlist-lite-for-woocommerce' )) }}
                  </div>
                  <div class="stwlite-tw-py-1">
                    <label
                      v-for="column in columnDefinitions"
                      :key="column.key"
                      class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-text-sm stwlite-tw-text-gray-700 hover:stwlite-tw-bg-gray-50 stwlite-tw-cursor-pointer"
                    >
                      <input
                        type="checkbox"
                        :checked="isColumnVisible(column.key)"
                        @change="toggleColumn(column.key)"
                        class="stwlite-tw-h-4 stwlite-tw-w-4 stwlite-tw-mr-2"
                      />
                      {{ column.label }}
                    </label>
                  </div>
                </PopoverPanel>
              </Popover>
            </div>
          </div>

          <div v-if="fetchingItems" class="stwlite-tw-px-6 stwlite-tw-py-3">
            <div class="stwlite-tw-animate-pulse stwlite-tw-flex stwlite-tw-space-x-4">
              <div class="stwlite-tw-flex-1 stwlite-tw-space-y-6 stwlite-tw-py-1">
                <div class="stwlite-tw-h-2 stwlite-tw-bg-slate-700 stwlite-tw-rounded"></div>
                <div class="stwlite-tw-space-y-3">
                  <div class="stwlite-tw-grid stwlite-tw-grid-cols-3 stwlite-tw-gap-4">
                    <div class="stwlite-tw-h-2 stwlite-tw-bg-slate-700 stwlite-tw-rounded stwlite-tw-col-span-2"></div>
                    <div class="stwlite-tw-h-2 stwlite-tw-bg-slate-700 stwlite-tw-rounded stwlite-tw-col-span-1"></div>
                  </div>
                  <div class="stwlite-tw-h-2 stwlite-tw-bg-slate-700 stwlite-tw-rounded"></div>
                </div>
              </div>
            </div>
          </div>

          <div v-else>
            <div class="stwlite-tw-px-6 stwlite-tw-py-3 stwlite-tw-bg-gray-50 stwlite-tw-border-0 stwlite-tw-border-b stwlite-tw-border-gray-200 stwlite-tw-border-solid">
              <div
                class="stwlite-tw-grid stwlite-tw-gap-6 stwlite-tw-items-center stwlite-tw-text-left stwlite-tw-text-xs stwlite-tw-font-medium stwlite-tw-text-gray-500 stwlite-tw-uppercase stwlite-tw-tracking-wider"
                :style="{ 'grid-template-columns': rowGridTemplate }"
              >
                <div>
                  <input
                    type="checkbox"
                    :checked="allSelected"
                    @change="toggleAll"
                    class="stwlite-tw-h-4 stwlite-tw-w-4"
                  />
                </div>
                <div v-if="isColumnVisible('name')">
                  <SortHeader
                    :label="getI18n('column_name', __( 'Name', 'saveto-wishlist-lite-for-woocommerce' ))"
                    column="name"
                    :activeColumn="sortColumn"
                    :activeOrder="sortOrder"
                    @sort="handleSort"
                  />
                </div>
                <div v-if="isColumnVisible('user')">{{ getI18n('column_user', __( 'User', 'saveto-wishlist-lite-for-woocommerce' )) }}</div>
                <div v-if="isColumnVisible('status')">{{ getI18n('column_status', __( 'Status', 'saveto-wishlist-lite-for-woocommerce' )) }}</div>
                <div v-if="isColumnVisible('created_at')">
                  <SortHeader
                    :label="getI18n('date_created', __( 'Date Created', 'saveto-wishlist-lite-for-woocommerce' ))"
                    column="created_at"
                    :activeColumn="sortColumn"
                    :activeOrder="sortOrder"
                    @sort="handleSort"
                  />
                </div>
                <div v-if="isColumnVisible('updated_at')">
                  <SortHeader
                    :label="getI18n('last_updated', __( 'Last Updated', 'saveto-wishlist-lite-for-woocommerce' ))"
                    column="updated_at"
                    :activeColumn="sortColumn"
                    :activeOrder="sortOrder"
                    @sort="handleSort"
                  />
                </div>
                <div>{{ getI18n('column_actions', __( 'Actions', 'saveto-wishlist-lite-for-woocommerce' )) }}</div>
              </div>
            </div>

            <div v-if="dataSource.length > 0">
              <div v-for="(item, index) in dataSource" class="stwlite-tw-px-6 stwlite-tw-py-3 stwlite-tw-border-b stwlite-tw-border-gray-200">
                <div
                  class="stwlite-tw-grid stwlite-tw-gap-6 stwlite-tw-items-center stwlite-tw-text-left stwlite-tw-text-xs stwlite-tw-text-gray-500 stwlite-tw-tracking-wider"
                  :style="{ 'grid-template-columns': rowGridTemplate }"
                >
                  <div><input type="checkbox" :checked="tableSelectedRows.includes(item.id)" @change="toggleSingle(item.id)" /></div>
                  <div v-if="isColumnVisible('name')">{{ item.name }}</div>
                  <div v-if="isColumnVisible('user')">{{ item.user_name || '' }}</div>
                  <div v-if="isColumnVisible('status')">{{ item.status === 'publish' ? getI18n('published', __( 'Published', 'saveto-wishlist-lite-for-woocommerce' )) : getI18n('draft', __( 'Draft', 'saveto-wishlist-lite-for-woocommerce' )) }}</div>
                  <div v-if="isColumnVisible('created_at')">{{ formatDate(item.created_at) }}</div>
                  <div v-if="isColumnVisible('updated_at')">{{ formatDate(item.updated_at) }}</div>
                  <div class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-gap-2">
                    <button class="wishlist-lists-view-details stwlite-tw-flex stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-transparent stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-white stwlite-tw-bg-blue-600 hover:stwlite-tw-bg-blue-700 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-blue-500 stwlite-tw-transition-colors stwlite-tw-duration-200 stwlite-tw-cursor-pointer" @click="editWishlist(item, index)">
                      <Eye class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2" /> {{ getI18n('view_details', __( 'Details', 'saveto-wishlist-lite-for-woocommerce' )) }}
                    </button>
                    <button class="wishlist-lists-delete stwlite-tw-flex stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-px-3 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-transparent stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-white stwlite-tw-bg-red-600 hover:stwlite-tw-bg-red-700 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-red-500 stwlite-tw-transition-colors stwlite-tw-duration-200 stwlite-tw-cursor-pointer" @click="deleteWishlist(item, index)">
                      <Trash class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-mr-2" /> {{ getI18n('delete', __( 'Delete', 'saveto-wishlist-lite-for-woocommerce' )) }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div class="stwlite-tw-px-6 stwlite-tw-py-16">
                <div class="stwlite-tw-text-center stwlite-tw-max-w-md stwlite-tw-mx-auto">
                  <div class="stwlite-tw-mx-auto stwlite-tw-w-20 stwlite-tw-h-20 stwlite-tw-bg-gradient-to-br from-pink-100 to-purple-100 stwlite-tw-rounded-full stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-center stwlite-tw-mb-6">
                    <div class="stwlite-tw-relative">
                      <Heart class="stwlite-tw-w-8 stwlite-tw-h-8 stwlite-tw-text-pink-500" />
                      <Sparkles class="stwlite-tw-w-4 stwlite-tw-h-4 stwlite-tw-text-purple-500 stwlite-tw-absolute stwlite-tw-top-1 stwlite-tw-right-1" />
                    </div>
                  </div>
    
                  <h3 class="stwlite-tw-text-xl stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-3">
                    {{ getI18n('no_wishlists_yet', __( 'No wishlists yet!', 'saveto-wishlist-lite-for-woocommerce' )) }}
                  </h3>
                  
                  <p class="stwlite-tw-text-gray-500 stwlite-tw-mb-6 stwlite-tw-leading-relaxed">
                    {{ getI18n('no_wishlists_yet_description', __( 'Your customers haven\'t created any wishlists yet. Once they start saving their favorite products, you\'ll see all their wishlist activity here.', 'saveto-wishlist-lite-for-woocommerce' )) }}
                  </p>
    
                  <div class="stwlite-tw-bg-gradient-to-r from-blue-50 to-purple-50 stwlite-tw-rounded-lg stwlite-tw-p-6 stwlite-tw-border stwlite-tw-border-blue-200">
                    <h4 class="stwlite-tw-text-lg stwlite-tw-font-semibold stwlite-tw-text-gray-900 stwlite-tw-mb-2">
                      {{ getI18n('get_started_with_save_to_wishlist', __( 'Get Started with SaveTo Wishlist', 'saveto-wishlist-lite-for-woocommerce' )) }}
                    </h4>
                    <p class="stwlite-tw-text-sm stwlite-tw-text-gray-600 stwlite-tw-mb-4">
                      {{ getI18n('learn_how_to_maximize', __( 'Learn how to maximize your wishlist functionality and boost customer engagement with our comprehensive guides and best practices.', 'saveto-wishlist-lite-for-woocommerce' )) }}
                    </p>
                    
                    <div class="stwlite-tw-flex stwlite-tw-flex-col sm:stwlite-tw-flex-row stwlite-tw-justify-center stwlite-tw-gap-3">
                      <a 
                        href="https://savetowishlist.com/knowledge-base/?utm_source=stwlite&utm_medium=wishlistpage&utm_campaign=wishlistpagebutton" 
                        target="_blank"
                        class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-justify-center stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-transparent stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-white stwlite-tw-bg-blue-600 hover:stwlite-tw-bg-blue-700 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-blue-500 stwlite-tw-transition-all stwlite-tw-duration-200 stwlite-tw-transform hover:stwlite-tw-scale-105 hover:stwlite-tw-text-white stwlite-tw-no-underline"
                      >
                        {{ getI18n('view_documentation', __( 'View Documentation', 'saveto-wishlist-lite-for-woocommerce' )) }}
                        <ExternalLink class="stwlite-tw-ml-2 stwlite-tw-w-4 stwlite-tw-h-4" />
                      </a>
                      
                      <a 
                        href="https://wordpress.org/support/plugin/saveto-wishlist-lite-for-woocommerce/" 
                        target="_blank"
                        class="stwlite-tw-inline-flex stwlite-tw-items-center stwlite-tw-justify-center stwlite-tw-px-4 stwlite-tw-py-2 stwlite-tw-border stwlite-tw-border-gray-300 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-rounded-md stwlite-tw-text-gray-700 stwlite-tw-bg-white hover:stwlite-tw-bg-gray-50 focus:stwlite-tw-outline-none focus:stwlite-tw-ring-2 focus:stwlite-tw-ring-offset-2 focus:stwlite-tw-ring-blue-500 stwlite-tw-transition-all stwlite-tw-duration-200 hover:stwlite-tw-text-gray-700 stwlite-tw-no-underline"
                      >
                        {{ getI18n('get_support', __( 'Get Support', 'saveto-wishlist-lite-for-woocommerce' )) }}
                        <ArrowRight class="stwlite-tw-ml-2 stwlite-tw-w-4 stwlite-tw-h-4" />
                      </a>
                    </div>
                  </div>
                </div>
              </div>

            </div>
            
          </div>
        </div>

        <div v-if="paginationConfig.totalPages > 0" class="stwlite-tw-p-6 stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-center">
          <nav class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-1" aria-label="Pagination">
            <!-- Previous -->
            <button
              @click="handlePageChange(paginationConfig.current - 1, paginationConfig.pageSize)"
              :disabled="paginationConfig.current === 1"
              class="stwlite-tw-px-3 stwlite-tw-py-1.5 stwlite-tw-rounded-lg stwlite-tw-border stwlite-tw-border-solid stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-cursor-pointer"
              :class="paginationConfig.current === 1 
                ? 'stwlite-tw-text-gray-400 stwlite-tw-bg-gray-100 stwlite-tw-cursor-not-allowed' 
                : 'stwlite-tw-text-gray-700 stwlite-tw-bg-white hover:stwlite-tw-bg-gray-50 stwlite-tw-border-gray-300'"
            >
              {{ getI18n('previous', __( 'Previous', 'saveto-wishlist-lite-for-woocommerce' )) }}
            </button>

            <!-- Page numbers -->
            <Transition
              enter="transition ease-out duration-200"
              enter-from="opacity-0 translate-y-1"
              enter-to="opacity-100 translate-y-0"
              leave="transition ease-in duration-150"
              leave-from="opacity-100 translate-y-0"
              leave-to="opacity-0 translate-y-1"
            >
              <div class="stwlite-tw-flex stwlite-tw-space-x-1">
                <template v-for="(item, index) in paginationItems" :key="index">
                  <button
                    v-if="typeof item === 'number'"
                    @click="handlePageChange(item, paginationConfig.pageSize)"
                    class="stwlite-tw-px-3 stwlite-tw-py-1.5 stwlite-tw-rounded-lg stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-border stwlite-tw-border-solid stwlite-tw-cursor-pointer"
                    :class="item === paginationConfig.current 
                      ? 'stwlite-tw-bg-blue-600 stwlite-tw-text-white stwlite-tw-border-blue-600' 
                      : 'stwlite-tw-bg-white stwlite-tw-text-gray-700 stwlite-tw-border-gray-300 hover:stwlite-tw-bg-gray-50'"
                  >
                    {{ item }}
                  </button>
                  <span
                    v-else
                    class="stwlite-tw-px-3 stwlite-tw-py-1.5 stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-text-gray-500"
                  >
                    ...
                  </span>
                </template>
              </div>
            </Transition>

            <!-- Next -->
            <button
              @click="handlePageChange(paginationConfig.current + 1, paginationConfig.pageSize)"
              :disabled="paginationConfig.current === paginationConfig.totalPages"
              class="stwlite-tw-px-3 stwlite-tw-py-1.5 stwlite-tw-rounded-lg stwlite-tw-border stwlite-tw-border-solid stwlite-tw-text-sm stwlite-tw-font-medium stwlite-tw-cursor-pointer"
              :class="paginationConfig.current === paginationConfig.totalPages 
                ? 'stwlite-tw-text-gray-400 stwlite-tw-bg-gray-100 stwlite-tw-cursor-not-allowed' 
                : 'stwlite-tw-text-gray-700 stwlite-tw-bg-white hover:stwlite-tw-bg-gray-50 stwlite-tw-border-gray-300'"
            >
              {{ getI18n('next', __( 'Next', 'saveto-wishlist-lite-for-woocommerce' )) }}
            </button>
          </nav>
        </div>

        <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-justify-between stwlite-tw-bg-white stwlite-tw-px-6 stwlite-tw-py-3 stwlite-tw-rounded-lg stwlite-tw-shadow-sm stwlite-tw-border stwlite-tw-border-gray-200 stwlite-tw-opacity-50 stwlite-tw-border-solid">
          <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-text-sm stwlite-tw-text-gray-500">
            <span>{{ tableInfo.replace('%1$s', ((paginationConfig.current - 1) * paginationConfig.pageSize + 1).toString()).replace('%2$s', Math.min(paginationConfig.current * paginationConfig.pageSize, paginationConfig.total).toString()).replace('%3$s', paginationConfig.total.toString()) }}</span>
          </div>
          <div class="stwlite-tw-flex stwlite-tw-items-center stwlite-tw-space-x-2 stwlite-tw-text-sm stwlite-tw-text-gray-500">
            <span>{{ paginationConfig.pageSize }} / {{ getI18n('page', __( 'Page', 'saveto-wishlist-lite-for-woocommerce' )) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <Confirmation
    :isOpen="isConfirmationOpen"
    :processing="isConfirming"
    :title="getI18n('confirmation_title', __('Confirmation', 'saveto-wishlist-lite-for-woocommerce'))"
    :message="confirmationMessage"
    :confirmText="getI18n('delete', __('Delete', 'saveto-wishlist-lite-for-woocommerce'))"
    :cancelText="getI18n('cancelButtonText', __('Cancel', 'saveto-wishlist-lite-for-woocommerce'))"
    @closeAction="closeConfirmation"
    @confirmAction="confirmAction"
  />

  <Notification
    v-if="notificationMessage"
    :message="notificationMessage"
    :type="notificationType"
    :messageTitle="notificationMessageTitle"
    @closeNotification="closeNotification"
  />
</template>

<style scoped lang="scss">
.savetowishlist-tw-filters {
  select,
  input[type="text"],
  input[type="date"] {
    width: 275px;
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding-top: 0.5rem;
    padding-bottom: 0.5rem;
    padding-left: 0.75rem;
    padding-right: 0.75rem;
    border-color: rgb(209 213 219 / 1);
    border-width: 1px;
    border-radius: 0.375rem;
    background-color: rgb(255 255 255 / 1);
  }

  input[type="text"] {
    padding-left: 2.5rem;
  }
}
</style>