//
//  HistoryMonthView.swift
//  Andromida
//
//  A single month calendar grid showing daily completion progress.
//

import SwiftUI
import Bedrock

/// A calendar grid for a single month with progress rings for each day.
struct HistoryMonthView: View {
    let month: Date
    let selectedRitual: Ritual?
    let completionRate: (Date, Ritual?) -> Double
    let onDayTapped: (Date) -> Void
    
    private let calendar = Calendar.current
    private let weekdaySymbols = Calendar.current.shortWeekdaySymbols
    
    private var monthTitle: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM yyyy"
        return formatter.string(from: month)
    }
    
    private var daysInMonth: [Date?] {
        // Get the first day of the month
        guard let firstOfMonth = calendar.date(from: calendar.dateComponents([.year, .month], from: month)) else {
            return []
        }
        
        // Get the range of days in this month
        guard let range = calendar.range(of: .day, in: .month, for: firstOfMonth) else {
            return []
        }
        
        // Get the weekday of the first day (1 = Sunday, 7 = Saturday)
        let firstWeekday = calendar.component(.weekday, from: firstOfMonth)
        
        // Create array with leading nil placeholders for alignment
        var days: [Date?] = Array(repeating: nil, count: firstWeekday - 1)
        
        // Add actual days
        for day in range {
            if let date = calendar.date(byAdding: .day, value: day - 1, to: firstOfMonth) {
                days.append(date)
            }
        }
        
        return days
    }
    
    private var today: Date {
        calendar.startOfDay(for: Date())
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.medium) {
            // Month header
            Text(monthTitle)
                .font(.headline)
                .foregroundStyle(AppTextColors.primary)
                .padding(.horizontal, Design.Spacing.small)
            
            // Weekday headers
            weekdayHeader
            
            // Day grid
            dayGrid
        }
        .padding(Design.Spacing.medium)
        .background(AppSurface.card)
        .clipShape(.rect(cornerRadius: Design.CornerRadius.large))
    }
    
    private var weekdayHeader: some View {
        HStack(spacing: 0) {
            ForEach(weekdaySymbols, id: \.self) { symbol in
                Text(symbol)
                    .font(.caption2)
                    .foregroundStyle(AppTextColors.tertiary)
                    .frame(maxWidth: .infinity)
            }
        }
    }
    
    private var dayGrid: some View {
        let columns = Array(repeating: GridItem(.flexible(), spacing: Design.Spacing.xSmall), count: 7)
        let dates = daysInMonth
        let progressValues = dates.map { date -> Double? in
            guard let date else { return nil }
            return date > today ? 0 : completionRate(date, selectedRitual)
        }
        
        return LazyVGrid(columns: columns, spacing: Design.Spacing.xSmall) {
            ForEach(Array(dates.enumerated()), id: \.offset) { index, date in
                if let date = date {
                    let isToday = calendar.isDate(date, inSameDayAs: today)
                    let isFuture = date > today
                    
                    // Show all days - future days show with 0 progress and are not tappable
                    HistoryDayCell(
                        date: date,
                        progress: progressValues[index] ?? 0,
                        isToday: isToday,
                        isFuture: isFuture,
                        onTap: { if !isFuture { onDayTapped(date) } }
                    )
                } else {
                    // Placeholder for alignment
                    HistoryDayPlaceholder()
                }
            }
        }
    }
}

#Preview {
    ScrollView {
        HistoryMonthView(
            month: Date(),
            selectedRitual: nil,
            completionRate: { _, _ in Double.random(in: 0...1) },
            onDayTapped: { _ in }
        )
        .padding()
    }
    .background(AppSurface.primary)
}
