<script setup lang="ts">
import { h, resolveComponent } from 'vue'

const NuxtTime = resolveComponent('NuxtTime')
const UBadge = resolveComponent('UBadge')
const { locale, t } = useI18n()
const localePath = useLocalePath()
const loading = ref(true)

type FeedbackRow = {
  id: string
  message: string
  status: string
  reply: string | null
  createdAt: string
}

const { data, pending, refresh } = await useApiFetch<FeedbackRow[]>(
  '/api/user/feedback',
  { server: false }
)

const feedback = computed<FeedbackRow[]>(() => {
  const feedbackData = data.value
  return Array.isArray(feedbackData) ? feedbackData : []
})

const isLoading = computed(() => {
  const pendingValue = typeof pending === 'object' && 'value' in pending ? pending.value : pending
  return Boolean(pendingValue) || loading.value
})

const columns = [
  {
    accessorKey: 'createdAt',
    header: t('account.feedback.createdAt') || 'Created',
    cell: ({ row }: { row: { original: FeedbackRow } }) =>
      h(NuxtTime, { datetime: row.original.createdAt, locale: locale.value })
  },
  {
    accessorKey: 'message',
    header: t('account.feedback.message') || 'Message'
  },
  {
    accessorKey: 'status',
    header: t('account.feedback.status') || 'Status',
    cell: ({ row }: { row: { original: FeedbackRow } }) =>
      h(UBadge, {
        variant: 'soft',
        color: getFeedbackStatusColor(row.original.status),
        class: 'capitalize'
      }, [row.original.status])
  },
  {
    accessorKey: 'reply',
    header: t('account.feedback.reply') || 'Reply',
    cell: ({ row }: { row: { original: FeedbackRow } }) =>
      row.original.reply ? row.original.reply : t('account.feedback.noReply') || '—'
  }
]

const getFeedbackStatusColor = (status: string) => {
  switch (status) {
    case 'replied':
      return 'info'
    case 'closed':
      return 'neutral'
    default:
      return 'warning'
  }
}

onMounted(() => {
  loading.value = false
})
</script>

<template>
  <NuxtLayout
    :page-title="t('account.feedback.title') || 'Support'"
    :parent="{ label: t('account.title'), to: localePath('/dashboard/account') }"
    name="dashboard"
    type="account"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refresh" />
      <PageMainCard
        :title="t('account.feedback.title') || 'Your support requests'"
        :description="t('account.feedback.description')"
        :icon="useSolarIcon('question-circle')"
        :loading="isLoading"
        :on-refresh="refresh"
      >
        <UTable
          :data="feedback"
          :columns="columns as any"
          :loading="isLoading"
          :empty="isLoading ? 'Loading...' : 'No feedback found'"
        />
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>
