<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import Select from 'primevue/select'
import { Film, Link as LinkIcon, Sparkles, Star } 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 clipUrl = ref('')
const title = ref('')
const creator = ref('')
const submitting = ref(false)
const submitMessage = ref('')
const submitError = ref('')

onMounted(async () => {
  await store.loadHomeData()
  const clipCategory = store.categories.categories.find((c) => /clip/i.test(c.name))
  selectedCategoryId.value = clipCategory?.id ?? store.categories.categories[0]?.id ?? null
})

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

const platform = computed(() => {
  const url = clipUrl.value.trim().toLowerCase()
  if (!url) return null
  if (url.includes('twitch.tv') || url.includes('clips.twitch.tv')) return 'Twitch'
  if (url.includes('youtube.com') || url.includes('youtu.be')) return 'YouTube'
  return 'unknown'
})

const urlValid = computed(() => platform.value === 'Twitch' || platform.value === 'YouTube')

async function submitClip() {
  if (!urlValid.value) {
    submitError.value = 'Bitte gib einen gültigen Twitch- oder YouTube-Link an.'
    return
  }

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

  try {
    await store.submitClip({
      year: store.categories.year,
      categoryId: selectedCategoryId.value,
      twitchUserId: authStore.session?.twitchUserId ?? '',
      clipUrl: clipUrl.value.trim(),
      title: title.value.trim(),
      creator: creator.value.trim(),
    })

    submitMessage.value = 'Clip eingereicht! Das Team schaut ihn sich an. Danke fürs Teilen. 💜'
    clipUrl.value = ''
    title.value = ''
    creator.value = ''
  } 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="Clip des Jahres"
      title="Reich deinen Clip ein"
      description="Der eine Moment, den die Community sehen muss? Teil den Link zu deinem Lieblings-Clip – wir kümmern uns um den Rest."
      :icon="Film"
    />

    <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 · Link einfügen</span>
        <span class="h-px flex-1 bg-slate-200" />
        <span class="text-violet-600">2 · Details</span>
        <span class="h-px flex-1 bg-slate-200" />
        <span>3 · Einreichen</span>
      </div>

      <div class="grid gap-8 p-7 sm:p-9 lg:grid-cols-[1.1fr_0.9fr]">
        <!-- Left: form -->
        <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 Einreichung. 💜
          </p>

          <div class="space-y-2">
            <label class="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">Clip-Link (Twitch oder YouTube)</label>
            <div class="flex items-center gap-2 rounded-2xl border bg-white px-4 py-3 transition"
              :class="clipUrl && !urlValid ? 'border-rose-300' : 'border-violet-200'">
              <LinkIcon class="h-4 w-4 shrink-0 text-violet-400" />
              <input
                v-model="clipUrl"
                type="url"
                class="w-full bg-transparent text-sm outline-none"
                placeholder="https://clips.twitch.tv/… oder https://youtu.be/…"
              />
              <span v-if="urlValid" class="shrink-0 rounded-full bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold text-emerald-600">{{ platform }}</span>
            </div>
            <p v-if="clipUrl && !urlValid" class="text-xs text-rose-500">Das sieht nicht nach einem Twitch- oder YouTube-Link aus.</p>
          </div>

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

          <div class="grid gap-4 sm:grid-cols-2">
            <div class="space-y-2">
              <label class="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">Titel (optional)</label>
              <input v-model="title" type="text" class="w-full rounded-2xl border border-violet-200 bg-white px-4 py-3 text-sm" placeholder="Worum geht's im Clip?" />
            </div>
            <div class="space-y-2">
              <label class="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">VTuber im Clip (optional)</label>
              <input v-model="creator" type="text" class="w-full rounded-2xl border border-violet-200 bg-white px-4 py-3 text-sm" placeholder="Name oder @handle" />
            </div>
          </div>

          <p v-if="submitMessage" class="rounded-2xl border border-emerald-200 bg-emerald-50 px-5 py-4 text-sm text-emerald-700">{{ submitMessage }}</p>
          <p v-if="submitError" class="rounded-2xl border border-rose-200 bg-rose-50 px-5 py-4 text-sm text-rose-700">{{ submitError }}</p>

          <Button class="w-full gap-2" :disabled="submitting || !authStore.isLoggedIn || !urlValid" @click="submitClip">
            <Film class="h-4 w-4" />
            {{ submitting ? 'Reicht ein ...' : 'Clip einreichen' }}
          </Button>
        </div>

        <!-- Right: preview / rules -->
        <div class="space-y-4">
          <div 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">Vorschau</p>
            <div class="mt-3 grid aspect-video place-items-center rounded-xl bg-white/60">
              <Film class="h-10 w-10 text-violet-400" />
            </div>
            <p class="mt-3 truncate text-sm font-semibold text-violet-800">{{ title || 'Dein Clip-Titel' }}</p>
            <p class="truncate text-xs text-slate-500">{{ creator || 'VTuber im Clip' }} · {{ platform && urlValid ? platform : 'Link einfügen' }}</p>
          </div>

          <div class="rounded-2xl bg-violet-50/50 px-5 py-4 text-xs leading-6 text-slate-500">
            <p class="flex items-center gap-2"><Star class="h-3.5 w-3.5 text-amber-400" /> Twitch-Clips oder YouTube-Links werden akzeptiert.</p>
            <p class="flex items-center gap-2"><Star class="h-3.5 w-3.5 text-amber-400" /> Mehrere Clips? Einfach nacheinander einreichen.</p>
            <p class="flex items-center gap-2"><Sparkles class="h-3.5 w-3.5 text-amber-400" /> Das Team prüft jede Einreichung vor der Voting-Phase.</p>
          </div>
        </div>
      </div>
    </Card>
  </div>
</template>
