import { computed } from 'vue'
import { useAsyncState } from '@vueuse/core'
import type { Ticket } from '@/lib/types/event'
import { fetchUserTickets } from '@/lib/api/events'
import { useAuth } from '@/composables/useAuthService'

interface GroupedTickets {
  eventId: string
  tickets: Ticket[]
  paidCount: number
  pendingCount: number
  registeredCount: number
}

export function useUserTickets() {
  const { isAuthenticated, currentUser } = useAuth()
  
  const { state: tickets, isLoading, error: asyncError, execute: refresh } = useAsyncState(
    async () => {
      if (!isAuthenticated.value || !currentUser.value) {
        return []
      }
      return await fetchUserTickets(currentUser.value.id)
    },
    [] as Ticket[],
    {
      immediate: false,
      resetOnExecute: false,
    }
  )

  const error = computed(() => {
    if (asyncError.value) {
      return {
        message: asyncError.value instanceof Error
          ? asyncError.value.message
          : 'An error occurred while fetching tickets'
      }
    }
    return null
  })

  const sortedTickets = computed(() => {
    return [...tickets.value].sort((a, b) =>
      new Date(b.time).getTime() - new Date(a.time).getTime()
    )
  })

  const paidTickets = computed(() => {
    return sortedTickets.value.filter(ticket => ticket.paid)
  })

  const pendingTickets = computed(() => {
    return sortedTickets.value.filter(ticket => !ticket.paid)
  })

  const registeredTickets = computed(() => {
    return sortedTickets.value.filter(ticket => ticket.registered)
  })

  const unregisteredTickets = computed(() => {
    return sortedTickets.value.filter(ticket => ticket.paid && !ticket.registered)
  })

  // Group tickets by event
  const groupedTickets = computed(() => {
    const groups = new Map<string, GroupedTickets>()
    
    sortedTickets.value.forEach(ticket => {
      if (!groups.has(ticket.event)) {
        groups.set(ticket.event, {
          eventId: ticket.event,
          tickets: [],
          paidCount: 0,
          pendingCount: 0,
          registeredCount: 0
        })
      }
      
      const group = groups.get(ticket.event)!
      group.tickets.push(ticket)
      
      if (ticket.paid) {
        group.paidCount++
      } else {
        group.pendingCount++
      }
      
      if (ticket.registered) {
        group.registeredCount++
      }
    })
    
    // Convert to array and sort by most recent ticket in each group
    return Array.from(groups.values()).sort((a, b) => {
      const aLatest = Math.max(...a.tickets.map(t => new Date(t.time).getTime()))
      const bLatest = Math.max(...b.tickets.map(t => new Date(t.time).getTime()))
      return bLatest - aLatest
    })
  })

  // Load tickets when authenticated
  const loadTickets = async () => {
    if (isAuthenticated.value && currentUser.value) {
      await refresh()
    }
  }

  return {
    // State
    tickets: sortedTickets,
    paidTickets,
    pendingTickets,
    registeredTickets,
    unregisteredTickets,
    groupedTickets,
    isLoading,
    error,

    // Actions
    refresh: loadTickets,
  }
} 