//
//  DatesStep.swift
//  SportsTime
//
//  Step 2 of the trip wizard - select travel dates.
//

import SwiftUI

struct DatesStep: View {
    @Environment(\.colorScheme) private var colorScheme
    @Binding var startDate: Date
    @Binding var endDate: Date
    @Binding var hasSetDates: Bool
    let onDatesChanged: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: Theme.Spacing.md) {
            StepHeader(
                title: "When would you like to travel?",
                subtitle: "Tap to select start and end dates"
            )

            DateRangePicker(
                startDate: $startDate,
                endDate: $endDate
            )
            .onChange(of: startDate) { _, _ in
                // Only mark as complete when user has selected both dates (end > start)
                updateHasSetDates()
                onDatesChanged()
            }
            .onChange(of: endDate) { _, _ in
                // Only mark as complete when user has selected both dates (end > start)
                updateHasSetDates()
                onDatesChanged()
            }
        }
        .padding(Theme.Spacing.lg)
        .background(Theme.cardBackground(colorScheme))
        .clipShape(RoundedRectangle(cornerRadius: Theme.CornerRadius.large))
        .overlay {
            RoundedRectangle(cornerRadius: Theme.CornerRadius.large)
                .stroke(Theme.surfaceGlow(colorScheme), lineWidth: 1)
        }
        .onAppear {
            // Auto-validate if dates are already valid (e.g., defaults)
            updateHasSetDates()
        }
    }

    private func updateHasSetDates() {
        // User must select both start and end dates (end date must be after start)
        let calendar = Calendar.current
        let startDay = calendar.startOfDay(for: startDate)
        let endDay = calendar.startOfDay(for: endDate)
        hasSetDates = endDay > startDay
    }
}

// MARK: - Preview

#Preview {
    DatesStep(
        startDate: .constant(Date()),
        endDate: .constant(Date().addingTimeInterval(86400 * 5)),
        hasSetDates: .constant(true),
        onDatesChanged: {}
    )
    .padding()
    .themedBackground()
}
