//
// Copyright 2021-2024 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
// Please see LICENSE files in the repository root for full details.
//

import SwiftUI
import AVKit

struct AuthenticationServerSelectionScreen: View {
    // MARK: - Properties
    
    // MARK: Private
    
    @Environment(\.theme) private var theme
    
    
    @State private var showAlertForMissingCameraAuthorization = false
    @State private var showAlertForInvalidServer = false
    @State private var isEditingTextField = false
    @State private var presentQRCodeScanner = false
    @State private var qrCode = ""

    // bwi #4976 show maintenance alert
    @State private var isFetchingDowntime = false
    @State private var activeAlert: ServerMaintenanceAlertType = .showInvalidAppVersionAlert
    
    private var textFieldFooterColor: Color {
        viewModel.viewState.hasValidationError ? theme.colors.alert : theme.colors.tertiaryContent
    }
    
    // MARK: Public
    
    @ObservedObject var viewModel: AuthenticationServerSelectionViewModel.Context
    
    // MARK: Views
    
    var body: some View {
        GeometryReader { _ in
            ScrollView {
                VStack(spacing: 8) {
                    header
                        .padding(.top, OnboardingMetrics.topPaddingToNavigationBar)
                        .padding(.bottom, 16)
                    
                    if BWIBuildSettings.shared.allowScanServerQRCode {
                        scanButton
                            .alert(isPresented: $showAlertForMissingCameraAuthorization)  {
                                Alert(
                                    title: Text(BWIL10n.authenticationServerSelectionQrMissingAuthorizationTitle),
                                    message: Text(BWIL10n.authenticationServerSelectionQrMissingAuthorizationMessage),
                                    primaryButton: .default(Text(VectorL10n.settingsTitle), action: openSettingsApp),
                                    secondaryButton: .cancel())
                            }
                    }

                    serverForm
                        .alert(item: $viewModel.alertInfo) { $0.alert }

                    if BWIBuildSettings.shared.authScreenShowTestServerOptions {
                        serverSelectionButton
                    }
                }
                .readableFrame()
                .padding(.horizontal, 16)
            }


        }
        .background(theme.colors.background.ignoresSafeArea())
        .toolbar { toolbar }
        .accentColor(theme.colors.accent)
        .sheet(isPresented: $presentQRCodeScanner) {
            AuthenticationServerSelectionQRCodeScanner(qrCode: $qrCode)
        }
        .onChange(of: qrCode) { newValue in
            if !qrCode.isEmpty {
                viewModel.homeserverAddress = qrCode
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    self.submit()
                }
            }
        }
        .alert(isPresented: $viewModel.showAlert, content: {
            if viewModel.isInvalidServerAlert {
                return self.invalidServerAlert()
            } else {
                return ServerDowntimeDefaultService.shared.alert(alertType: activeAlert) {
                    self.submit()
                }
            }
        })

    }
    
    /// The title, message and icon at the top of the screen.
    var header: some View {
        VStack(spacing: 8) {
            if BWIBuildSettings.shared.bumLoginFlowLayout || BWIBuildSettings.shared.bwiLoginFlowLayout {
                ServerIcon(image: nil, size: OnboardingMetrics.iconSize)
                    .padding(.bottom, 16)
            } else {
                OnboardingIconImage(image: Asset.Images.welcomeExperience1)
                    .padding(.bottom, 16)
            }
            
            Text(viewModel.viewState.headerTitle)
                .font(theme.fonts.title2B)
                .multilineTextAlignment(.center)
                .foregroundColor(theme.colors.primaryContent)
                .accessibilityIdentifier("headerTitle")
            
            Text(viewModel.viewState.headerMessage)
                .font(theme.fonts.body)
                .multilineTextAlignment(.center)
                .foregroundColor(theme.colors.secondaryContent)
                .accessibilityIdentifier("headerMessage")
        }
    }
    
    var scanButton: some View {
        VStack(spacing: 8) {
            Button {
                if AVCaptureDevice.authorizationStatus(for: .video) == .denied {
                    showAlertForMissingCameraAuthorization = true
                } else {
                    qrCode = ""
                    presentQRCodeScanner = true
                }
            } label: {
                Text(viewModel.viewState.scanCodeButtonTitle)
            }
            .buttonStyle(PrimaryActionButtonStyle())
            .accessibilityIdentifier("qrCodeButton")
            
            
            Text(VectorL10n.or)
                .foregroundColor(theme.colors.secondaryContent)
                .padding(5)
        }
    }
    
    /// The text field and confirm button where the user enters a server URL.
    var serverForm: some View {
        VStack(alignment: .leading, spacing: 12) {
            VStack(spacing: 8) {
                textField
                    .onSubmit(submit)
                
                if case let .message(errorMessage) = viewModel.viewState.footerError {
                    Text(errorMessage)
                        .font(theme.fonts.footnote)
                        .foregroundColor(textFieldFooterColor)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .accessibilityIdentifier("textFieldFooter")
                }
            }
            
            Button(action: startButtonAction) {
                Text(viewModel.viewState.buttonTitle)
            }
            .buttonStyle(PrimaryActionButtonStyle())
            .disabled(viewModel.viewState.hasValidationError)
            .accessibilityIdentifier("confirmButton")
        }
    }
    
    var textField: some View {
        TextField(BWIL10n.authenticationServerSelectionServerUrl, text: $viewModel.homeserverAddress) {
            isEditingTextField = $0
        }
        .keyboardType(.URL)
        .autocapitalization(.none)
        .disableAutocorrection(true)
        .textFieldStyle(BorderedInputFieldStyle(isEditing: isEditingTextField,
                                                isError: viewModel.viewState.isShowingFooterError))
        .onChange(of: viewModel.homeserverAddress) { _ in viewModel.send(viewAction: .clearFooterError) }
        .accessibilityIdentifier("addressTextField")
    }
    
    @ViewBuilder
    var sunsetBanners: some View {
        if viewModel.viewState.footerError == .sunsetBanner, let replacementApp = BuildSettings.replacementApp {
            VStack(spacing: 16) {
                SunsetOIDCRegistrationBanner(homeserverAddress: viewModel.homeserverAddress, 
                                             replacementApp: replacementApp)
                
                SunsetDownloadBanner(replacementApp: replacementApp) {
                    viewModel.send(viewAction: .downloadReplacementApp(replacementApp))
                }
            }
            .padding(.vertical, 4)
            .padding(.bottom, 16)
            .accessibilityIdentifier("sunsetBanners")
        }
    }
    
    @ToolbarContentBuilder
    var toolbar: some ToolbarContent {
        ToolbarItem(placement: .cancellationAction) {
            if viewModel.viewState.hasModalPresentation {
                Button { viewModel.send(viewAction: .dismiss) } label: {
                    Text(VectorL10n.cancel)
                }
                .accessibilityLabel(VectorL10n.cancel)
                .accessibilityIdentifier("dismissButton")
            }
        }
    }
    
    /// Sends the `confirm` view action so long as the text field input is valid.
    private func submit() {
        guard !viewModel.viewState.hasValidationError else { return }
        // BWI: #6777 validate and use base url from wellknown
        viewModel.send(viewAction: .confirm)
        // BWI END
    }
    
    /// bwi: jump directly into the iOS settings app to allow camera access
    private func openSettingsApp() {
        if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
    
    // bwi: show server selection button
    var serverSelectionButton: some View {
        VStack() {
            Menu(content: {
                ForEach(ServerURLHelper.shared.serverSettings, id: \.self) { server in
                    Button(server.name, action: {
                        viewModel.homeserverAddress = server.serverUrl
                    })
                }
            }, label: {
                Button(action: { return }) {
                    Text(BWIL10n.bwiAuthBetaSelectionButtonTitle)
                }
                .buttonStyle(PrimaryActionButtonStyle())
            })
        }
    }
    
    // bwi: show alert with advertizment link if URL is valid
    private func invalidServerAlert() -> Alert {
        if let url = URL(string: BWIBuildSettings.shared.bumAdvertizementURLString) {
            return Alert(
                title: Text(BWIL10n.authenticationServerSelectionServerDeniedTitle),
                message: Text(BWIL10n.authenticationServerSelectionServerDeniedMessage),
                primaryButton: .default(Text(BWIL10n.authenticationServerSelectionServerDeniedAdvertizementWebsiteButton), action: {
                    // BWI: #6777 reset isInvalidServerAlert on dismiss, otherwise server downtime errors are not displayed
                    viewModel.isInvalidServerAlert = false
                    // BWI END
                    UIApplication.shared.vc_open(url, completionHandler: nil)
                }),
                secondaryButton: .default(Text(VectorL10n.ok), action:  {
                    // BWI: #6777 reset isInvalidServerAlert on dismiss, otherwise server downtime errors are not displayed
                    viewModel.isInvalidServerAlert = false
                    // BWI END
                }))
            
        } else {
            return Alert(
                title: Text(BWIL10n.authenticationServerSelectionServerDeniedTitle),
                message: Text(BWIL10n.authenticationServerSelectionServerDeniedMessage),
                dismissButton: .default(Text(VectorL10n.ok), action:  {
                    // BWI: #6777 reset isInvalidServerAlert on dismiss, otherwise server downtime errors are not displayed
                    viewModel.isInvalidServerAlert = false
                    // BWI END
                }))
        }
    }

    // bwi #4295 ask for maintenance before going to login
    private func startButtonAction() {
        // #4295: Only ask for maintenance here when there is no server selection afterwards
        if BWIBuildSettings.shared.enableMaintenanceInfoOnLogin {
            isFetchingDowntime = true   // show progresview
            
            if BWIBuildSettings.shared.useTestDataForDowntime {
                ServerDowntimeDefaultService.shared.fetchDowntimes {
                    self.isFetchingDowntime = false // hide progressview
                    self.showAlertIfNeeded()
                }
            } else {
                ServerDowntimeDefaultService.shared.fetchDowntimesWithDirectRequest(localUrlString:viewModel.homeserverAddress) { success, _, _, _ in
                    DispatchQueue.main.async {
                        self.isFetchingDowntime = false   // hide progressview
                        if success {
                            self.showAlertIfNeeded()
                        } else {
                            // hotfix 2.9.1 if request ist no successful there probably is no maintenance on server -> don't show popup
                            self.submit()
                        }
                    }
                }
            }
        } else {
            self.submit()
        }
    }
    
    private func showAlertIfNeeded() {
        if ServerDowntimeDefaultService.shared.showAlert() {
            activeAlert = ServerDowntimeDefaultService.shared.alertType()
            // BWI: #6777 moved boolean to viewmodel bindings
            viewModel.showAlert = true
            // BWI END
        } else {
            self.submit()
        }
    }
}

// MARK: - Previews

@available(iOS 15.0, *)
struct AuthenticationServerSelection_Previews: PreviewProvider {
    static let stateRenderer = MockAuthenticationServerSelectionScreenState.stateRenderer
    static var previews: some View {
        stateRenderer.screenGroup(addNavigation: true)
            .navigationViewStyle(.stack)
    }
}
