import SwiftUI

struct MainView: View {
    @EnvironmentObject private var store: SecureStore

    @State private var status = "Connected"
    @State private var keywords: [String] = []
    @State private var whitelist: [String] = []
    @State private var blacklist: [String] = []
    @State private var isBusy = false
    @State private var appeared = false
    @State private var heartbeatTimer: Timer?

    private var actionsDisabled: Bool {
        isBusy || store.accessBlocked
    }

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 16) {
                    if store.accessBlocked {
                        BrandCard {
                            VStack(alignment: .leading, spacing: 6) {
                                Text("Full access required")
                                    .font(.headline)
                                    .foregroundStyle(BrandTheme.ink)
                                Text(store.accessBlockedMessage ?? "Trial ended — upgrade to full access.")
                                    .font(.subheadline)
                                    .foregroundStyle(.orange)
                            }
                        }
                    }

                    BrandCard {
                        HStack(spacing: 14) {
                            Group {
                                if let logo = store.brandLogoUrl, let url = URL(string: logo) {
                                    AsyncImage(url: url) { phase in
                                        switch phase {
                                        case .success(let image):
                                            image.resizable().scaledToFit()
                                        default:
                                            Image("AppLogo").resizable().scaledToFit()
                                        }
                                    }
                                } else {
                                    Image("AppLogo").resizable().scaledToFit()
                                }
                            }
                            .frame(width: 56, height: 56)
                            .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))

                            VStack(alignment: .leading, spacing: 4) {
                                Text(store.displayAppName)
                                    .font(.title3.weight(.bold))
                                    .foregroundStyle(BrandTheme.ink)
                                Text(store.accessBlocked ? "Blocked" : status)
                                    .font(.caption.weight(.semibold))
                                    .foregroundStyle(store.accessBlocked ? .orange : BrandTheme.accent)
                            }
                            Spacer()
                        }
                    }

                    BrandCard {
                        VStack(alignment: .leading, spacing: 10) {
                            Text("Device")
                                .font(.headline)
                                .foregroundStyle(BrandTheme.ink)
                            labeled("Company", store.companyName ?? "—")
                            labeled("Name", store.deviceName ?? "—")
                            labeled("Device ID", store.deviceUid ?? "—")
                            labeled("Status", store.accessBlocked ? "Blocked" : status)
                        }
                    }

                    BrandCard {
                        VStack(spacing: 10) {
                            Button("Send heartbeat") {
                                Task { await sendHeartbeat() }
                            }
                            .buttonStyle(.borderedProminent)
                            .tint(BrandTheme.accent)
                            .disabled(actionsDisabled)
                            .frame(maxWidth: .infinity)

                            Button("Send test message") {
                                Task { await sendTestMessage() }
                            }
                            .buttonStyle(.borderedProminent)
                            .tint(BrandTheme.accent)
                            .disabled(actionsDisabled)
                            .frame(maxWidth: .infinity)

                            Button("Sync Previous Messages") {
                                status = "SMS history sync is only available on Android."
                            }
                            .buttonStyle(.bordered)
                            .tint(BrandTheme.accent)
                            .disabled(true)
                            .frame(maxWidth: .infinity)

                            Button("Refresh keywords & filters") {
                                Task { await refreshFilters() }
                            }
                            .buttonStyle(.bordered)
                            .tint(BrandTheme.accent)
                            .disabled(actionsDisabled)
                            .frame(maxWidth: .infinity)
                        }
                    }

                    if !keywords.isEmpty {
                        BrandCard {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Keywords").font(.headline)
                                ForEach(keywords, id: \.self) { Text($0).foregroundStyle(BrandTheme.muted) }
                            }
                        }
                    }

                    if !whitelist.isEmpty || !blacklist.isEmpty {
                        BrandCard {
                            VStack(alignment: .leading, spacing: 8) {
                                Text("Sender filters").font(.headline)
                                if !whitelist.isEmpty {
                                    Text("Whitelist: \(whitelist.joined(separator: ", "))")
                                        .foregroundStyle(BrandTheme.muted)
                                }
                                if !blacklist.isEmpty {
                                    Text("Blacklist: \(blacklist.joined(separator: ", "))")
                                        .foregroundStyle(BrandTheme.muted)
                                }
                            }
                        }
                    }

                    Button("Logout", role: .destructive) {
                        store.clearSession()
                    }
                    .buttonStyle(.bordered)
                    .padding(.top, 4)
                }
                .padding(20)
                .opacity(appeared ? 1 : 0)
                .offset(y: appeared ? 0 : 14)
            }
            .navigationTitle(store.displayAppName)
            .scrollContentBackground(.hidden)
            .background(BrandTheme.pageBackground.ignoresSafeArea())
            .tint(BrandTheme.accent)
            .onAppear {
                withAnimation(.spring(response: 0.55, dampingFraction: 0.86)) {
                    appeared = true
                }
                startForegroundHeartbeat()
            }
            .onDisappear {
                heartbeatTimer?.invalidate()
                heartbeatTimer = nil
            }
            .task {
                if store.accessBlocked {
                    status = store.accessBlockedMessage ?? "Full access required"
                } else {
                    await refreshFilters()
                }
            }
        }
    }

    /// iOS cannot run the Android SMS foreground service, so the device app keeps
    /// itself "online" with a lightweight heartbeat while the dashboard is open.
    private func startForegroundHeartbeat() {
        heartbeatTimer?.invalidate()
        let timer = Timer(timeInterval: 60, repeats: true) { _ in
            Task { @MainActor in
                guard !store.accessBlocked else { return }
                await sendHeartbeat()
            }
        }
        RunLoop.main.add(timer, forMode: .common)
        heartbeatTimer = timer
    }

    private func labeled(_ title: String, _ value: String) -> some View {
        HStack {
            Text(title).foregroundStyle(BrandTheme.muted)
            Spacer()
            Text(value).foregroundStyle(BrandTheme.ink).fontWeight(.medium)
        }
        .font(.subheadline)
    }

    private func handleAccessDenied(_ error: NotifyHubError) {
        let message = error.localizedDescription ?? "Full access required"
        store.markAccessBlocked(message: message)
        status = message
    }

    private func sendHeartbeat() async {
        isBusy = true
        defer { isBusy = false }
        do {
            let response = try await APIClient.shared.heartbeat()
            store.applyBranding(response.branding)
            store.clearAccessBlock()
            status = "Heartbeat ok"
        } catch let error as NotifyHubError where error.isAccessDenied {
            handleAccessDenied(error)
        } catch let error as NotifyHubError where error.isMaintenance {
            status = error.localizedDescription
        } catch {
            status = error.localizedDescription
        }
    }

    private func sendTestMessage() async {
        guard let deviceUid = store.deviceUid else {
            status = "Device not registered"
            return
        }
        isBusy = true
        defer { isBusy = false }
        do {
            try await APIClient.shared.sendTestMessage(deviceUid: deviceUid)
            status = "Test message sent"
        } catch let error as NotifyHubError where error.isAccessDenied {
            handleAccessDenied(error)
        } catch let error as NotifyHubError where error.isMaintenance {
            status = error.localizedDescription
        } catch {
            status = error.localizedDescription
        }
    }

    private func refreshFilters() async {
        isBusy = true
        defer { isBusy = false }
        do {
            async let keywordTask = APIClient.shared.fetchKeywords()
            async let filterTask = APIClient.shared.fetchSenderFilters()
            keywords = try await keywordTask
            let filters = try await filterTask
            whitelist = filters.whitelist
            blacklist = filters.blacklist
            status = "Filters updated"
        } catch let error as NotifyHubError where error.isAccessDenied {
            handleAccessDenied(error)
        } catch let error as NotifyHubError where error.isMaintenance {
            status = error.localizedDescription
        } catch {
            status = error.localizedDescription
        }
    }
}
