<template>
  <Modal
    :open="category !== null"
    :title="category ? `${category.categoryName} Leaderboard` : 'Leaderboard'"
    :subtitle="category ? `${category.groupName} · ${viewerRangeLabel(category.viewerRangeMin, category.viewerRangeMax)}` : undefined"
    size="xl"
    @close="closeAll"
  >
    <template v-if="category">
      <div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
        <div class="rounded-2xl border border-violet-100 bg-violet-50/40 px-4 py-3">
          <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Votes</p>
          <strong class="mt-1 block text-xl text-slate-950">{{ category.voteCount.toLocaleString('de-DE') }}</strong>
        </div>
        <div class="rounded-2xl border border-violet-100 bg-violet-50/40 px-4 py-3">
          <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Kandidaten</p>
          <strong class="mt-1 block text-xl text-slate-950">{{ category.candidateCount }}</strong>
        </div>
        <div class="rounded-2xl border border-violet-100 bg-violet-50/40 px-4 py-3">
          <p class="text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500">Reviews</p>
          <strong class="mt-1 block text-xl text-slate-950">{{ category.openReviewCount }}</strong>
        </div>
      </div>

      <div class="mt-5 overflow-hidden rounded-2xl border border-violet-100">
        <div class="hidden grid-cols-[72px_minmax(220px,1.5fr)_120px_120px_240px] gap-3 bg-violet-50/70 px-4 py-3 text-[10px] font-bold uppercase tracking-[0.14em] text-slate-500 lg:grid">
          <span>Rang</span>
          <span>Kandidat</span>
          <span>Votes</span>
          <span>Anteil</span>
          <span>Status</span>
        </div>

        <div v-if="category.leaderboard.length > 0" class="divide-y divide-violet-100 bg-white">
          <article
            v-for="(candidate, index) in category.leaderboard"
            :key="candidate.candidateId"
            class="grid gap-3 px-4 py-4 lg:grid-cols-[72px_minmax(220px,1.5fr)_120px_120px_240px] lg:items-center"
          >
            <div class="flex items-center gap-3 lg:block">
              <span class="grid h-9 w-9 place-items-center rounded-xl bg-violet-100 text-sm font-black text-violet-800">{{ index + 1 }}</span>
              <span v-if="candidate.isTopTie" class="rounded-full bg-amber-50 px-2 py-1 text-[11px] font-semibold text-amber-700 lg:hidden">Tie</span>
            </div>

            <div class="min-w-0">
              <p class="truncate text-base font-bold text-slate-900">{{ candidate.displayName }}</p>
              <p class="mt-0.5 truncate text-sm text-slate-500">{{ candidate.channelSlug }} · {{ candidate.platform }}</p>
            </div>

            <p class="text-sm font-bold text-slate-900">
              <span class="lg:hidden text-slate-500">Votes: </span>{{ candidate.votes.toLocaleString('de-DE') }}
            </p>

            <p class="text-sm font-bold text-violet-800">
              <span class="lg:hidden text-slate-500">Anteil: </span>{{ candidate.voteSharePercent }}%
            </p>

            <div class="flex flex-wrap items-center gap-2 lg:flex-nowrap lg:justify-between">
              <div class="flex flex-wrap gap-2">
                <span v-if="candidate.isCurrentWinner" class="rounded-full bg-emerald-50 px-3 py-1 text-[11px] font-semibold text-emerald-700">
                  Gewinner
                </span>
                <span v-if="candidate.isTopTie" class="hidden rounded-full bg-amber-50 px-3 py-1 text-[11px] font-semibold text-amber-700 lg:inline-flex">
                  Tie
                </span>
                <span class="rounded-full px-3 py-1 text-[11px] font-semibold" :class="candidate.hasClip ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'">
                  {{ candidate.hasClip ? 'Clip da' : 'Clip fehlt' }}
                </span>
                <span v-if="candidate.hasWinnerConflict" class="rounded-full bg-amber-50 px-3 py-1 text-[11px] font-semibold text-amber-700">
                  Regelkonflikt
                </span>
                <span v-if="!candidate.isAccepted" class="rounded-full bg-slate-100 px-3 py-1 text-[11px] font-semibold text-slate-600">
                  nicht final
                </span>
              </div>
              <Button variant="ghost" size="sm" class="gap-1.5 whitespace-nowrap" @click="openCandidateDetails(candidate.candidateId)">
                <Eye class="h-4 w-4" />
                Details
              </Button>
            </div>
          </article>
        </div>

        <div v-else class="bg-white px-4 py-12 text-center text-sm text-slate-500">
          Noch keine Votes oder keine Kandidaten in dieser Unterkategorie.
        </div>
      </div>
    </template>
  </Modal>

  <AdminVotingCandidateDetailModal
    :open="selectedCandidateId !== null"
    :category-name="category?.categoryName ?? ''"
    :group-name="category?.groupName ?? ''"
    :rank="selectedCandidateRankIndex"
    :candidate="selectedCandidate"
    :leaderboard-entry="selectedCandidateRank"
    @close="selectedCandidateId = null"
  />
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Eye } from '@lucide/vue'

import type { AdminCandidateItem } from '../../types/awards'
import AdminVotingCandidateDetailModal from './AdminVotingCandidateDetailModal.vue'
import Modal from '../ui/Modal.vue'
import Button from '../ui/Button.vue'
import type { AdminVotingWorkspaceRow } from './useAdminVotingManager'

const props = defineProps<{
  category: AdminVotingWorkspaceRow | null
  candidates: AdminCandidateItem[]
}>()

const emit = defineEmits<{
  close: []
}>()

const selectedCandidateId = ref<number | null>(null)

const selectedCandidate = computed(() =>
  props.candidates.find((candidate) => candidate.id === selectedCandidateId.value) ?? null,
)

const selectedCandidateRank = computed(() =>
  props.category?.leaderboard.find((candidate) => candidate.candidateId === selectedCandidateId.value) ?? null,
)

const selectedCandidateRankIndex = computed(() => {
  if (!props.category || selectedCandidateId.value === null) return null
  const index = props.category.leaderboard.findIndex((candidate) => candidate.candidateId === selectedCandidateId.value)
  return index >= 0 ? index + 1 : null
})

watch(() => props.category?.categoryId ?? null, () => {
  selectedCandidateId.value = null
})

function openCandidateDetails(candidateId: number) {
  selectedCandidateId.value = candidateId
}

function closeAll() {
  selectedCandidateId.value = null
  emit('close')
}

function viewerRangeLabel(min: number | null, max: number | null) {
  if (min === null && max === null) return 'Offene Einordnung'
  if (min !== null && max === null) return `Ab ${min} Viewer`
  if (min === null && max !== null) return `Bis ${max} Viewer`
  return `${min} bis ${max} Viewer`
}
</script>
