<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(232,184,196,0.55),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(168,200,232,0.56),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(167,229,211,0.58),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full max-w-[960px] gap-8" aria-labelledby="perfil-gamer-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(232,184,196,0.55)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Perfil
          </p>
          <h1 id="perfil-gamer-title"
            class="my-5 max-w-[720px] font-serif text-[40px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] md:text-[48px]">
            Perfil Gamer
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Gerencie seu apelido, bio, país e preferências de plataformas e jogos.
          </p>
        </div>
      </header>

      <section
        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 do perfil gamer">
        <div>
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(168,200,232,0.56)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            {{ modeLabel }}
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            {{ modeTitle }}
          </h2>
        </div>

        <div v-if="isLoading" class="grid gap-3" role="status" aria-live="polite">
          <div v-for="item in 5" :key="item" class="h-12 animate-pulse rounded-xl bg-[#f0efed]"></div>
        </div>

        <div v-else-if="errorMessage"
          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">
          {{ errorMessage }}
        </div>

        <form v-else class="grid gap-5" @submit.prevent="salvarPerfil">
          <div class="grid gap-2">
            <label for="nickname" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
              Nickname
            </label>
            <input id="nickname" v-model="form.nickname" type="text" required maxlength="80"
              class="h-11 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
              placeholder="Seu apelido no GameVerse" />
          </div>

          <div class="grid gap-2">
            <label for="bio" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
              Bio
            </label>
            <textarea id="bio" v-model="form.bio" rows="4"
              class="rounded-xl border border-[#e7e5e4] px-4 py-3 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
              placeholder="Conte um pouco sobre você como jogador"></textarea>
          </div>

          <div class="grid gap-2">
            <label for="country" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
              País
            </label>
            <input id="country" v-model="form.country" type="text" maxlength="80"
              class="h-11 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
              placeholder="Brasil" />
          </div>

          <div class="grid gap-2">
            <label for="platforms" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
              Plataformas favoritas
            </label>
            <input id="platforms" v-model="form.platformsText" type="text"
              class="h-11 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
              placeholder="Steam, Epic Games, PlayStation" />
            <p class="m-0 text-xs text-[#777169]">Separe por vírgula.</p>
          </div>

          <div class="grid gap-2">
            <label for="games" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
              Jogos favoritos
            </label>
            <input id="games" v-model="form.gamesText" type="text"
              class="h-11 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
              placeholder="Valorant, Elden Ring, Hades" />
            <p class="m-0 text-xs text-[#777169]">Separe por vírgula.</p>
          </div>

          <div v-if="perfil?.avatar" class="grid gap-2">
            <span class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">Avatar atual</span>
            <img :src="perfil.avatar" alt="Avatar do perfil gamer"
              class="h-20 w-20 rounded-full border border-[#e7e5e4] object-cover" />
          </div>

          <div class="flex flex-wrap gap-3 pt-2">
            <button type="submit" :disabled="isSaving"
              class="inline-flex h-10 items-center justify-center gap-2 rounded-full bg-[#292524] px-6 text-[15px] font-medium text-white transition hover:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70">
              <Icon v-if="isSaving" name="mdi:loading" class="animate-spin text-base" />
              <span>{{ isSaving ? 'Salvando...' : submitLabel }}</span>
            </button>

            <button v-if="perfil" type="button" :disabled="isSaving" @click="removerPerfil"
              class="inline-flex h-10 items-center justify-center rounded-full border border-red-300 bg-transparent px-6 text-[15px] font-medium text-red-700 transition hover:border-red-500 disabled:cursor-not-allowed disabled:opacity-70">
              Remover perfil
            </button>
          </div>
        </form>
      </section>

      <div class="flex flex-col items-center gap-2 text-center text-xs leading-[1.4] tracking-[0.16px] text-[#777169]">
        <p>
          Microsserviço consumido:
          <span class="font-medium text-[#4e4e4e]">https://perfilgameredivaldo-production.up.railway.app/api</span>
          &nbsp;·&nbsp; Feito por Edivaldo Rodrigues
        </p>
        <span class="inline-flex items-center gap-1.5">
          <span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
          Sistema de validação de token funcional
        </span>
      </div>
    </main>
  </div>
</template>

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

const PERFIL_GAMER_API_BASE_URL = 'https://perfilgameredivaldo-production.up.railway.app/api'

const { $toast } = useNuxtApp()

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

const perfil = ref(null)
const isLoading = ref(true)
const isSaving = ref(false)
const errorMessage = ref('')
const tokenValido = ref(false)

const form = reactive({
  nickname: '',
  bio: '',
  country: '',
  platformsText: '',
  gamesText: ''
})

const isCreateMode = computed(() => !perfil.value)

const modeLabel = computed(() => (isCreateMode.value ? 'Novo' : 'Editar'))
const modeTitle = computed(() =>
  isCreateMode.value ? 'Criar perfil gamer' : 'Editar perfil gamer'
)
const submitLabel = computed(() => (isCreateMode.value ? 'Criar perfil' : 'Salvar alterações'))

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

const parseList = (value) => {
  return value
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean)
}

const preencherFormulario = (data) => {
  form.nickname = data?.nickname ?? ''
  form.bio = data?.bio ?? ''
  form.country = data?.country ?? ''
  form.platformsText = Array.isArray(data?.platforms) ? data.platforms.join(', ') : ''
  form.gamesText = Array.isArray(data?.games) ? data.games.join(', ') : ''
}

const montarPayload = () => ({
  nickname: form.nickname.trim(),
  bio: form.bio.trim() || null,
  country: form.country.trim() || null,
  platforms: parseList(form.platformsText),
  games: parseList(form.gamesText)
})

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

  isLoading.value = true
  errorMessage.value = ''
  tokenValido.value = false

  try {
    const data = await $fetch(`${PERFIL_GAMER_API_BASE_URL}/profiles/me`, {
      headers: {
        Authorization: `Bearer ${token.value}`
      }
    })

    perfil.value = data
    preencherFormulario(data)
    tokenValido.value = true
  } 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
    }

    if (statusCode === 404) {
      perfil.value = null
      tokenValido.value = true
      return
    }

    errorMessage.value = error?.data?.message ?? 'Erro ao carregar o perfil gamer. Tente novamente.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

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

  isSaving.value = true
  errorMessage.value = ''

  try {
    const payload = montarPayload()

    if (isCreateMode.value) {
      const data = await $fetch(`${PERFIL_GAMER_API_BASE_URL}/profiles`, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${token.value}`
        },
        body: payload
      })

      perfil.value = data
      preencherFormulario(data)
      $toast.success('Perfil gamer criado com sucesso!', { duration: 5000 })
    } else {
      const data = await $fetch(`${PERFIL_GAMER_API_BASE_URL}/profiles/${perfil.value.user_id}`, {
        method: 'PUT',
        headers: {
          Authorization: `Bearer ${token.value}`
        },
        body: payload
      })

      perfil.value = data
      preencherFormulario(data)
      $toast.success('Perfil gamer atualizado!', { duration: 5000 })
    }

    tokenValido.value = true
  } 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
    }

    const validationMessage = error?.data?.message
    const nicknameError = error?.data?.errors?.nickname?.[0]
    errorMessage.value =
      nicknameError ?? validationMessage ?? 'Não foi possível salvar o perfil gamer.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isSaving.value = false
  }
}

async function removerPerfil() {
  if (!perfil.value || !token.value) {
    return
  }

  isSaving.value = true
  errorMessage.value = ''

  try {
    await $fetch(`${PERFIL_GAMER_API_BASE_URL}/profiles/${perfil.value.user_id}`, {
      method: 'DELETE',
      headers: {
        Authorization: `Bearer ${token.value}`
      }
    })

    perfil.value = null
    form.nickname = ''
    form.bio = ''
    form.country = ''
    form.platformsText = ''
    form.gamesText = ''
    $toast.success('Perfil gamer removido.', { duration: 5000 })
  } 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
    }

    errorMessage.value = error?.data?.message ?? 'Erro ao remover o perfil gamer.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isSaving.value = false
  }
}

onMounted(() => {
  carregarPerfil()
})
</script>
