<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { usePagesStore } from '~/stores/pages'
import { useVariantsStore } from '~/stores/variants'

const route = useRoute()
const router = useRouter()
const pagesStore = usePagesStore()
const variantsStore = useVariantsStore()

const pageId = computed(() => String(route.params.id || ''))
const page = computed(() => pagesStore.pages.find((item) => item.id === pageId.value) ?? null)
const variants = computed(() => variantsStore.listByPage(pageId.value))
const hasPage = computed(() => page.value !== null)

const totalLeads = computed(() => variants.value.reduce((sum, item) => sum + item.leadCount, 0))
const totalTraffic = computed(() => variants.value.reduce((sum, item) => sum + item.trafficWeight, 0))

const newVariantName = ref('')
const newVariantDescription = ref('')
const newVariantWeight = ref(10)

const pageTitle = computed(() => {
  if (!page.value) {
    return ''
  }

  return `${page.value.name} 변형 관리`
})

const backToPages = () => {
  router.push('/admin/pages')
}

const toBuilder = () => {
  if (hasPage.value) {
    router.push(`/admin/pages/${pageId.value}/builder`)
  }
}

const createVariant = () => {
  const name = newVariantName.value.trim()
  if (!hasPage.value || name.length === 0) {
    return
  }

  variantsStore.createVariant({
    pageId: pageId.value,
    name,
    description: newVariantDescription.value,
    trafficWeight: Number(newVariantWeight.value) || 10
  })

  newVariantName.value = ''
  newVariantDescription.value = ''
  newVariantWeight.value = 10
}

const removeVariant = (variantId: string) => {
  variantsStore.removeVariant(pageId.value, variantId)
}

const toggleVariant = (variantId: string) => {
  variantsStore.toggleActive(pageId.value, variantId)
}
</script>

<template>
  <div class="space-y-5">
    <header class="rounded-xl border border-slate-700/80 bg-gradient-to-r from-slate-900 via-indigo-950/70 to-slate-900 px-5 py-4">
      <p class="text-xs uppercase tracking-[0.18em] text-cyan-300">페이지</p>
      <div class="mt-2 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 class="text-2xl font-bold text-slate-100">{{ hasPage ? pageTitle : '페이지를 찾을 수 없습니다' }}</h1>
          <p v-if="page" class="mt-1 text-sm text-slate-400">
            {{ page.domain }}{{ page.routePath }} · {{ page.leadCount }} 리드
          </p>
        </div>
        <div class="flex flex-wrap items-center gap-2">
          <button
            type="button"
            class="rounded-md border border-cyan-300/30 bg-cyan-500/10 px-3 py-1.5 text-sm font-semibold text-cyan-100 hover:bg-cyan-500/20"
            @click="toBuilder"
          >
            빌더 열기
          </button>
          <button
            type="button"
            class="rounded-md border border-slate-700 px-3 py-1.5 text-sm text-slate-300 hover:bg-slate-900"
            @click="backToPages"
          >
            페이지 목록
          </button>
        </div>
      </div>
    </header>

    <div v-if="!hasPage" class="rounded-xl border border-slate-800 bg-slate-900/70 px-6 py-8">
      <h2 class="text-xl font-bold text-slate-100">해당 페이지를 찾을 수 없습니다.</h2>
      <p class="mt-1 text-sm text-slate-300">ID가 변경되었거나 삭제된 페이지일 수 있습니다.</p>
      <button
        type="button"
        class="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="backToPages"
      >
        페이지 목록으로 이동
      </button>
    </div>

    <template v-else>
      <section class="grid gap-4 md:grid-cols-2">
        <article class="rounded-xl border border-slate-800 bg-slate-900/70 p-5">
          <h2 class="text-sm font-semibold text-slate-200">변형 메트릭</h2>
          <div class="mt-4 grid grid-cols-2 gap-3">
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">총 변형 수</p>
              <p class="mt-2 text-2xl font-black text-slate-100">{{ variants.length }}</p>
            </div>
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">누적 리드</p>
              <p class="mt-2 text-2xl font-black text-slate-100">{{ totalLeads }}</p>
            </div>
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">총 트래픽 비율</p>
              <p class="mt-2 text-2xl font-black text-slate-100">{{ totalTraffic }}%</p>
            </div>
          </div>
        </article>
        <article class="rounded-xl border border-slate-800 bg-slate-900/70 p-5">
          <h2 class="text-sm font-semibold text-slate-200">새 변형 추가</h2>
          <div class="mt-4 space-y-3">
            <label class="block space-y-2">
              <span class="text-xs font-medium text-slate-300">변형 이름</span>
              <input
                v-model="newVariantName"
                type="text"
                placeholder="예: 주말 자극형"
                class="w-full rounded-lg border border-indigo-400/30 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none"
              />
            </label>
            <label class="block space-y-2">
              <span class="text-xs font-medium text-slate-300">메모</span>
              <input
                v-model="newVariantDescription"
                type="text"
                placeholder="변형 설명"
                class="w-full rounded-lg border border-indigo-400/30 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none"
              />
            </label>
            <label class="block space-y-2">
              <span class="text-xs font-medium text-slate-300">트래픽 비율 (%)</span>
              <input
                v-model.number="newVariantWeight"
                type="number"
                min="1"
                max="100"
                class="w-full rounded-lg border border-indigo-400/30 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none"
              />
            </label>
            <button
              type="button"
              class="w-full rounded-lg bg-gradient-to-r from-indigo-600 to-cyan-500 px-4 py-2 text-sm font-semibold text-white"
              @click="createVariant"
            >
              변형 생성
            </button>
          </div>
        </article>
      </section>

      <section class="space-y-3">
        <div class="rounded-xl border border-slate-800 bg-slate-900/70 px-4 py-3 text-sm font-semibold text-slate-100">
          등록 변형 목록
        </div>
        <article
          v-for="variant in variants"
          :key="variant.id"
          class="rounded-xl border border-slate-800 bg-slate-900/70 p-5"
        >
          <div class="flex flex-wrap items-start justify-between gap-2">
            <div>
              <h3 class="text-lg font-bold text-slate-100">{{ variant.name }}</h3>
              <p class="mt-1 text-sm text-slate-400">{{ variant.description || '메모 없음' }}</p>
            </div>
            <button
              type="button"
              @click="toggleVariant(variant.id)"
              :class="variant.isActive ? 'bg-emerald-500/20 text-emerald-100' : 'bg-slate-700 text-slate-300'"
              class="rounded-md border border-slate-700 px-3 py-1.5 text-xs font-semibold"
            >
              {{ variant.isActive ? '활성' : '비활성' }}
            </button>
          </div>
          <div class="mt-3 grid gap-3 md:grid-cols-3">
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">상태</p>
              <p class="mt-1 text-base font-semibold text-slate-100">
                {{ variant.isActive ? '노출' : '중단' }}
              </p>
            </div>
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">트래픽 비율</p>
              <p class="mt-1 text-base font-semibold text-slate-100">{{ variant.trafficWeight }}%</p>
            </div>
            <div class="rounded-lg border border-slate-700 bg-slate-950/60 p-3">
              <p class="text-xs text-slate-400">리드 수</p>
              <p class="mt-1 text-base font-semibold text-slate-100">{{ variant.leadCount }}</p>
            </div>
          </div>
          <div class="mt-4 flex justify-end">
            <button
              type="button"
              class="rounded-md border border-red-300/40 bg-red-900/20 px-3 py-1.5 text-sm text-red-100"
              @click="removeVariant(variant.id)"
            >
              삭제
            </button>
          </div>
        </article>
      </section>
    </template>
  </div>
</template>
