import SwiftUI

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

    @State private var companyName = ""
    @State private var deviceName = ""
    @State private var registrationCode = ""
    @State private var deviceUid = ""
    @State private var apiToken = ""
    @State private var signingSecret = ""
    @State private var status = ""
    @State private var isLoading = false
    @State private var appeared = false

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                BrandLogoView(height: 110)
                    .frame(maxWidth: .infinity)

                Text("Connect this device")
                    .font(.system(size: 28, weight: .bold, design: .rounded))
                    .foregroundStyle(BrandTheme.ink)
                Text("Enter your company name, device name, and registration code")
                    .foregroundStyle(BrandTheme.muted)

                BrandCard {
                    VStack(alignment: .leading, spacing: 12) {
                        Text("Register with code")
                            .font(.headline)
                            .foregroundStyle(BrandTheme.ink)
                        TextField("Company name", text: $companyName)
                            .textInputAutocapitalization(.words)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        TextField("Device name", text: $deviceName)
                            .textInputAutocapitalization(.words)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        TextField("Registration code", text: $registrationCode)
                            .textInputAutocapitalization(.characters)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        Button("Register with code") {
                            Task { await registerWithCode() }
                        }
                        .buttonStyle(.borderedProminent)
                        .tint(BrandTheme.accent)
                        .disabled(isLoading)
                        .frame(maxWidth: .infinity)
                    }
                }

                BrandCard {
                    VStack(alignment: .leading, spacing: 12) {
                        Text("Or use admin-registered credentials")
                            .font(.subheadline.weight(.semibold))
                            .foregroundStyle(BrandTheme.muted)
                        TextField("Device ID (e.g. DEV-00001)", text: $deviceUid)
                            .textInputAutocapitalization(.characters)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        SecureField("API token", text: $apiToken)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        SecureField("Signing secret (required when HMAC is enabled)", text: $signingSecret)
                            .padding(12)
                            .background(RoundedRectangle(cornerRadius: 12).fill(Color.black.opacity(0.03)))
                        Button("Connect with credentials") {
                            Task { await connectWithCredentials() }
                        }
                        .buttonStyle(.bordered)
                        .tint(BrandTheme.accent)
                        .disabled(isLoading)
                        .frame(maxWidth: .infinity)
                    }
                }

                if !status.isEmpty {
                    Text(status)
                        .font(.footnote)
                        .foregroundStyle(.orange)
                }

                Text("iOS cannot read SMS automatically. Use this app for device registration, heartbeat, and test sync. SMS capture requires the Android app.")
                    .font(.footnote)
                    .foregroundStyle(BrandTheme.muted)
            }
            .padding(20)
            .opacity(appeared ? 1 : 0)
            .offset(y: appeared ? 0 : 16)
        }
        .background(BrandTheme.pageBackground.ignoresSafeArea())
        .onAppear {
            withAnimation(.spring(response: 0.55, dampingFraction: 0.86)) {
                appeared = true
            }
        }
    }

    private func registerWithCode() async {
        let company = companyName.trimmingCharacters(in: .whitespaces)
        let name = deviceName.trimmingCharacters(in: .whitespaces)
        let code = registrationCode.trimmingCharacters(in: .whitespaces)

        guard !company.isEmpty, !name.isEmpty, !code.isEmpty else {
            status = "Company name, device name, and registration code are required."
            return
        }

        isLoading = true
        status = "Registering…"
        defer { isLoading = false }

        do {
            let response = try await APIClient.shared.register(
                company: company,
                code: code,
                deviceName: name
            )
            store.saveRegistration(
                deviceUid: response.device_uid,
                apiToken: response.api_token,
                signingSecret: response.signing_secret,
                deviceName: response.device_name
            )
            store.applyBranding(response.branding)
            store.applyCompany(response.company)
            status = ""
        } catch let error as NotifyHubError where error.isAccessDenied {
            status = error.localizedDescription ?? "Trial ended — upgrade to full access."
        } catch let error as NotifyHubError where error.isMaintenance {
            status = error.localizedDescription
        } catch {
            status = error.localizedDescription
        }
    }

    private func connectWithCredentials() async {
        let uid = deviceUid.trimmingCharacters(in: .whitespaces).uppercased()
        let token = apiToken.trimmingCharacters(in: .whitespaces)
        let secret = signingSecret.trimmingCharacters(in: .whitespaces)

        guard !uid.isEmpty, !token.isEmpty else {
            status = "Device ID and API token are required."
            return
        }

        store.saveRegistration(
            deviceUid: uid,
            apiToken: token,
            signingSecret: secret.isEmpty ? nil : secret,
            deviceName: deviceName.trimmingCharacters(in: .whitespaces).isEmpty ? uid : deviceName.trimmingCharacters(in: .whitespaces)
        )

        isLoading = true
        status = "Verifying…"
        defer { isLoading = false }

        do {
            let response = try await APIClient.shared.heartbeat()
            store.applyBranding(response.branding)
            store.clearAccessBlock()
            status = ""
        } catch let error as NotifyHubError where error.isAccessDenied {
            store.clearSession()
            status = error.localizedDescription ?? "Trial ended — upgrade to full access."
        } catch let error as NotifyHubError where error.isMaintenance {
            status = error.localizedDescription
        } catch {
            store.clearSession()
            status = error.localizedDescription
        }
    }
}
