import SwiftUI

/// Home: who the phone belongs to, "Take reading", always-listen, Apple Health sharing, plan, recent activity.
struct HomeView: View {
    @EnvironmentObject var settings: Settings
    @EnvironmentObject var ble: BleCollector
    @State private var queued = 0
    @State private var history: [ReadingQueue.Log] = []
    @State private var healthMsg: String?
    @State private var confirmUnpair = false

    private var client: [String: Any] { settings.config?["client"] as? [String: Any] ?? [:] }
    private var patient: [String: Any]? { settings.config?["patient"] as? [String: Any] }

    var body: some View {
        NavigationStack {
            List {
                Section {
                    Text(client["name"] as? String ?? "CarePulse").font(.title2.bold()).foregroundStyle(.purple)
                    Text(patient.map { "For \($0["name"] as? String ?? "")" } ?? "Ward / shared phone – readings go to the patient the device is assigned to").font(.subheadline)
                    if patient == nil { TextField("Patient UHID (ward mode)", text: $settings.wardUHID).textInputAutocapitalization(.characters) }
                }
                Section {
                    Button { ble.start() } label: { Text("Take reading").font(.title2.bold()).frame(maxWidth: .infinity, minHeight: 64) }.buttonStyle(.borderedProminent)
                    Text(ble.status).frame(maxWidth: .infinity).multilineTextAlignment(.center)
                    Toggle("Always listen for my devices", isOn: $settings.autoListen).onChange(of: settings.autoListen) { on in on ? ble.start() : ble.stop() }
                }
                Section { NavigationLink { MedicinesView() } label: { Label("My medicines", systemImage: "pills") } }
                Section("Apple Health") {
                    if HealthKitSync.shared.available {
                        Toggle("Share data from Apple Health / Watch", isOn: $settings.healthEnabled).onChange(of: settings.healthEnabled) { on in
                            guard on else { return }
                            Task {
                                do { try await HealthKitSync.shared.requestAccess(); HealthKitSync.shared.startObserving()
                                     let n = await HealthKitSync.shared.sync(); healthMsg = n > 0 ? "\(n) values queued" : "Nothing new"; await Uploader.run(); await refresh() }
                                catch { healthMsg = error.localizedDescription }
                            }
                        }
                        if let m = healthMsg { Text(m).font(.footnote).foregroundStyle(.secondary) }
                    } else { Text("Apple Health is not available on this device.").font(.footnote) }
                }
                if let sched = settings.config?["schedule"] as? [[String: Any]], !sched.isEmpty {
                    Section("Your plan") { ForEach(sched.indices, id: \.self) { i in
                        let s = sched[i]; Text("\(s["name"] as? String ?? "") – \((s["times"] as? [String])?.joined(separator: ", ") ?? "")")
                    } }
                }
                Section(queued > 0 ? "Recent · \(queued) waiting to send" : "Recent") {
                    ForEach(history) { h in VStack(alignment: .leading) { Text(h.text).foregroundStyle(h.flag == "error" ? .red : .primary); Text(h.at, style: .relative).font(.caption).foregroundStyle(.secondary) } }
                }
                if let help = client["helpline"] as? String, !help.isEmpty { Section { Link("Feeling unwell? Call \(help)", destination: URL(string: "tel:\(help.filter(\.isNumber))")!).foregroundStyle(.red) } }
                Section {
                    Button("Send now") { Task { await Uploader.run(); await refresh() } }
                    Button("Unpair", role: .destructive) { confirmUnpair = true }
                }
            }
            .navigationTitle("CarePulse")
            .refreshable { await Uploader.run(); await refresh() }
            .task { await refresh() }
            .confirmationDialog("Unpair this phone from the hospital?", isPresented: $confirmUnpair) { Button("Unpair", role: .destructive) { ble.stop(); settings.clear() } }
        }
    }

    private func refresh() async { queued = await ReadingQueue.shared.count(); history = await ReadingQueue.shared.recent() }
}
