import Combine
import Foundation

struct ReviewTask: Identifiable, Equatable {
    let id: String
    let userId: String
    let lessonId: String
    let sourceSessionId: String
    let reviewType: ReviewType
    let scheduledAt: String
    let completedAt: String?
    var status: ReviewTaskStatus
}

enum ReviewType: String {
    case recall, feynman, review
}

enum ReviewTaskStatus: String {
    case pending, completed
}

@MainActor
final class ReviewPlanViewModel: ObservableObject {
    @Published var todayTasks: [ReviewTask] = [
        ReviewTask(id: "t1", userId: "u1", lessonId: "l1", sourceSessionId: "s1",
                   reviewType: .recall, scheduledAt: "", completedAt: nil, status: .pending),
        ReviewTask(id: "t2", userId: "u1", lessonId: "l2", sourceSessionId: "s2",
                   reviewType: .feynman, scheduledAt: "", completedAt: nil, status: .completed),
        ReviewTask(id: "t3", userId: "u1", lessonId: "l3", sourceSessionId: "s3",
                   reviewType: .review, scheduledAt: "", completedAt: nil, status: .pending),
    ]

    @Published var tomorrowTasks: [ReviewTask] = [
        ReviewTask(id: "t4", userId: "u1", lessonId: "l4", sourceSessionId: "s4",
                   reviewType: .recall, scheduledAt: "", completedAt: nil, status: .pending),
        ReviewTask(id: "t5", userId: "u1", lessonId: "l5", sourceSessionId: "s5",
                   reviewType: .feynman, scheduledAt: "", completedAt: nil, status: .pending),
    ]

    @Published var weekTasks: [ReviewTask] = [
        ReviewTask(id: "t6", userId: "u1", lessonId: "l6", sourceSessionId: "s6",
                   reviewType: .review, scheduledAt: "", completedAt: nil, status: .pending),
        ReviewTask(id: "t7", userId: "u1", lessonId: "l7", sourceSessionId: "s7",
                   reviewType: .recall, scheduledAt: "", completedAt: nil, status: .completed),
    ]

    var totalCount: Int { todayTasks.count + tomorrowTasks.count + weekTasks.count }

    func toggleTask(_ task: ReviewTask) {
        for list in [\ReviewPlanViewModel.todayTasks, \.tomorrowTasks, \.weekTasks] {
            if let idx = self[keyPath: list].firstIndex(where: { $0.id == task.id }) {
                let current = self[keyPath: list][idx].status
                self[keyPath: list][idx].status = current == .completed ? .pending : .completed
                return
            }
        }
    }
}
