import { ref, computed, onMounted, watch } from 'vue'
import { useChoreStore } from '@/stores/choreStore'
import { useGroupStore } from '@/stores/groupStore'
import { useAuthStore } from '@/stores/auth'
import { useExpenses } from '@/composables/useExpenses'

interface NextAction {
    type: 'chore' | 'expense' | 'none';
    title: string;
    subtitle: string;
    cta: string;
    path: string;
    priority: number; // 1 = highest
}

interface PriorityAction {
    id: string
    type: 'chore' | 'expense' | 'debt' | 'overdue'
    priority: 'urgent' | 'high' | 'medium' | 'low'
    title: string
    description?: string
    dueDate?: Date
    amount?: number
    actionUrl: string
}

interface PersonalStatus {
    completedToday: number
    netBalance: number
    pointsThisWeek: number
    streakCount: number
    totalTasks: number
    pendingExpenses: number
}

export function usePersonalStatus() {
    const choreStore = useChoreStore()
    const groupStore = useGroupStore()
    const { expenses, fetchExpenses } = useExpenses()
    const authStore = useAuthStore()

    const isLoading = ref(true)

    const fetchAllData = async (groupId: number) => {
        isLoading.value = true
        await Promise.all([
            choreStore.fetchGroup(groupId),
            choreStore.fetchPersonal(),
            fetchExpenses({ group_id: groupId }),
        ])
        isLoading.value = false
    }

    onMounted(() => {
        if (groupStore.currentGroupId) {
            fetchAllData(groupStore.currentGroupId)
        }
    })

    watch(() => groupStore.currentGroupId, (newGroupId) => {
        if (newGroupId) {
            fetchAllData(newGroupId)
        }
    })

    const userChoresWithAssignments = computed(() => {
        const userId = authStore.user?.id
        if (!userId) return []

        return choreStore.allChores.flatMap(chore =>
            chore.assignments
                .filter(assignment => assignment.assigned_to_user_id === userId)
                .map(assignment => ({
                    choreName: chore.name,
                    ...assignment
                }))
        )
    })

    // Legacy nextAction for backward compatibility
    const nextAction = computed<NextAction>(() => {
        const now = new Date()
        // Priority 1: Overdue chores
        const overdueChoreAssignment = userChoresWithAssignments.value
            .filter(assignment => new Date(assignment.due_date) < now && !assignment.is_complete)
            .sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime())[0]

        if (overdueChoreAssignment) {
            return {
                type: 'chore',
                title: `Overdue: ${overdueChoreAssignment.choreName}`,
                subtitle: `Was due on ${new Date(overdueChoreAssignment.due_date).toLocaleDateString()}`,
                cta: 'View Chore',
                path: `/chores`,
                priority: 1,
            }
        }

        // Priority 2: Upcoming chores
        const upcomingChoreAssignment = userChoresWithAssignments.value
            .filter(assignment => !assignment.is_complete)
            .sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime())[0]

        if (upcomingChoreAssignment) {
            return {
                type: 'chore',
                title: `Next up: ${upcomingChoreAssignment.choreName}`,
                subtitle: `Due on ${new Date(upcomingChoreAssignment.due_date).toLocaleDateString()}`,
                cta: 'View Chore',
                path: `/chores`,
                priority: 2,
            }
        }

        return {
            type: 'none',
            title: "You're all caught up!",
            subtitle: 'No urgent tasks or expenses. Great job!',
            cta: 'Go to Dashboard',
            path: '/dashboard',
            priority: 99,
        }
    })

    // New priority action for the refactored component
    const priorityAction = computed<PriorityAction | null>(() => {
        const now = new Date()
        const userId = authStore.user?.id
        if (!userId) return null

        // Priority 1: Overdue chores (urgent)
        const overdueChoreAssignment = userChoresWithAssignments.value
            .filter(assignment => new Date(assignment.due_date) < now && !assignment.is_complete)
            .sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime())[0]

        if (overdueChoreAssignment) {
            return {
                id: overdueChoreAssignment.id.toString(),
                type: 'overdue',
                priority: 'urgent',
                title: overdueChoreAssignment.choreName,
                dueDate: new Date(overdueChoreAssignment.due_date),
                actionUrl: '/chores'
            }
        }

        // Priority 2: Due today chores (high)
        const dueTodayChoreAssignment = userChoresWithAssignments.value
            .filter(assignment => {
                const dueDate = new Date(assignment.due_date)
                const today = new Date()
                return dueDate.toDateString() === today.toDateString() && !assignment.is_complete
            })
            .sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime())[0]

        if (dueTodayChoreAssignment) {
            return {
                id: dueTodayChoreAssignment.id.toString(),
                type: 'chore',
                priority: 'high',
                title: dueTodayChoreAssignment.choreName,
                dueDate: new Date(dueTodayChoreAssignment.due_date),
                actionUrl: '/chores'
            }
        }

        // Priority 3: Upcoming chores (medium)
        const upcomingChoreAssignment = userChoresWithAssignments.value
            .filter(assignment => new Date(assignment.due_date) > now && !assignment.is_complete)
            .sort((a, b) => new Date(a.due_date).getTime() - new Date(b.due_date).getTime())[0]

        if (upcomingChoreAssignment) {
            return {
                id: upcomingChoreAssignment.id.toString(),
                type: 'chore',
                priority: 'medium',
                title: upcomingChoreAssignment.choreName,
                dueDate: new Date(upcomingChoreAssignment.due_date),
                actionUrl: '/chores'
            }
        }

        return null
    })

    // Personal status summary
    const personalStatus = computed<PersonalStatus>(() => {
        const userId = authStore.user?.id
        if (!userId) {
            return {
                completedToday: 0,
                netBalance: 0,
                pointsThisWeek: 0,
                streakCount: 0,
                totalTasks: 0,
                pendingExpenses: 0
            }
        }

        const today = new Date()
        const weekStart = new Date(today.getFullYear(), today.getMonth(), today.getDate() - today.getDay())

        // Count completed chores today
        const completedToday = userChoresWithAssignments.value.filter(assignment => {
            if (!assignment.is_complete || !assignment.completed_at) return false
            const completedDate = new Date(assignment.completed_at)
            return completedDate.toDateString() === today.toDateString()
        }).length

        // Calculate points this week (assuming 10 points per completed chore)
        const pointsThisWeek = userChoresWithAssignments.value.filter(assignment => {
            if (!assignment.is_complete || !assignment.completed_at) return false
            const completedDate = new Date(assignment.completed_at)
            return completedDate >= weekStart
        }).length * 10

        // Simple streak calculation (consecutive days with completed chores)
        let streakCount = 0
        const checkDate = new Date(today)
        while (streakCount < 30) { // Max 30 days lookback
            const dayAssignments = userChoresWithAssignments.value.filter(assignment => {
                if (!assignment.is_complete || !assignment.completed_at) return false
                const completedDate = new Date(assignment.completed_at)
                return completedDate.toDateString() === checkDate.toDateString()
            })

            if (dayAssignments.length > 0) {
                streakCount++
                checkDate.setDate(checkDate.getDate() - 1)
            } else {
                break
            }
        }

        return {
            completedToday,
            netBalance: 0, // TODO: Calculate from expenses
            pointsThisWeek,
            streakCount,
            totalTasks: userChoresWithAssignments.value.length,
            pendingExpenses: expenses.value.length
        }
    })

    return {
        // Legacy support
        nextAction,
        isLoading,
        // New interface
        personalStatus,
        priorityAction
    }
} 