<template>
  <div
    class="relative min-h-screen overflow-x-hidden bg-[#f5f5f5] px-3 py-8 font-sans text-[#0c0a09] sm:px-4 md:px-6 md:py-12 xl:px-8 xl: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(244,197,168,0.62),transparent_28%),radial-gradient(circle_at_72%_24%,rgba(167,229,211,0.5),transparent_30%),radial-gradient(circle_at_52%_78%,rgba(168,200,232,0.52),transparent_34%)] blur-2xl"
      aria-hidden="true"></div>

    <main class="relative mx-auto grid w-full min-w-0 max-w-[1120px] gap-6 md:gap-8" aria-labelledby="gift-card-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(244,197,168,0.62)] px-3 py-1 text-xs font-semibold uppercase leading-[1.4] tracking-[0.96px] text-[#0c0a09]">
            Carteira
          </p>
          <h1 id="gift-card-title"
            class="my-5 max-w-[720px] break-words font-serif text-[34px] font-light leading-[1.08] tracking-[-0.96px] text-[#0c0a09] sm:text-[40px] md:text-[48px]">
            Gift Cards
          </h1>
          <p class="m-0 max-w-[560px] text-base font-normal leading-6 tracking-[0.16px] text-[#4e4e4e]">
            Crie cartões, consulte saldo por código e realize resgates com segurança.
          </p>
        </div>
      </header>

      <div class="grid min-w-0 gap-6 md:gap-8 xl:grid-cols-2">
        <section
          class="grid min-w-0 gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6 xl:p-8"
          aria-label="Criar gift card">
          <div>
            <span
              class="inline-flex min-h-6 items-center rounded-full bg-[rgba(167,229,211,0.62)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
              Novo
            </span>
            <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
              Emitir gift card
            </h2>
          </div>

          <form class="grid gap-4" @submit.prevent="criarGiftCard">
            <div class="grid gap-2">
              <label for="balance" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
                Valor inicial (R$)
              </label>
              <input id="balance" v-model.number="createForm.balance" type="number" min="1" step="0.01" required
                class="h-11 w-full min-w-0 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
                placeholder="100.00" />
            </div>
            <button type="submit" :disabled="isCreating"
              class="inline-flex min-h-10 w-full items-center justify-center gap-2 rounded-full bg-[#292524] px-6 py-2 text-[15px] font-medium text-white transition hover:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70 sm:w-fit">
              <Icon v-if="isCreating" name="mdi:loading" class="animate-spin text-base" />
              <span>{{ isCreating ? 'Criando...' : 'Criar gift card' }}</span>
            </button>
          </form>
        </section>

        <section
          class="grid min-w-0 gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6 xl:p-8"
          aria-label="Consultar e resgatar gift card">
          <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]">
              Operações
            </span>
            <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
              Consultar e resgatar
            </h2>
          </div>

          <form class="grid gap-4" @submit.prevent="consultarGiftCard">
            <div class="grid gap-2">
              <label for="code" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
                Código do cartão
              </label>
              <input id="code" v-model="operationForm.code" type="text" required maxlength="10"
                class="h-11 w-full min-w-0 rounded-xl border border-[#e7e5e4] px-4 text-[15px] uppercase text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
                placeholder="AB12CD34EF" />
            </div>
            <button type="submit" :disabled="isConsulting"
              class="inline-flex min-h-10 w-full items-center justify-center gap-2 rounded-full border border-[#d6d3d1] bg-transparent px-6 py-2 text-[15px] font-medium text-[#0c0a09] transition hover:border-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70 sm:w-fit">
              <Icon v-if="isConsulting" name="mdi:loading" class="animate-spin text-base" />
              <span>{{ isConsulting ? 'Consultando...' : 'Consultar saldo' }}</span>
            </button>
          </form>

          <form class="grid gap-4 border-t border-[#e7e5e4] pt-4" @submit.prevent="resgatarGiftCard">
            <div class="grid gap-2">
              <label for="amount" class="text-xs font-semibold uppercase tracking-[0.96px] text-[#777169]">
                Valor do resgate (R$)
              </label>
              <input id="amount" v-model.number="operationForm.amount" type="number" min="0.01" step="0.01" required
                class="h-11 w-full min-w-0 rounded-xl border border-[#e7e5e4] px-4 text-[15px] text-[#0c0a09] outline-none transition focus:border-[#0c0a09]"
                placeholder="25.00" />
            </div>
            <button type="submit" :disabled="isRedeeming"
              class="inline-flex min-h-10 w-full items-center justify-center gap-2 rounded-full bg-[#292524] px-6 py-2 text-[15px] font-medium text-white transition hover:bg-[#0c0a09] disabled:cursor-not-allowed disabled:opacity-70 sm:w-fit">
              <Icon v-if="isRedeeming" name="mdi:loading" class="animate-spin text-base" />
              <span>{{ isRedeeming ? 'Resgatando...' : 'Resgatar valor' }}</span>
            </button>
          </form>

          <div v-if="selectedCard"
            class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-4 text-[15px] leading-[1.47] text-[#292524]">
            <p class="m-0"><strong>Código:</strong> {{ selectedCard.code }}</p>
            <p class="m-0 mt-2">
              <strong>Saldo:</strong> {{ formatCurrency(selectedCard.balance) }}
            </p>
            <p class="m-0 mt-2">
              <strong>Status:</strong>
              {{ selectedCard.is_active ? 'Ativo' : 'Desativado' }}
            </p>
          </div>
        </section>
      </div>

      <section
        class="grid min-w-0 gap-6 rounded-2xl border border-[#e7e5e4] bg-white p-4 shadow-[0_4px_16px_rgba(0,0,0,0.04)] sm:p-5 md:p-6 xl:p-8"
        aria-label="Meus gift cards">
        <div>
          <span
            class="inline-flex min-h-6 items-center rounded-full bg-[rgba(244,197,168,0.56)] px-2.5 py-1 text-xs font-semibold uppercase leading-none tracking-[0.96px] text-[#0c0a09]">
            Meus cartões
          </span>
          <h2 class="mt-4 font-serif text-3xl font-light leading-[1.13] tracking-[-0.32px] text-[#0c0a09]">
            Cartões emitidos por você
          </h2>
        </div>

        <div v-if="isLoading" class="grid gap-3" role="status" aria-live="polite">
          <div v-for="item in 3" :key="item" class="h-16 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] text-red-700"
          role="alert">
          {{ errorMessage }}
        </div>

        <div v-else-if="!giftCards.length"
          class="rounded-xl border border-[#e7e5e4] bg-[#fafafa] px-4 py-6 text-center text-[15px] text-[#777169]">
          Você ainda não emitiu nenhum gift card.
        </div>

        <div v-else class="overflow-hidden rounded-xl border border-[#e7e5e4]">
          <ul class="grid divide-y divide-[#e7e5e4]">
            <li v-for="card in giftCards" :key="card.id"
              class="flex min-w-0 flex-col gap-3 bg-white p-4 lg:flex-row lg:items-center lg:justify-between">
              <div class="grid min-w-0 gap-1">
                <span class="min-w-0 break-words font-mono text-base font-medium tracking-wider text-[#0c0a09]">{{
                  card.code }}</span>
                <span class="text-xs text-[#777169]">Criado em {{ formatDate(card.created_at) }}</span>
              </div>
              <div class="flex min-w-0 flex-wrap items-center gap-3">
                <span class="text-[15px] font-medium text-[#292524]">{{
                  formatCurrency(card.balance)
                }}</span>
                <span class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold uppercase" :class="card.is_active
                  ? 'bg-[rgba(167,229,211,0.62)] text-[#0c0a09]'
                  : 'bg-[#f0efed] text-[#777169]'
                  ">
                  {{ card.is_active ? 'Ativo' : 'Inativo' }}
                </span>
                <button type="button" class="text-[15px] font-medium text-[#0c0a09] underline-offset-2 hover:underline"
                  @click="preencherCodigo(card.code)">
                  Usar código
                </button>
              </div>
            </li>
          </ul>
        </div>
      </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://giftcardapipedro-production.up.railway.app/api</span>
          &nbsp;·&nbsp; Feito por Pedro Henrique e João Vitor
        </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'
})

useHead({
  title: 'Gift Cards | GameVerse',
  meta: [
    {
      name: 'description',
      content: 'Crie cartões, consulte saldo por código e realize resgates com segurança.'
    }
  ]
})

const GIFT_CARD_API_BASE_URL = 'https://giftcardapipedro-production.up.railway.app/api'

const { $toast } = useNuxtApp()

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

const giftCards = ref([])
const selectedCard = ref(null)
const isLoading = ref(true)
const isCreating = ref(false)
const isConsulting = ref(false)
const isRedeeming = ref(false)
const errorMessage = ref('')
const tokenValido = ref(false)

const createForm = reactive({
  balance: 50
})

const operationForm = reactive({
  code: '',
  amount: 10
})

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

const authHeaders = () => ({
  Authorization: `Bearer ${token.value}`
})

const formatCurrency = (value) => {
  return new Intl.NumberFormat('pt-BR', {
    style: 'currency',
    currency: 'BRL'
  }).format(Number(value ?? 0))
}

const formatDate = (value) => {
  if (!value) return '-'
  return new Intl.DateTimeFormat('pt-BR', {
    dateStyle: 'short',
    timeStyle: 'short'
  }).format(new Date(value))
}

const tratarErroAuth = async (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 true
  }

  return false
}

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

  isLoading.value = true
  errorMessage.value = ''

  try {
    const data = await $fetch(`${GIFT_CARD_API_BASE_URL}/giftcards`, {
      headers: authHeaders()
    })

    giftCards.value = Array.isArray(data) ? data : []
    tokenValido.value = true
  } catch (error) {
    if (await tratarErroAuth(error)) {
      return
    }

    giftCards.value = []
    errorMessage.value = error?.data?.message ?? 'Erro ao carregar seus gift cards.'
    $toast.error(errorMessage.value, { duration: 8000 })
  } finally {
    isLoading.value = false
  }
}

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

  isCreating.value = true

  try {
    const data = await $fetch(`${GIFT_CARD_API_BASE_URL}/giftcards`, {
      method: 'POST',
      headers: authHeaders(),
      body: { balance: createForm.balance }
    })

    giftCards.value = [data, ...giftCards.value]
    operationForm.code = data.code
    selectedCard.value = data
    tokenValido.value = true
    $toast.success(`Gift card ${data.code} criado!`, { duration: 5000 })
  } catch (error) {
    if (await tratarErroAuth(error)) {
      return
    }

    $toast.error(error?.data?.message ?? 'Erro ao criar gift card.', { duration: 8000 })
  } finally {
    isCreating.value = false
  }
}

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

  isConsulting.value = true

  try {
    const code = operationForm.code.trim().toUpperCase()
    const data = await $fetch(`${GIFT_CARD_API_BASE_URL}/giftcards/${encodeURIComponent(code)}`, {
      headers: authHeaders()
    })

    selectedCard.value = data
    tokenValido.value = true
    $toast.success('Saldo consultado com sucesso.', { duration: 4000 })
  } catch (error) {
    if (await tratarErroAuth(error)) {
      return
    }

    selectedCard.value = null
    $toast.error(error?.data?.message ?? 'Gift card não encontrado.', { duration: 6000 })
  } finally {
    isConsulting.value = false
  }
}

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

  isRedeeming.value = true

  try {
    const code = operationForm.code.trim().toUpperCase()
    const data = await $fetch(
      `${GIFT_CARD_API_BASE_URL}/giftcards/redeem/${encodeURIComponent(code)}`,
      {
        method: 'POST',
        headers: authHeaders(),
        body: { amount: operationForm.amount }
      }
    )

    selectedCard.value = data.gift_card ?? selectedCard.value
    tokenValido.value = true
    $toast.success(data.message ?? 'Resgate realizado!', { duration: 5000 })
    await carregarGiftCards()
  } catch (error) {
    if (await tratarErroAuth(error)) {
      return
    }

    $toast.error(error?.data?.message ?? 'Erro ao resgatar gift card.', { duration: 8000 })
  } finally {
    isRedeeming.value = false
  }
}

function preencherCodigo(code) {
  operationForm.code = code
  selectedCard.value = giftCards.value.find((card) => card.code === code) ?? selectedCard.value
}

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