<template>
  <div>
    <UForm
      :schema="schema"
      :state="form.state"
      class="space-y-6"
      @submit="onSubmit"
    >
      <div class="flex items-center gap-2">
        <UAvatar
          :src="user.avatarUrl"
          size="lg"
        />
        <div>
          <p class="text-smfont-bold">
            {{ user.name }}
          </p>
          <p class="text-sm text-neutral-500">
            {{ user.email }}
          </p>
        </div>
      </div>
      <UFormField
        :label="$t('superAdmin.banUser.reasonLabel')"
        name="reason"
        required
      >
        <UTextarea
          v-model="form.state.reason"
          class="w-full"
          size="lg"
        />
      </UFormField>
      <UFormField
        :label="$t('superAdmin.banUser.bannedUntilLabel')"
        name="bannedUntil"
        required
      >
        <UInput
          :model-value="dateDisplay"
          class="w-full"
          size="lg"
          readonly
        >
          <template #trailing>
            <UPopover>
              <UButton
                color="neutral"
                variant="ghost"
                icon="i-solar-calendar-bold-duotone"
                size="sm"
              />
              <template #content>
                <UCalendar
                  :model-value="calendarDate as any"
                  size="sm"
                  color="neutral"
                  @update:model-value="updateDate as any"
                />
              </template>
            </UPopover>
          </template>
        </UInput>
      </UFormField>
      <UButton
        type="submit"
        :label="$t('superAdmin.banUser.submitButton')"
        color="neutral"
        :loading="form.isSubmitting.value"
      />
    </UForm>
  </div>
</template>

<script lang="ts" setup>
/* eslint-disable @stylistic/member-delimiter-style */
import { getLocalTimeZone, today, type CalendarDate } from '@internationalized/date'
import { z } from 'zod'
import type { User } from '~/types/database'
import { useDateFormat } from '@vueuse/core'
import type { FormSubmitEvent } from '@nuxt/ui'
import { useForm } from '../../composables/useForm'

interface TeamMember {
  id: string;
  teamId: string;
  userId: string;
  role: string;
  createdAt: string;
  updatedAt: string;
  team: {
    id: string;
    name: string;
    ownerId: string;
    logo: string;
    slug: string;
    createdAt: string;
    updatedAt: string;
  };
}

type OAuthAccountLite = { providerId?: string, accountId?: string }
interface ExtendedUser extends User {
  avatarUrl?: string
  oauthAccounts?: OAuthAccountLite[]
  teamMembers?: TeamMember[]
}

const props = defineProps<{
  user: ExtendedUser
}>()

const emit = defineEmits(['user-banned'])
const toast = useToast()
const { t } = useI18n()
const log = useLogger('Ban User')

const schema = z.object({
  userId: z.string().min(1, t('superAdmin.banUser.validation.userIdRequired')),
  reason: z.string().min(1, t('superAdmin.banUser.validation.reasonRequired')),
  bannedUntil: z.any().refine((value) => {
    if (!value) return false
    const currentDate = today(getLocalTimeZone())
    return value.compare(currentDate) > 0
  }, t('superAdmin.banUser.validation.dateInFuture'))
})

type Schema = z.output<typeof schema>

// Use form composable for consistent form handling
const form = useForm(schema, {
  userId: props.user.id,
  reason: '',
  bannedUntil: today(getLocalTimeZone())
})

const calendarDate = computed(() => form.state.bannedUntil as CalendarDate)

const dateDisplay = computed(() => {
  return useDateFormat((form.state.bannedUntil as CalendarDate).toDate(getLocalTimeZone()), 'YYYY-MM-DD').value
})

function updateDate(value: CalendarDate) {
  form.setField('bannedUntil', value as unknown as Schema['bannedUntil'])
}

const onSubmit = async (event: FormSubmitEvent<Schema>) => {
  await form.handleFormSubmit(
    event,
    async (data: Schema) => {
      const formData = {
        ...data,
        banned: true,
        bannedUntil: (data.bannedUntil as CalendarDate).toDate(getLocalTimeZone()).toISOString()
      }

      const apiCall = useApiCall()
      await apiCall('/api/super-admin/users/ban', {
        method: 'POST',
        body: formData
      })

      toast.add({
        title: t('superAdmin.banUser.messages.success'),
        description: t('superAdmin.banUser.messages.successDescription', {
          name: props.user.name,
          date: useDateFormat(formData.bannedUntil, 'MMM D, YYYY').value
        }),
        color: 'success',
        duration: 5000
      })

      emit('user-banned', props.user)
    },
    {
      onError: (error: unknown) => {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const errorMessage = (error as any)?.data?.message || t('superAdmin.banUser.messages.error')
        toast.add({
          title: t('superAdmin.banUser.messages.errorTitle'),
          description: errorMessage,
          color: 'error',
          duration: 5000
        })
        log.error('Failed to ban user:', error)
      }
    }
  )
}
</script>
