import SwiftUI
import BackgroundTasks

@main
struct MataElang404App: App {
  @Environment(\.scenePhase) private var phase
  init() {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: heartbeatTaskId, using: nil) { task in
      Heartbeat.schedule()
      let t = Task { do { try await Heartbeat.send(); task.setTaskCompleted(success: true) } catch { task.setTaskCompleted(success: false) } }
      task.expirationHandler = { t.cancel() }
    }
  }
  var body: some Scene {
    WindowGroup { RootView().preferredColorScheme(.dark) }
      .onChange(of: phase) { if $0 == .background, Store.deviceToken != nil { Heartbeat.schedule() } }
  }
}

struct RootView: View {
  @State private var enrolled = Store.deviceToken != nil
  var body: some View {
    ZStack {
      Color(red: 0.01, green: 0.03, blue: 0.09).ignoresSafeArea()
      if enrolled { HomeView { enrolled = false } } else { SetupView { enrolled = true } }
    }
  }
}

struct SetupView: View {
  let onDone: () -> Void
  @State private var pairMode = false
  @State private var ident = ""; @State private var pw = ""; @State private var code = ""
  @State private var consent = false; @State private var busy = false; @State private var err = ""
  var body: some View {
    ScrollView {
      VStack(alignment: .leading, spacing: 14) {
        Text("Mata Elang404").font(.largeTitle.bold())
        Text("Pantau • Lindungi • Amankan").foregroundColor(.gray)
        Picker("", selection: $pairMode) { Text("Login").tag(false); Text("Kode Pairing").tag(true) }.pickerStyle(.segmented)
        if pairMode {
          TextField("Kode pairing (8 karakter)", text: $code).textInputAutocapitalization(.characters).autocorrectionDisabled().textFieldStyle(.roundedBorder)
        } else {
          TextField("Email atau username", text: $ident).textInputAutocapitalization(.never).autocorrectionDisabled().textFieldStyle(.roundedBorder)
          SecureField("Password", text: $pw).textFieldStyle(.roundedBorder)
        }
        Toggle(isOn: $consent) { Text(consentText).font(.footnote) }
        if !err.isEmpty { Text(err).foregroundColor(.red) }
        Button { Task { await enroll() } } label: { Text(busy ? "Memproses…" : "Daftarkan Perangkat").frame(maxWidth: .infinity) }
          .buttonStyle(.borderedProminent).disabled(!consent || busy)
      }.padding(24)
    }
  }
  private func enroll() async {
    busy = true; err = ""; defer { busy = false }
    do {
      var data: [String: Any]
      if pairMode {
        var b = deviceInfo(consent: true); b["pairing_code"] = code.uppercased()
        data = try await API.call("POST", "/device/pair", body: b)["data"] as? [String: Any] ?? [:]
      } else {
        let l = try await API.call("POST", "/auth/login", body: ["identifier": ident, "password": pw])
        let tok = (l["data"] as? [String: Any])?["token"] as? String
        var b = deviceInfo(consent: true); b["method"] = "manual"
        data = try await API.call("POST", "/device/enroll", body: b, token: tok)["data"] as? [String: Any] ?? [:]
      }
      guard let dt = data["device_token"] as? String, let did = data["device_id"] as? String else { err = "Respons tidak lengkap"; return }
      Store.deviceToken = dt; Store.deviceId = did; Store.locationOn = false
      Heartbeat.schedule(); onDone()
    } catch let e as APIError { err = e.message } catch { err = "Gagal" }
  }
}

struct PendingSession: Equatable { let id: String; let type: String }

struct HomeView: View {
  let onLogout: () -> Void
  @StateObject private var loc = LocationService()
  @State private var sharing = Store.locationOn
  @State private var pending: [PendingSession] = []
  @State private var status = "Menghubungkan…"; @State private var err = ""
  private var deviceId: String { Store.deviceId ?? "" }

  var body: some View {
    ScrollView {
      VStack(alignment: .leading, spacing: 14) {
        Text("Mata Elang404").font(.largeTitle.bold())
        card { VStack(alignment: .leading) { Text("Sistem Aktif").font(.headline); Text(status).foregroundColor(.gray) } }
        card {
          VStack(alignment: .leading, spacing: 6) {
            Toggle(isOn: Binding(get: { sharing }, set: { on in Task { await setSharing(on) } })) {
              VStack(alignment: .leading) { Text("Bagikan lokasi").font(.headline); Text("Hanya saat app terbuka. Matikan kapan saja.").font(.footnote).foregroundColor(.gray) }
            }
            if sharing { Text("● Lokasi sedang dibagikan").foregroundColor(.green) }
          }
        }
        if !err.isEmpty { Text(err).foregroundColor(.red) }
        Button(role: .destructive) { Task { await revoke() } } label: { Text("Cabut pendaftaran perangkat ini").frame(maxWidth: .infinity) }.buttonStyle(.bordered)
      }.padding(24)
    }
    .task { await loop() }
    .alert("Permintaan sesi pemantauan", isPresented: Binding(get: { pending.first != nil }, set: { _ in })) {
      if pending.first?.type == "location" { Button("Setujui") { respond(true) } }
      Button("Tolak", role: .cancel) { respond(false) }
    } message: {
      Text(pending.first?.type == "location" ? "Administrator meminta sesi berbagi lokasi. Anda dapat menolak atau menghentikannya kapan saja." : "Jenis sesi ini belum didukung di iOS dan akan ditolak.")
    }
  }

  private func card<C: View>(@ViewBuilder _ c: () -> C) -> some View {
    c().padding(16).frame(maxWidth: .infinity, alignment: .leading).background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 18))
  }

  private func logout() { Store.clear(); onLogout() }

  private func setSharing(_ on: Bool) async {
    err = ""
    if on, !(await loc.requestAuthorization()) { err = "Izin lokasi ditolak di Pengaturan iOS"; return }
    do {
      _ = try await API.call("POST", "/device/permission", body: ["device_id": deviceId, "permission": "location", "status": on ? "granted" : "revoked"], token: Store.deviceToken)
      sharing = on; Store.locationOn = on
    } catch let e as APIError { err = e.message } catch {}
  }

  private func respond(_ accept: Bool) {
    guard let s = pending.first else { return }; pending = []
    Task { _ = try? await API.call("POST", "/device/session/respond", body: ["session_id": s.id, "accept": accept], token: Store.deviceToken) }
  }

  private func revoke() async {
    do { _ = try await API.call("POST", "/device/revoke", body: ["device_id": deviceId], token: Store.deviceToken); logout() }
    catch let e as APIError { err = e.message } catch {}
  }

  private func loop() async {
    var tick = 0
    while !Task.isCancelled {
      do {
        try await Heartbeat.send()
        let d = (try await API.call("GET", "/device/detail?id=\(deviceId)", token: Store.deviceToken))["data"] as? [String: Any]
        let s = d?["active_sessions"] as? [[String: Any]] ?? []
        pending = s.compactMap { x in (x["status"] as? String) == "pending" ? PendingSession(id: x["id"] as? String ?? "", type: x["type"] as? String ?? "") : nil }
        if sharing, loc.authorized, tick % 4 == 0, let l = await loc.current() {
          _ = try await API.call("POST", "/device/location", body: ["latitude": l.coordinate.latitude, "longitude": l.coordinate.longitude, "accuracy_m": l.horizontalAccuracy], token: Store.deviceToken)
        }
        status = "Terhubung"; err = ""
      } catch let e as APIError {
        if e.code == 401 { logout(); return }
        status = "Tidak terhubung"; err = e.message
      } catch {}
      tick += 1; try? await Task.sleep(nanoseconds: 15_000_000_000)
    }
  }
}
