<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { AvatarRoot, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box'
import { Lucide } from '@/components/ui/lucide'
import logoUrl from '@/assets/images/logo.svg'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { getPublicMemberProfile } from '../services/public-member-profile.service'
import type { PublicMemberProfile } from '../types/public-member-profile.types'

const route = useRoute()

const loading = ref(true)
const error = ref<string | null>(null)
const member = ref<PublicMemberProfile | null>(null)

const token = computed(() => String(route.params.token ?? '').trim())

const avatarFallback = computed(() => {
  const name = member.value?.name?.trim()
  if (!name) return '--'
  return name.slice(0, 2).toUpperCase()
})

const displayValue = (value: string | number | null | undefined) => {
  if (value === null || value === undefined || value === '') return '-'
  return String(value).trim() || '-'
}

async function fetchMemberProfile() {
  loading.value = true
  error.value = null
  member.value = null

  if (!token.value) {
    error.value = 'Pautan pengesahan tidak sah.'
    loading.value = false
    return
  }

  try {
    const response = await getPublicMemberProfile(token.value)

    if (!response.success || !response.data) {
      throw new Error(response.message ?? 'Anggota tidak dijumpai atau tidak sah.')
    }

    member.value = response.data
  } catch (err) {
    error.value = getApiErrorMessage(err, 'Gagal memuatkan profil anggota.')
  } finally {
    loading.value = false
  }
}

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

<template>
  <div class="min-h-screen bg-slate-100 px-4 py-10">
    <div class="mx-auto w-full max-w-md">
      <div class="mb-6 flex flex-col items-center text-center">
        <img :src="logoUrl" alt="MyKOPKB" class="h-10 w-auto" />
        <h1 class="mt-4 text-xl font-semibold text-slate-900">Maklumat Anggota</h1>
      </div>

      <AlertRoot v-if="error" variant="danger">
        <AlertTitle>Pengesahan gagal</AlertTitle>
        <AlertDescription>{{ error }}</AlertDescription>
      </AlertRoot>

      <Box v-else-if="loading" raised="single" class="p-8 text-center text-sm text-slate-500">
        Memuatkan maklumat anggota...
      </Box>

      <Box v-else-if="member" raised="single" class="overflow-hidden p-0">
        <div class="bg-linear-to-br from-primary via-primary/95 to-primary/75 p-6 text-primary-foreground">
          <div class="flex items-start justify-between gap-3">
            <Badge class="bg-white/15 text-white">Disahkan</Badge>
            <div class="text-right text-[10px] font-semibold uppercase tracking-[0.2em] opacity-80">
              MyKOPKB
            </div>
          </div>

          <div class="mt-6 flex items-center gap-4">
            <AvatarRoot class="size-16 border-4 border-white/20 bg-white/10">
              <AvatarFallback>{{ avatarFallback }}</AvatarFallback>
              <AvatarImage v-if="member.image_url" :src="member.image_url" :alt="member.name" />
            </AvatarRoot>
            <div class="min-w-0 flex-1">
              <div class="truncate text-lg font-semibold">{{ member.name }}</div>
              <div class="mt-1 text-sm opacity-80">{{ displayValue(member.member_type) }}</div>
            </div>
          </div>
        </div>

        <div class="space-y-4 p-6">
          <div class="flex items-center gap-3 rounded-lg border border-foreground/10 p-4">
            <Lucide class="size-5 text-primary" icon="IdCard" />
            <div>
              <div class="text-xs uppercase tracking-wide text-slate-500">No. Anggota</div>
              <div class="font-mono text-base font-semibold text-slate-900">
                {{ displayValue(member.member_number) }}
              </div>
            </div>
          </div>

          <div class="flex items-center gap-3 rounded-lg border border-foreground/10 p-4">
            <Lucide class="size-5 text-primary" icon="Briefcase" />
            <div class="min-w-0">
              <div class="text-xs uppercase tracking-wide text-slate-500">Unit</div>
              <div class="truncate text-base font-medium text-slate-900">
                {{ displayValue(member.company_name) }}
              </div>
            </div>
          </div>

          <div class="flex items-center gap-3 rounded-lg border border-foreground/10 p-4">
            <Lucide class="size-5 text-primary" icon="CircleCheck" />
            <div>
              <div class="text-xs uppercase tracking-wide text-slate-500">Status</div>
              <div class="text-base font-medium capitalize text-slate-900">
                {{ displayValue(member.status) }}
              </div>
            </div>
          </div>

          <p class="text-center text-xs text-slate-500">
            Disahkan pada {{ new Date(member.verified_at).toLocaleString('ms-MY') }}
          </p>
        </div>
      </Box>
    </div>
  </div>
</template>
