//
//  MenuView.swift
//  Gran Fondo
//
//  Created by Willem L. Middelkoop on 06/05/2024.
//

import SwiftUI
import HealthKit

struct MenuView: View {
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var bluetoothManager: BluetoothManager
    @EnvironmentObject var activityRecorder: ActivityRecorder
    
    @State var unitPreference: UnitsPreference = .Metric
    @State var preferredScope: DataPointScope = .sinceStart
    @State var sex: HKBiologicalSex = .male
    
    @State var weight: Double = 70 // Default in kg
    @State var height: Double = 175 // Default in cm
    
    @State var heartRateRest: Int = 60
    @State var heartRateMax: Int = 200
   
    @State private var showSensorView = false
    @State private var showHeroView = false

    var body: some View {
        
        NavigationView {
            
            VStack{
                
                // Header with text and image
               HStack(alignment: .center) {
                   Image("icon")
                          .resizable()
                          .aspectRatio(contentMode: .fill)
                          .frame(width: 85, height: 85)
                          .clipped()
                          .cornerRadius(8)
                   VStack(alignment: .leading){
                       Text("Track your rides and runs effortlessly with Gran Fondo.")
                           .font(.headline)
                           .fontWeight(.semibold)
                           .foregroundColor(.primary)
                           .padding(.bottom, 5)
                       Text("Made with ❤️ by fellow cyclist and runner Willem L. Middelkoop.")
                           .font(.system(size:12))
                           .fontWeight(.bold)
                           .foregroundColor(.secondary)
                           .padding(0)
                   }.padding()
               }
               .padding()
                
                Form {
                    Section(header: Text("Graphs and metrics")) {
                        Text("Data displays automatically based on what's available.")
                        
                       Picker("Units", selection: $unitPreference) {
                            Text("Metric ").tag(UnitsPreference.Metric)
                            Text("Imperial").tag(UnitsPreference.Imperial)
                        }.onChange(of: unitPreference) { oldUnitPreference, newUnitPreference in
                            activityRecorder.setUnitPreference(to: newUnitPreference)
                        }.onAppear{
                            unitPreference = activityRecorder.unitsPreference
                        }
                        
                        Picker("Graphs show", selection: $preferredScope) {
                            Text(DataPointScope.lastMinute.description).tag(DataPointScope.lastMinute)
                            Text(DataPointScope.last5Minutes.description).tag(DataPointScope.last5Minutes)
                            Text(DataPointScope.last15Minutes.description).tag(DataPointScope.last15Minutes)
                            Text(DataPointScope.lastHour.description).tag(DataPointScope.lastHour)
                            Text(DataPointScope.sinceStart.description).tag(DataPointScope.sinceStart)
                        }.onChange(of: preferredScope) { oldScope, newScope in
                            activityRecorder.setDataPointScope(to: newScope)
                        }.onAppear{
                            preferredScope = activityRecorder.preferredScope
                        }
                        
                        Text("Tap any graph to adjust the timespan. Tap on any value to toggle its graph visibility.")
                        
                        Button("Configure Bluetooth sensors") {
                            showSensorView = true
                        }.sheet(isPresented: $showSensorView) {
                            SensorView(sensors: $bluetoothManager.sensors, bluetoothManager: bluetoothManager)
                        }
                        
                    }
                    
                    Section(header: Text("Body and Calories")) {
                        Text("The following information is used to better estimate the calories burned by your activity.")
                        
                        Picker("Biological Sex", selection: $sex) {
                            Text("Male").tag(HKBiologicalSex.male)
                            Text("Female").tag(HKBiologicalSex.female)
                            Text("Other").tag(HKBiologicalSex.other)
                            Text("Not Set").tag(HKBiologicalSex.notSet)
                        }
                        //.pickerStyle(SegmentedPickerStyle())
                        .onChange(of: sex) { oldSex, newSex in
                            activityRecorder.setActiveEnergyInputSex(to: newSex)
                        }.onAppear{
                            sex = activityRecorder.activeEnergyInputSex
                        }
                        
                        // Weight input with unit handling
                        HStack {
                            Text("Weight")
                            TextField("Enter weight", value: $weight, format: .number)
                                .keyboardType(.decimalPad)
                                .multilineTextAlignment(.trailing) // Align text
                                .frame(maxWidth: .infinity)
                            Text(unitPreference == .Metric ? "kg" : "lb")
                                .foregroundColor(.gray)
                                .frame(width:40, alignment: .leading)
                        }
                        .onChange(of: unitPreference) { oldUnit, newUnit in
                            if newUnit == .Metric {
                                weight = weight / 2.20462 // Convert lb to kg
                            } else {
                                weight = weight * 2.20462 // Convert kg to lb
                            }
                        }.onChange(of: weight) { oldWeight, newWeight in
                            if newWeight < 0 || newWeight > 1000 {
                                weight = 0
                            }
                            
                            activityRecorder.setActiveEnergyInputWeight(to: weight)
                        }.onAppear{
                            weight = activityRecorder.activeEnergyInputWeight
                            weight = (weight * 10).rounded() / 10
                        }
                        
                        // Height input with unit handling
                        HStack {
                            Text("Height")
                            TextField("Enter height", value: $height, format: .number)
                                .keyboardType(.decimalPad)
                                .multilineTextAlignment(.trailing) // Align text
                                .frame(maxWidth: .infinity)
                            Text(unitPreference == .Metric ? "cm" : "in")
                                .foregroundColor(.gray)
                                .frame(width:40, alignment: .leading)
                        }
                        .onChange(of: unitPreference) { oldUnit, newUnit in
                            if newUnit == .Metric {
                                height = height * 2.54 // Convert in to cm
                            } else {
                                height = height / 2.54 // Convert cm to in
                            }
                        }
                        .onChange(of: height) { oldHeight, newHeight in
                            if newHeight < 0 || newHeight > 1000 {
                                height = 0
                            }
                            activityRecorder.setActiveEnergyInputHeight(to: height)
                            
                        }.onAppear{
                            height = activityRecorder.activeEnergyInputHeight
                            height = (height * 10).rounded() / 10
                        }
                        
                        // Resting Heart Rate input
                        HStack {
                            Text("Resting Heart Rate")
                                
                            Spacer()
                            
                            TextField("Enter resting HR", value: $heartRateRest, format: .number)
                                .keyboardType(.numberPad)
                                .multilineTextAlignment(.trailing) // Align text
                                .frame(maxWidth: 50)//.infinity)
                                .onChange(of: heartRateRest) { oldHeartRateRest, newHeartRateRest in
                                    if newHeartRateRest < 0 || newHeartRateRest > 200 {
                                        heartRateRest = 60 // Reset to default if invalid
                                    }else{
                                        heartRateRest = newHeartRateRest
                                    }
                                    
                                    activityRecorder.setActiveEnergyInputHeartRateRest(to: heartRateRest)
                                }
                            Text("bpm")
                                .foregroundColor(.gray)
                                .frame(width:40, alignment: .leading)
                        }
                        .onAppear {
                            heartRateRest = activityRecorder.activeEnergyInputHeartRateRest
                        }

                        // Maximum Heart Rate input
                        HStack {
                            Text("Maximum Heart Rate")
                            Spacer()
                            TextField("Enter max HR", value: $heartRateMax, format: .number)
                                .keyboardType(.numberPad)
                                .multilineTextAlignment(.trailing) // Align text
                                .frame(maxWidth: 50)//.infinity)
                                .onChange(of: heartRateMax) { oldHeartRateMax, newHeartRateMax in
                                    if newHeartRateMax < 0 || newHeartRateMax > 220 {
                                        heartRateMax = 200 // Reset to default if invalid
                                    }else{
                                        heartRateMax = newHeartRateMax
                                    }
                                    activityRecorder.setActiveEnergyInputHeartRateMax(to: heartRateMax)
                                }
                            Text("bpm")
                                .foregroundColor(.gray)
                                .frame(width:40, alignment: .leading)
                        }
                        .onAppear {
                            heartRateMax = activityRecorder.activeEnergyInputHeartRateMax
                        }
                    }
                    
                    
                    Section(header: Text("Support Gran Fondo — Become a Hero!")) {
                        Text("By supporting Gran Fondo, you not only enhance your app experience but also support its commitment to privacy and ad-free usage. \n\nEvery subscription directly funds further development, helping me to test and integrate more Bluetooth sensors and refine features.\n🙏 Thank you, Willem.")
                        
                        
                        Button("Buy or Subscribe") {
                            showHeroView = true
                        }.sheet(isPresented: $showHeroView) {
                            HeroView()
                        }
                        
                    }
                    
                    Section(header: Text("Links")) {
                        Button("Follow Willem on X") {
                            let url = URL(string: "https://x.com/wlmiddelkoop/")!
                            UIApplication.shared.open(url)
                        }
                        Button("Willem's Blog") {
                            let url = URL(string: "https://willem.com/blog/")!
                            UIApplication.shared.open(url)
                        }
                       Button("Privacy Statement") {
                            let url = URL(string: "https://willem.com/etcetera/granfondo.app/privacy/")!
                            UIApplication.shared.open(url)
                        }
                        Button("Terms of Use (EULA)") {
                            let url = URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!
                            UIApplication.shared.open(url)
                        }
                    }
                    
                }.navigationBarTitle("Gran Fondo", displayMode: .inline)
                    .navigationBarItems(trailing: Button("Done") {
                        presentationMode.wrappedValue.dismiss()
                })
            }
        }
    }
}

