import { computed, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { getActivity } from '../services/activity.service'
import type { ActivityDetail } from '../types/activity.types'

export function useActivityDetail() {
  const route = useRoute()
  const activity = ref<ActivityDetail | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const activityId = computed(() => String(route.params.id ?? ''))

  async function fetchActivity() {
    if (!activityId.value) {
      error.value = 'ID aktiviti tidak sah.'
      return
    }

    loading.value = true
    error.value = null

    try {
      activity.value = await getActivity(activityId.value)
    } catch (err) {
      error.value = getApiErrorMessage(err, 'Gagal memuatkan butiran aktiviti.')
      activity.value = null
    } finally {
      loading.value = false
    }
  }

  watch(activityId, () => {
    fetchActivity()
  })

  onMounted(() => {
    fetchActivity()
  })

  return {
    activity,
    activityId,
    loading,
    error,
    fetchActivity,
  }
}
