<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { usePagesStore, type PageStatus, type PageSortBy } from '~/stores/pages'
import { useVariantsStore } from '~/stores/variants'
import CreatePageModal from '~/components/admin/CreatePageModal.vue'
import { useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const pagesStore = usePagesStore()
const variantsStore = useVariantsStore()
const { filteredPages, searchQuery, campaignFilter, statusFilter, sortBy, campaignOptions } = storeToRefs(pagesStore)
const pages = computed(() =>
  filteredPages.value.map((page) => ({
    ...page,
    variantCount: variantsStore.countByPage(page.id)
  }))
)
const showCreatePage = ref(false)

const initialCampaign = computed(() => {
  const value = route.query.campaignId
  if (typeof value === 'string' && value.length > 0) {
    return value
  }

  return 'all'
})

watch(
  () => initialCampaign.value,
  (next) => {
    pagesStore.setCampaignFilter(next)
  },
  { immediate: true }
)

const statusOptions = [
  { value: 'all', label: '전체' },
  { value: 'live', label: '라이브' },
  { value: 'draft', label: '초안' },
  { value: 'paused', label: '일시정지' }
] as const

const sortOptions: Array<{ value: PageSortBy; label: string }> = [
  { value: 'updated', label: '최근 수정순' },
  { value: 'name', label: '이름 오름차순' },
  { value: 'leads', label: '리드' },
  { value: 'visitors', label: '방문자' },
  { value: 'variants', label: '변형 수' }
]

const campaignItems = computed(() => [
  { value: 'all', label: '전체 캠페인' },
  ...campaignOptions.value.map((campaign) => ({
    value: campaign.id,
    label: campaign.name
  }))
])

const statusLabel = (status: PageStatus) => {
  const { label } = pagesStore.statusClass(status)
  return label
}

const statusClass = (status: PageStatus) => {
  const { chipClass } = pagesStore.statusClass(status)
  return chipClass
}

const statusDotClass = (status: PageStatus) => {
  const { dotClass } = pagesStore.statusClass(status)
  return dotClass
}

const openCreatePage = () => {
  showCreatePage.value = true
}

const closeCreatePage = () => {
  showCreatePage.value = false
}

const submitCreatePage = (payload: { name: string; campaignId: string; domain: string; routePath: string }) => {
  pagesStore.createPage(payload)
  showCreatePage.value = false
}

const openBuilder = (pageId: string) => {
  router.push(`/admin/pages/${pageId}/builder`)
}

const onDelete = (pageId: string) => {
  pagesStore.removePage(pageId)
}

const campaignLabel = (campaignId: string) => pagesStore.campaignName(campaignId)

const pageUrl = (domain: string, routePath: string) => `https://${domain}${routePath}`
</script>

<template>
  <div class="space-y-5">
    <header class="rounded-xl border border-slate-700/80 bg-gradient-to-r from-slate-900 via-slate-900 to-indigo-950/70 px-5 py-4 shadow-[0_16px_40px_rgba(0,0,0,0.35)]">
      <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
          <p class="text-sm text-slate-400">홈 <span class="px-2">></span> 페이지</p>
          <h1 class="mt-1 text-3xl font-black tracking-tight text-slate-100">페이지 관리</h1>
          <p class="mt-1 text-sm text-slate-400">캠페인 기준으로 페이지를 관리하고 운영하세요.</p>
        </div>
        <button
          type="button"
          @click="openCreatePage"
          class="rounded-xl bg-gradient-to-r from-indigo-500 to-cyan-500 px-5 py-2.5 text-base font-semibold text-white shadow-lg shadow-cyan-950/40 transition hover:from-indigo-400 hover:to-cyan-400"
        >
          + 새 페이지 만들기
        </button>
      </div>
    </header>

    <section class="rounded-2xl border border-indigo-400/20 bg-gradient-to-br from-slate-900/80 via-slate-950 to-slate-900/90 p-5 shadow-[0_12px_30px_rgba(0,0,0,0.3)]">
      <div class="flex flex-nowrap items-end justify-between gap-4">
        <label class="min-w-0 space-y-2">
          <span class="px-1 text-xs font-semibold tracking-[0.12em] text-cyan-200">검색</span>
          <div class="relative">
            <span class="pointer-events-none absolute inset-y-0 left-3 flex items-center text-cyan-300">⌕</span>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="페이지명, 도메인, 경로로 검색"
              class="w-full min-w-[520px] rounded-xl border border-indigo-500/20 bg-slate-950/80 px-9 py-3 text-sm text-slate-100 outline-none ring-0 transition focus:border-cyan-400 focus:shadow-[0_0_0_1px_rgba(103,232,249,0.35)]"
            />
          </div>
        </label>
        <div class="ml-auto flex shrink-0 items-end gap-3">
          <label class="flex flex-col space-y-2">
            <span class="px-1 text-xs font-semibold tracking-[0.12em] text-cyan-200">캠페인</span>
            <select
              v-model="campaignFilter"
              class="shrink-0 rounded-xl border border-indigo-500/25 bg-slate-950/80 px-5 py-3 text-sm font-medium text-slate-200 outline-none transition hover:border-cyan-400"
            >
              <option
                v-for="campaign in campaignItems"
                :key="campaign.value"
                :value="campaign.value"
              >
                {{ campaign.label }}
              </option>
            </select>
          </label>
          <label class="flex flex-col space-y-2">
            <span class="px-1 text-xs font-semibold tracking-[0.12em] text-cyan-200">상태</span>
            <select
              v-model="statusFilter"
              class="shrink-0 rounded-xl border border-indigo-500/25 bg-slate-950/80 px-5 py-3 text-sm font-medium text-slate-200 outline-none transition hover:border-cyan-400"
            >
              <option v-for="status in statusOptions" :key="status.value" :value="status.value">
                {{ status.label }}
              </option>
            </select>
          </label>
          <label class="flex flex-col space-y-2">
            <span class="px-1 text-xs font-semibold tracking-[0.12em] text-cyan-200">정렬</span>
            <select
              v-model="sortBy"
              class="shrink-0 rounded-xl border border-indigo-500/25 bg-slate-950/80 px-5 py-3 text-sm font-medium text-slate-200 outline-none transition hover:border-cyan-400"
            >
              <option v-for="option in sortOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </option>
            </select>
          </label>
        </div>
      </div>
    </section>

    <section class="space-y-4">
      <article
        v-for="page in pages"
        :key="page.id"
        class="relative overflow-hidden rounded-2xl border border-slate-800 bg-gradient-to-b from-slate-900/95 to-slate-950/95 p-5 shadow-lg shadow-black/20 transition hover:-translate-y-0.5 hover:border-cyan-300/40"
      >
        <div class="flex items-start justify-between gap-2">
          <div>
            <h2 class="text-xl font-bold text-slate-100">{{ page.name }}</h2>
            <p class="mt-1 text-sm text-slate-400">{{ campaignLabel(page.campaignId) }}</p>
            <p class="mt-1 text-sm text-slate-300">
              {{ pageUrl(page.domain, page.routePath) }}
            </p>
          </div>
          <span class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 font-semibold tracking-[0.08em]" :class="statusClass(page.status)" style="font-size: 9px; line-height: 1.1;">
            <span class="h-1.5 w-1.5 rounded-full" :class="statusDotClass(page.status)" />
            {{ statusLabel(page.status) }}
          </span>
        </div>

        <div class="mt-4 grid grid-cols-4 gap-3">
          <div class="rounded-xl border border-slate-800 bg-slate-950/80 p-3">
            <p class="text-xs tracking-wider text-slate-400">도메인</p>
            <p class="mt-1 text-lg font-bold text-slate-100">{{ page.domain }}</p>
          </div>
          <div class="rounded-xl border border-slate-800 bg-slate-950/80 p-3">
            <p class="text-xs tracking-wider text-slate-400">리드</p>
            <p class="mt-1 text-lg font-bold text-slate-100">{{ page.leadCount }}</p>
          </div>
          <div class="rounded-xl border border-slate-800 bg-slate-950/80 p-3">
            <p class="text-xs tracking-wider text-slate-400">방문자</p>
            <p class="mt-1 text-lg font-bold text-slate-100">{{ page.visitorCount }}</p>
          </div>
          <div class="rounded-xl border border-slate-800 bg-slate-950/80 p-3">
            <p class="text-xs tracking-wider text-slate-400">변형</p>
            <p class="mt-1 text-lg font-bold text-slate-100">{{ page.variantCount }}</p>
          </div>
        </div>

        <div class="mt-4 flex items-center justify-between border-t border-slate-700/60 pt-4">
          <p class="text-sm text-slate-400">마지막 수정: {{ new Date(page.updatedAt).toLocaleString() }}</p>
          <div class="flex items-center gap-2">
            <button
              type="button"
              class="rounded-md border border-slate-700/80 bg-slate-900 px-3 py-1.5 text-sm text-slate-200 transition hover:bg-slate-800/70"
            >
              미리보기
            </button>
            <NuxtLink
              :to="`/admin/pages/${page.id}/variants`"
              class="rounded-md border border-indigo-400/40 bg-indigo-950/50 px-3 py-1.5 text-sm text-indigo-100 transition hover:bg-indigo-900/50"
            >
              변형 관리
            </NuxtLink>
            <button
              type="button"
              @click="openBuilder(page.id)"
              class="rounded-md bg-gradient-to-r from-indigo-600 to-cyan-500 px-3 py-1.5 text-sm font-medium text-white hover:from-indigo-500 hover:to-cyan-400"
            >
              빌더 열기
            </button>
            <button
              type="button"
              @click="onDelete(page.id)"
              class="rounded-md border border-red-300/30 bg-red-900/30 px-3 py-1.5 text-sm text-red-100 transition hover:bg-red-900/50"
            >
              삭제
            </button>
          </div>
        </div>
      </article>

      <article class="flex min-h-[220px] items-center justify-center rounded-2xl border border-dashed border-cyan-300/30 bg-gradient-to-b from-slate-900 to-indigo-950/60 p-5">
        <div class="text-center">
          <div class="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gradient-to-r from-indigo-400/20 to-cyan-400/20 text-2xl text-cyan-200">+</div>
          <p class="text-2xl font-bold text-slate-100">페이지가 없습니다</p>
          <p class="mt-2 text-slate-400">필터를 조정하거나 새 페이지를 먼저 만들어보세요.</p>
          <button
            type="button"
            class="mx-auto mt-4 rounded-md bg-gradient-to-r from-indigo-600 to-cyan-500 px-4 py-2 text-sm font-semibold text-white"
            @click="openCreatePage"
          >
            바로 만들기
          </button>
        </div>
      </article>
    </section>

    <CreatePageModal
      v-if="showCreatePage"
      :campaigns="campaignOptions"
      @close="closeCreatePage"
      @submit="submitCreatePage"
    />
  </div>
</template>
