<script lang="ts" setup>
import { useDateFormat, useTimeAgo } from '@vueuse/core'

interface Feedback {
  id: string
  message: string
  status: string
  createdAt: string
  user: {
    id: string
    name: string
    email: string
    image?: string | null
  }
  meta?: {
    url?: string
    browser?: string
    platform?: string
    screenResolution?: string
    language?: string
    timezone?: string
    colorScheme?: string
  }
}

const { data: feedback, refresh, pending: isLoading } = await useApiFetch<Feedback[]>(
  '/api/super-admin/feedback'
)

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

const toast = useToast()

const columns = computed(() => [
  t('admin.feedbackSubmissions.columns.user'),
  t('admin.feedbackSubmissions.columns.email'),
  t('admin.feedbackSubmissions.columns.status'),
  t('admin.feedbackSubmissions.columns.message'),
  t('admin.feedbackSubmissions.columns.date'),
  ''
])
const loadingFeedbackId = ref<string | null>(null)
const selectedFeedback = ref<Feedback | null>(null)
const replyModal = ref(false)
const showDeleteConfirmation = ref(false)
const isSubmitting = ref(false)
const isDeleting = ref(false)

const replyFormState = ref({
  message: ''
})

const actions = computed(() => [
  {
    label: t('admin.feedbackSubmissions.actions.reply'),
    onSelect: () => {
      if (selectedFeedback.value) {
        replyModal.value = true
      }
    }
  },
  {
    label: t('admin.feedbackSubmissions.actions.markClosed'),
    onSelect: () => {
      if (selectedFeedback.value) {
        void handleMarkAsClosed(selectedFeedback.value)
      }
    }
  },
  {
    label: t('admin.feedbackSubmissions.actions.delete'),
    color: 'error' as const,
    onSelect: () => {
      if (selectedFeedback.value) {
        showDeleteConfirmation.value = true
      }
    }
  }
])

const formatDate = (date: string | Date | undefined) => {
  if (!date) return t('admin.feedbackSubmissions.na')
  return useDateFormat(date, 'MMM D, YYYY HH:mm a').value
}

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

const handleReply = async () => {
  if (!selectedFeedback.value) return

  try {
    isSubmitting.value = true
    const apiCall = useApiCall()
    await apiCall('/api/super-admin/feedback/reply', {
      method: 'POST',
      body: {
        id: selectedFeedback.value.id,
        message: replyFormState.value.message,
        email: selectedFeedback.value.user.email
      }
    })
    toast.add({
      title: t('admin.feedbackSubmissions.messages.replySent'),
      description: t('admin.feedbackSubmissions.messages.replySentDescription'),
      color: 'success'
    })
    replyModal.value = false
    replyFormState.value.message = ''
    await refresh()
  } catch {
    toast.add({
      title: t('admin.feedbackSubmissions.messages.error'),
      description: t('admin.feedbackSubmissions.messages.replyError'),
      color: 'error'
    })
  } finally {
    isSubmitting.value = false
  }
}

const handleMarkAsClosed = async (feedbackItem: Feedback) => {
  try {
    loadingFeedbackId.value = feedbackItem.id
    const apiCall = useApiCall()
    await apiCall(`/api/super-admin/feedback/${feedbackItem.id}`, {
      method: 'PATCH',
      body: {
        status: 'closed'
      }
    })
    toast.add({
      title: t('admin.feedbackSubmissions.messages.closedSuccess'),
      description: t('admin.feedbackSubmissions.messages.closedSuccessDescription'),
      color: 'success'
    })
    await refresh()
  } catch {
    toast.add({
      title: t('admin.feedbackSubmissions.messages.error'),
      description: t('admin.feedbackSubmissions.messages.closedError'),
      color: 'error'
    })
  } finally {
    loadingFeedbackId.value = null
  }
}

const handleDelete = async () => {
  if (!selectedFeedback.value) return

  try {
    isDeleting.value = true
    const apiCall = useApiCall()
    await apiCall(`/api/super-admin/feedback/${selectedFeedback.value.id}`, {
      method: 'DELETE'
    })
    toast.add({
      title: t('admin.feedbackSubmissions.messages.deleteSuccess'),
      description: t('admin.feedbackSubmissions.messages.deleteSuccessDescription'),
      color: 'success'
    })
    showDeleteConfirmation.value = false
    await refresh()
  } catch {
    toast.add({
      title: t('admin.feedbackSubmissions.messages.error'),
      description: t('admin.feedbackSubmissions.messages.deleteError'),
      color: 'error'
    })
  } finally {
    isDeleting.value = false
  }
}

const { t } = useI18n()
const localePath = useLocalePath()

definePageMeta({
  layout: 'dashboard',
  middleware: ['super-admin'],
  colorMode: 'light'
})
</script>

<template>
  <NuxtLayout
    :page-title="t('admin.feedback-submissions')"
    :parent="{
      label: t('admin.title'),
      to: localePath('/dashboard/admin')
    }"
    type="admin"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refresh" />
      <PageMainCard
        :title="t('admin.feedback-submissions')"
        :description="t('admin.feedback-submissions-description')"
        :icon="useSolarIcon('chat-round')"
        :loading="isLoading"
        :on-refresh="refresh"
      >
        <div class="overflow-x-auto">
          <table class="w-full table-auto text-left text-sm">
            <thead>
              <tr>
                <th
                  v-for="column in columns"
                  :key="column"
                  class="p-2 text-nowrap whitespace-nowrap"
                >
                  {{ column }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="feedbackItem in feedbackList"
                :key="feedbackItem.id"
                class="border-b border-neutral-100 text-sm text-neutral-500 hover:bg-neutral-50 dark:border-white/10 dark:text-neutral-400 dark:hover:bg-neutral-800/50 [&>td]:whitespace-nowrap"
              >
                <td class="p-2">
                  <div class="flex items-center gap-2">
                    <UAvatar
                      :src="feedbackItem.user.image ?? undefined"
                      size="2xs"
                      :alt="feedbackItem.user.name"
                    />
                    {{ feedbackItem.user.name }}
                  </div>
                </td>
                <td class="p-2">
                  {{ feedbackItem.user.email }}
                </td>
                <td class="p-2">
                  <UBadge
                    variant="soft"
                    :color="getFeedbackStatusColor(feedbackItem.status)"
                    class="capitalize"
                  >
                    {{ feedbackItem.status }}
                  </UBadge>
                </td>
                <td class="max-w-xs p-2">
                  <div class="truncate">
                    {{ feedbackItem.message }}
                  </div>
                </td>
                <td class="p-2">
                  <UTooltip
                    :text="formatDate(feedbackItem.createdAt)"
                    :delay-duration="0"
                  >
                    <div>
                      {{ useTimeAgo(feedbackItem.createdAt) }}
                    </div>
                  </UTooltip>
                </td>
                <td class="p-2">
                  <UDropdownMenu
                    :items="actions"
                    :content="{ align: 'end', side: 'bottom', sideOffset: 0 }"
                  >
                    <UButton
                      icon="i-lucide-ellipsis"
                      variant="ghost"
                      color="neutral"
                      class="text-neutral-500"
                      :loading="loadingFeedbackId === feedbackItem.id"
                      @click="selectedFeedback = feedbackItem"
                    />
                  </UDropdownMenu>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Reply Modal -->
        <UModal
          v-model:open="replyModal"
          :title="t('admin.feedbackSubmissions.modals.reply.title')"
          :description="t('admin.feedbackSubmissions.modals.reply.description')"
        >
          <template #body>
            <div
              class="mb-4 flex items-center gap-2 border-b border-neutral-100 pb-2 text-xs dark:border-white/10"
            >
              <UAvatar
                :src="selectedFeedback?.user.image ?? undefined"
                size="2xs"
                :alt="selectedFeedback?.user.name"
              />
              {{ t('admin.feedbackSubmissions.modals.reply.userSays', { name: selectedFeedback?.user.name }) }}
            </div>
            <div class="mb-4 rounded-lg bg-neutral-50 p-4 dark:bg-neutral-800">
              <p
                class="max-h-40 overflow-auto text-sm whitespace-pre-line text-neutral-500 dark:text-neutral-400"
              >
                {{ selectedFeedback?.message }}
              </p>
            </div>
            <div class="mb-4 rounded-lg bg-neutral-50 p-4 dark:bg-neutral-800">
              <div class="grid grid-cols-2 gap-3 text-xs">
                <div
                  v-if="selectedFeedback?.meta?.url"
                  class="col-span-2"
                >
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.pageUrl') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.url
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.browser">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.browser') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.browser.split(' ')[0]
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.platform">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.platform') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.platform
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.screenResolution">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.screen') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.screenResolution
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.language">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.language') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.language
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.timezone">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.timezone') }}</span>
                  <span class="ml-2 text-neutral-500 dark:text-neutral-400">{{
                    selectedFeedback.meta.timezone
                  }}</span>
                </div>
                <div v-if="selectedFeedback?.meta?.colorScheme">
                  <span class="font-medium text-neutral-600 dark:text-neutral-300">{{ t('admin.feedbackSubmissions.modals.reply.metadata.colorScheme') }}</span>
                  <span
                    class="ml-2 text-neutral-500 capitalize dark:text-neutral-400"
                  >{{ selectedFeedback.meta.colorScheme }}</span>
                </div>
              </div>
            </div>
            <UForm
              :state="replyFormState"
              @submit="handleReply"
            >
              <UFormField
                :label="t('admin.feedbackSubmissions.modals.reply.messageLabel')"
                name="message"
              >
                <UTextarea
                  v-model="replyFormState.message"
                  :placeholder="t('admin.feedbackSubmissions.modals.reply.messagePlaceholder')"
                  :rows="4"
                  class="w-full"
                />
              </UFormField>
              <div class="mt-4 flex justify-end gap-2">
                <UButton
                  variant="ghost"
                  color="neutral"
                  @click="replyModal = false"
                >
                  {{ t('admin.feedbackSubmissions.modals.reply.cancelButton') }}
                </UButton>
                <UButton
                  type="submit"
                  :loading="isSubmitting"
                >
                  {{ t('admin.feedbackSubmissions.modals.reply.sendButton') }}
                </UButton>
              </div>
            </UForm>
          </template>
        </UModal>

        <!-- Delete Confirmation Modal -->
        <UModal
          v-model:open="showDeleteConfirmation"
          :title="t('admin.feedbackSubmissions.modals.delete.title')"
          :description="t('admin.feedbackSubmissions.modals.delete.description')"
        >
          <template #body>
            <div class="flex justify-end gap-2">
              <UButton
                variant="ghost"
                color="neutral"
                :label="t('admin.feedbackSubmissions.modals.delete.cancelButton')"
                @click="showDeleteConfirmation = false"
              />
              <UButton
                color="error"
                :loading="isDeleting"
                :label="t('admin.feedbackSubmissions.modals.delete.deleteButton')"
                @click="handleDelete"
              />
            </div>
          </template>
        </UModal>
      </PageMainCard>
    </UPageBody>
  </NuxtLayout>
</template>
