<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import Select from 'primevue/select'
import { Check, PlayCircle, Sparkles, Star, Vote } from '@lucide/vue'

import Button from '../components/ui/Button.vue'
import Card from '../components/ui/Card.vue'
import PageHero from '../components/ui/PageHero.vue'
import { useAwardsStore } from '../stores/awards'
import { useAuthStore } from '../stores/auth'

const store = useAwardsStore()
const authStore = useAuthStore()
const selectedCategoryId = ref<number | null>(null)
const selectedCandidateId = ref<number | null>(null)
const submitting = ref(false)
const submitMessage = ref('')
const submitError = ref('')

onMounted(async () => {
  await store.loadHomeData()
  selectedCategoryId.value = store.categories.categories[0]?.id ?? null
})

const categoryOptions = computed(() =>
  store.categories.categories.map((category) => ({
    label: category.name,
    value: category.id,
  })),
)

const category = computed(() =>
  store.categories.categories.find((item) => item.id === selectedCategoryId.value) ?? store.categories.categories[0],
)

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

async function submitVote() {
  if (!category.value || !selectedCandidateId.value) return

  submitting.value = true
  submitMessage.value = ''
  submitError.value = ''

  try {
    const response = await store.submitVote({
      seasonId: store.categories.seasonId,
      twitchUserId: authStore.session?.twitchUserId ?? '',
      entries: [
        {
          categoryId: category.value.id,
          candidateId: selectedCandidateId.value,
        },
      ],
    })

    submitMessage.value = `Stimme gezählt! (Ballot #${response.ballotId}) Danke fürs Mitmachen. 💜`
  } catch (error) {
    submitError.value = error instanceof Error ? error.message : 'Ups – das hat nicht geklappt. Versuch es gleich nochmal.'
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="space-y-12 pb-16">
    <PageHero
      eyebrow="Schritt 2 · Voten"
      title="Jetzt zählt deine Stimme"
      description="Eine Stimme pro Kategorie – wähl mit Herz. Deine Wahl bleibt bis zum Ende der Voting-Phase jederzeit änderbar, also kein Stress."
      :icon="Vote"
    />

    <Card class="overflow-hidden p-0">
      <!-- Stepper -->
      <div class="flex items-center gap-4 border-b border-violet-100 px-7 py-5 text-xs font-semibold text-slate-400 sm:px-9">
        <span class="text-violet-600">1 · Kategorie</span>
        <span class="h-px flex-1 bg-slate-200" />
        <span class="text-violet-600">2 · Favorit wählen</span>
        <span class="h-px flex-1 bg-slate-200" />
        <span>3 · Stimme abgeben</span>
      </div>

      <div class="grid gap-8 p-7 sm:p-9 lg:grid-cols-[0.82fr_1.18fr]">
        <!-- Left -->
        <div class="space-y-5">
          <p v-if="!authStore.isLoggedIn" class="rounded-2xl border border-amber-200 bg-amber-50 px-5 py-4 text-sm text-amber-800">
            Logg dich kurz oben mit Twitch ein – dann zählt deine Stimme. 💜
          </p>

          <div class="space-y-2">
            <label class="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">Für welche Kategorie stimmst du?</label>
            <Select
              v-model="selectedCategoryId"
              :options="categoryOptions"
              option-label="label"
              option-value="value"
              class="w-full"
            />
          </div>

          <div v-if="category" class="relative overflow-hidden rounded-2xl bg-[linear-gradient(135deg,#ece2ff,#f6ecff_55%,#fff2dd)] p-6">
            <div class="absolute right-3 top-3 h-1 w-24 rounded-full bg-[linear-gradient(90deg,#c4b5fd,#f5d0fe,#fecdd3,#fde68a,#bbf7d0,#bae6fd)]" />
            <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-500">{{ category.groupName }}</p>
            <h2 class="mt-2 font-[Cormorant_Garamond] text-3xl text-violet-800">{{ category.name }}</h2>
            <p class="mt-2 text-sm leading-7 text-slate-600">{{ category.description }}</p>
          </div>

          <p class="flex items-start gap-2 rounded-2xl border border-violet-100 bg-white/70 px-5 py-4 text-sm text-slate-600">
            <Star class="mt-0.5 h-4 w-4 shrink-0 text-amber-400" />
            Nur eine Stimme zählt pro Kategorie – aber du darfst sie jederzeit umentscheiden.
          </p>
          <p class="flex items-start gap-2 rounded-2xl border border-violet-100 bg-white/70 px-5 py-4 text-sm text-slate-600">
            <PlayCircle class="mt-0.5 h-4 w-4 shrink-0 text-violet-500" />
            Schau dir die eingereichten Clips an, bevor du wählst – so siehst du, was jede:n in dieser Kategorie besonders macht.
          </p>
        </div>

        <!-- Right: candidate grid -->
        <div class="space-y-4">
          <div class="flex items-center justify-between">
            <h3 class="font-[Cormorant_Garamond] text-3xl text-violet-800">Die Nominierten</h3>
            <span class="rounded-full bg-violet-50 px-3 py-1 text-xs font-semibold text-violet-600">
              {{ category?.candidates.length ?? 0 }} im Rennen
            </span>
          </div>

          <div class="grid gap-3 sm:grid-cols-2">
            <label
              v-for="candidate in category?.candidates ?? []"
              :key="candidate.id"
              :class="[
                'group flex cursor-pointer items-center gap-3 rounded-2xl border px-4 py-3 transition',
                selectedCandidateId === candidate.id
                  ? 'border-violet-400 bg-violet-50 ring-2 ring-violet-200'
                  : 'border-violet-100 bg-white hover:border-violet-300 hover:bg-violet-50/40',
              ]"
            >
              <input v-model="selectedCandidateId" type="radio" :value="candidate.id" class="sr-only" />
              <span class="grid h-11 w-11 shrink-0 place-items-center self-start rounded-full bg-[linear-gradient(135deg,#c4b5fd,#f5a9d6)] text-sm font-semibold text-white">
                {{ candidate.displayName.charAt(0) }}
              </span>
              <div class="min-w-0 flex-1">
                <p class="truncate font-semibold text-slate-800">{{ candidate.displayName }}</p>
                <p class="truncate text-xs text-slate-500">{{ candidate.channelSlug }} · {{ candidate.platform }}</p>
                <a
                  v-if="candidate.clipUrl"
                  :href="candidate.clipUrl"
                  target="_blank"
                  rel="noopener"
                  class="mt-1.5 inline-flex items-center gap-1 text-xs font-semibold text-violet-600 hover:text-violet-800"
                  @click.stop
                >
                  <PlayCircle class="h-3.5 w-3.5" /> Clip ansehen
                </a>
              </div>
              <span
                :class="[
                  'grid h-6 w-6 shrink-0 place-items-center self-start rounded-full border transition',
                  selectedCandidateId === candidate.id ? 'border-violet-500 bg-violet-500 text-white' : 'border-violet-200 text-transparent',
                ]"
              >
                <Check class="h-3.5 w-3.5" />
              </span>
            </label>
          </div>

          <div class="flex flex-wrap items-center justify-between gap-4 rounded-2xl bg-[linear-gradient(135deg,#f6ecff,#fff2dd)] px-6 py-5">
            <div class="space-y-1">
              <p class="text-xs font-semibold uppercase tracking-[0.2em] text-violet-400">Deine Wahl</p>
              <p class="font-[Cormorant_Garamond] text-2xl text-violet-800">
                {{ selectedCandidate?.displayName ?? 'Noch nichts gewählt' }}
              </p>
              <p v-if="submitMessage" class="text-sm text-emerald-700">{{ submitMessage }}</p>
              <p v-if="submitError" class="text-sm text-rose-700">{{ submitError }}</p>
            </div>
            <Button class="gap-2" :disabled="submitting || !authStore.isLoggedIn || !selectedCandidateId" @click="submitVote">
              <Sparkles class="h-4 w-4" />
              {{ submitting ? 'Speichert ...' : 'Stimme abgeben' }}
            </Button>
          </div>
        </div>
      </div>
    </Card>
  </div>
</template>
