<script setup lang="ts">
import { imagesApi } from '@/lib/api'
import { formatBytes, formatPercentage } from '@/lib/display'
import { useCompanyStore } from '@/stores/company'
import type { ImageAssetItem } from '@geo/shared-types'
import { useQuery } from '@tanstack/vue-query'
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

withDefaults(
  defineProps<{
    singleSelect?: boolean
  }>(),
  {
    singleSelect: true,
  },
)

const emit = defineEmits<{
  select: [image: ImageAssetItem]
}>()

const { t } = useI18n()
const companyStore = useCompanyStore()
const currentBrandId = computed(() => companyStore.currentBrandId)

// State
const selectedFolderId = ref<number | null>(null)
const searchKeyword = ref('')
const debouncedSearch = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const selectedId = ref<number | null>(null)

// Queries
const foldersQuery = useQuery({
  queryKey: computed(() => ['images', 'folders', currentBrandId.value]),
  enabled: computed(() => Boolean(currentBrandId.value)),
  queryFn: () => imagesApi.listFolders(),
})

const imagesQuery = useQuery({
  queryKey: computed(() => [
    'images',
    'list',
    'picker',
    currentBrandId.value,
    {
      folder_id: selectedFolderId.value,
      q: debouncedSearch.value,
      page: currentPage.value,
      page_size: pageSize.value,
    },
  ]),
  enabled: computed(() => Boolean(currentBrandId.value)),
  queryFn: () =>
    imagesApi.list({
      folder_id: selectedFolderId.value ?? undefined,
      q: debouncedSearch.value,
      page: currentPage.value,
      page_size: pageSize.value,
    }),
})

const storageQuery = useQuery({
  queryKey: ['images', 'storage-usage', 'picker'],
  queryFn: () => imagesApi.storageUsage(),
})

// Computed
const folders = computed(() => foldersQuery.data.value ?? [])
const images = computed(() => imagesQuery.data.value?.items ?? [])
const totalImages = computed(() => imagesQuery.data.value?.total ?? 0)
const storageUsage = computed(() => storageQuery.data.value)

// Actions
let searchTimer: ReturnType<typeof setTimeout> | null = null
watch(searchKeyword, () => {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    debouncedSearch.value = searchKeyword.value
    currentPage.value = 1
  }, 300)
})

watch(currentBrandId, () => {
  selectedFolderId.value = null
  selectedId.value = null
  currentPage.value = 1
})

function handleSelect(image: ImageAssetItem) {
  selectedId.value = image.id
  emit('select', image)
}

function getSelectPopupContainer(triggerNode: HTMLElement) {
  return triggerNode.parentElement ?? triggerNode
}
</script>

<template>
  <div class="image-library-picker">
    <div class="picker-toolbar">
      <a-select
        v-model:value="selectedFolderId"
        style="width: 160px"
        :placeholder="t('images.allFolders')"
        allow-clear
        :get-popup-container="getSelectPopupContainer"
        @change="currentPage = 1"
      >
        <a-select-option :value="null">{{ t('images.allFolders') }}</a-select-option>
        <a-select-option v-for="f in folders" :key="f.id" :value="f.id">
          {{ f.name }}
        </a-select-option>
      </a-select>

      <a-input-search
        v-model:value="searchKeyword"
        :placeholder="t('images.searchPlaceholder')"
        style="width: 240px"
        allow-clear
      />
    </div>

    <div class="picker-content">
      <div v-if="images.length > 0" class="image-grid">
        <div
          v-for="image in images"
          :key="image.id"
          class="image-item"
          :class="{ 'image-item--selected': selectedId === image.id }"
          @click="handleSelect(image)"
        >
          <div class="image-item__preview">
            <img :src="image.url" :alt="image.name" loading="lazy" />
          </div>
          <div class="image-item__name" :title="image.name">{{ image.name }}</div>
        </div>
      </div>
      <div v-else-if="!imagesQuery.isPending.value" class="empty-state">
        <a-empty :description="t('images.noImages')" />
      </div>

      <div v-if="totalImages > pageSize" class="pagination-wrapper">
        <a-pagination
          v-model:current="currentPage"
          :total="totalImages"
          :page-size="pageSize"
          size="small"
          @change="selectedId = null"
        />
      </div>
    </div>

    <div v-if="storageUsage" class="storage-usage">
      <div class="storage-usage__info">
        <span>
          {{ t('images.storageUsage') }}:
          {{
            t('images.storageUsageDetail', {
              used: formatBytes(storageUsage.used_bytes),
              total: formatBytes(storageUsage.quota_bytes),
              percent: formatPercentage(storageUsage.used_pct),
            })
          }}
        </span>
      </div>
      <a-progress
        :percent="storageUsage.used_pct"
        :show-info="false"
        stroke-color="#1677ff"
        size="small"
      />
    </div>
  </div>
</template>

<style scoped>
.image-library-picker {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
}

.picker-toolbar {
  display: flex;
  gap: 12px;
  align-items: center;
}

.picker-content {
  flex: 1;
  overflow-y: auto;
  min-height: 360px;
  display: flex;
  flex-direction: column;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.image-item {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s;
}

.image-item:hover {
  border-color: #1677ff;
}

.image-item--selected {
  border-color: #1677ff;
  box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
  background: #e6f4ff;
}

.image-item__preview {
  aspect-ratio: 1;
  background: #f9fafb;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.image-item__preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-item__name {
  padding: 6px 8px;
  font-size: 11px;
  color: #4b5563;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.storage-usage {
  margin-top: auto;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.storage-usage__info {
  font-size: 11px;
  color: #6b7280;
  margin-bottom: 4px;
}
</style>
