//
//  TimePickerView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI
import Bedrock

struct TimePickerView: View {
    @Binding var timeString: String
    @State private var selectedTime = Date()
    
    var body: some View {
        DatePicker("", selection: $selectedTime, displayedComponents: .hourAndMinute)
            .labelsHidden()
            .tint(AppAccent.primary)
            .onAppear {
                updateSelectedTimeFromString()
            }
            .onChange(of: selectedTime) { _, newTime in
                updateStringFromTime(newTime)
            }
            .onChange(of: timeString) { _, _ in
                updateSelectedTimeFromString()
            }
    }
    
    private func updateSelectedTimeFromString() {
        let components = timeString.split(separator: ":")
        guard components.count == 2,
              let hour = Int(components[0]),
              let minute = Int(components[1]) else {
            return
        }
        
        let calendar = Calendar.current
        let now = Date()
        let dateComponents = calendar.dateComponents([.year, .month, .day], from: now)
        
        var newComponents = dateComponents
        newComponents.hour = hour
        newComponents.minute = minute
        
        if let newDate = calendar.date(from: newComponents) {
            selectedTime = newDate
        }
    }
    
    private func updateStringFromTime(_ time: Date) {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        timeString = formatter.string(from: time)
    }
}
