<template>
  <div class="relative min-h-screen overflow-hidden bg-[#f5f5f5] px-4 py-10 font-sans text-[#0c0a09] md:px-8 md:py-16">
    <div
      class="pointer-events-none absolute left-1/2 top-8 h-[460px] w-[min(92vw,820px)] -translate-x-1/2 rounded-[48px] bg-[radial-gradient(circle_at_20%_30%,rgba(196,184,232,0.6),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(244,197,168,0.5),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(167,229,211,0.56),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full max-w-[720px] gap-8" aria-labelledby="criar-title">
      <header class="flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <p
            class="m-0 inline-flex rounded-full bg-[rgba(196,184,232,0.6)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Catálogo
          </p>
          <h1 id="criar-title"
            class="my-5 max-w-[720px] font-serif text-[40px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] md:text-[48px]">
            Novo jogo
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Preencha os dados para adicionar um jogo ao catálogo.
          </p>
        </div>
      </header>

      <form
        class="grid gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-6 shadow-[0_4px_16px_rgba(0,0,0,0.04)] md:p-8"
        aria-label="Formulário de criação de jogo" @submit.prevent="submitForm">
        <div>
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(196,184,232,0.4)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Informações
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            Dados do jogo
          </h2>
        </div>

        <div v-if="formError"
          class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-[15px] leading-[1.47] tracking-[0.15px] text-red-700"
          role="alert">
          {{ formError }}
        </div>

        <div class="grid gap-5">
          <div class="grid gap-1.5">
            <label for="title" class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
              Título <span class="text-red-500">*</span>
            </label>
            <input id="title" v-model="form.title" type="text" placeholder="Ex: Counter-Strike 2" required
              class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
          </div>

          <div class="grid gap-1.5">
            <label for="description"
              class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
              Descrição <span class="text-red-500">*</span>
            </label>
            <textarea id="description" v-model="form.description" rows="3" placeholder="Descreva o jogo..." required
              class="w-full resize-none rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white"></textarea>
          </div>

          <div class="grid gap-1.5">
            <label for="developer"
              class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
              Developer <span class="text-red-500">*</span>
            </label>
            <input id="developer" v-model="form.developer" type="text" placeholder="Ex: Valve" required
              class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
          </div>

          <div class="grid gap-5 md:grid-cols-2">
            <div class="grid gap-1.5">
              <label for="genres"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Gêneros <span class="text-red-500">*</span>
              </label>
              <input id="genres" v-model="form.genresRaw" type="text" placeholder="Ex: FPS, Ação, Multiplayer" required
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
              <p class="text-xs leading-[1.4] text-[#777169]">Separe com vírgula</p>
            </div>

            <div class="grid gap-1.5">
              <label for="platforms"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Plataformas <span class="text-red-500">*</span>
              </label>
              <input id="platforms" v-model="form.platformsRaw" type="text" placeholder="Ex: PC, PlayStation 5" required
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
              <p class="text-xs leading-[1.4] text-[#777169]">Separe com vírgula</p>
            </div>
          </div>
        </div>

        <div class="border-t border-[#e7e5e4] pt-5">
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(196,184,232,0.4)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Imagens
          </span>
          <p class="mb-4 mt-3 text-[13px] leading-[1.5] text-[#777169]">
            Opcional — URLs públicas das imagens do jogo.
          </p>

          <div class="grid gap-5 md:grid-cols-2">
            <div class="grid gap-1.5">
              <label for="thumbnail"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Thumbnail URL
              </label>
              <input id="thumbnail" v-model="form.thumbnail" type="url" placeholder="https://..."
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
            </div>

            <div class="grid gap-1.5">
              <label for="header"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">
                Header URL
              </label>
              <input id="header" v-model="form.header" type="url" placeholder="https://..."
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
            </div>
          </div>
        </div>

        <div class="border-t border-[#e7e5e4] pt-5">
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(196,184,232,0.4)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Requisitos de sistema
          </span>
          <p class="mb-4 mt-3 text-[13px] leading-[1.5] text-[#777169]">Opcional.</p>

          <div class="grid gap-5 md:grid-cols-3">
            <div class="grid gap-1.5">
              <label for="cpu"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">CPU</label>
              <input id="cpu" v-model="form.cpu" type="text" placeholder="Ex: Intel i5-8400"
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
            </div>
            <div class="grid gap-1.5">
              <label for="gpu"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">GPU</label>
              <input id="gpu" v-model="form.gpu" type="text" placeholder="Ex: GTX 1060"
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
            </div>
            <div class="grid gap-1.5">
              <label for="ram"
                class="text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#777169]">RAM</label>
              <input id="ram" v-model="form.ram" type="text" placeholder="Ex: 8 GB"
                class="w-full rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-2.5 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09] focus:bg-white" />
            </div>
          </div>
        </div>

        <div class="flex items-center gap-3 border-t border-[#e7e5e4] pt-5">
          <input id="active" v-model="form.active" type="checkbox"
            class="h-4 w-4 rounded border-[#d6d3d1] accent-[#292524]" />
          <label for="active" class="text-[15px] leading-[1.47] tracking-[0.15px] text-[#0c0a09]">
            Jogo ativo no catálogo
          </label>
        </div>

        <div class="flex justify-end gap-3 border-t border-[#e7e5e4] pt-5">
          <NuxtLink to="/catalogo"
            class="inline-flex h-10 items-center justify-center rounded-full border border-[#d6d3d1] bg-transparent px-5 text-[15px] font-medium leading-none text-[#0c0a09] transition hover:border-[#0c0a09]">
            Cancelar
          </NuxtLink>
          <button type="submit" :disabled="isSubmitting"
            class="inline-flex h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-5 text-[15px] font-medium leading-none text-white transition hover:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70">
            <Icon v-if="isSubmitting" name="mdi:loading" class="animate-spin text-base" />
            <span>{{ isSubmitting ? 'Salvando...' : 'Salvar jogo' }}</span>
          </button>
        </div>
      </form>
    </main>
  </div>
</template>

<script setup>
definePageMeta({
  middleware: 'auth',
  layout: 'protected'
})

const CATALOG_API_BASE_URL = 'https://catalogo-jogos-sd-production.up.railway.app'

const { $toast } = useNuxtApp()

const token = useCookie('token', {
  secure: true,
  sameSite: 'lax',
  maxAge: 900
})

const isSubmitting = ref(false)
const formError = ref('')

const form = reactive({
  title: '',
  description: '',
  developer: '',
  genresRaw: '',
  platformsRaw: '',
  thumbnail: '',
  header: '',
  cpu: '',
  gpu: '',
  ram: '',
  active: true
})

const clearToken = () => {
  token.value = null
}

async function submitForm() {
  formError.value = ''

  const genres = form.genresRaw
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)
  const platforms = form.platformsRaw
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)

  if (!form.title || !form.description || !form.developer || !genres.length || !platforms.length) {
    formError.value = 'Preencha todos os campos obrigatórios.'
    return
  }

  if (!token.value) {
    await navigateTo('/login')
    return
  }

  isSubmitting.value = true

  const body = {
    title: form.title,
    description: form.description,
    developer: form.developer,
    genres,
    platforms,
    active: form.active
  }

  if (form.thumbnail || form.header) {
    body.images = {}
    if (form.thumbnail) body.images.thumbnail = form.thumbnail
    if (form.header) body.images.header = form.header
  }

  if (form.cpu || form.gpu || form.ram) {
    body.system_requirements = {}
    if (form.cpu) body.system_requirements.cpu = form.cpu
    if (form.gpu) body.system_requirements.gpu = form.gpu
    if (form.ram) body.system_requirements.ram = form.ram
  }

  try {
    await $fetch(`${CATALOG_API_BASE_URL}/api/v1/catalog/games`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token.value}` },
      body
    })
    $toast.success(`${form.title} adicionado ao catálogo!`, { duration: 5000 })
    await navigateTo('/catalogo')
  } catch (error) {
    const statusCode = error?.statusCode ?? error?.response?.status ?? error?.data?.statusCode

    if (statusCode === 401) {
      clearToken()
      $toast.error('Sua sessão expirou. Faça login novamente.', { duration: 8000 })
      await navigateTo('/login')
      return
    }

    formError.value =
      error?.data?.message ?? 'Erro ao criar o jogo. Verifique os dados e tente novamente.'
    $toast.error(formError.value, { duration: 8000 })
  } finally {
    isSubmitting.value = false
  }
}
</script>
