//
//  SupportButtonView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 19/06/2024.
//

import SwiftUI
import LeStorage
import Zip

extension URL: Identifiable {
    public var id: String {
        return self.absoluteString
    }
}
struct SupportButtonView: View {
    let contentIsUnavailable: Bool
    
    @State private var sentError: ContactManagerError? = nil
    @State private var zipFilePath: URL?
    @EnvironmentObject var networkMonitor: NetworkMonitor

    var messageSentFailed: Binding<Bool> {
        Binding {
            sentError != nil
        } set: { newValue in
            if newValue == false {
                sentError = nil
            }
        }
    }

    var body: some View {
        Group {
            if contentIsUnavailable {
                FooterButtonView("Besoin d'aide ? Un problème ? Contactez-nous !") {
                    _zip()
                }
            } else {
                Button("Signaler un problème") {
                    _zip()
                }
            }
        }
        .alert("Un problème est survenu", isPresented: messageSentFailed) {
            Button("OK") {
            }
        } message: {
            let message = [networkMonitor.connected == false ? "L'appareil n'est pas connecté à internet." as String? : nil, sentError == .mailNotSent ? "Le mail est dans la boîte d'envoi de l'app Mail. Vérifiez son état dans l'app Mail avant d'essayer de le renvoyer." as String? : nil, (sentError == .messageFailed || sentError == .messageNotSent) ? "Le SMS n'a pas été envoyé" as String? : nil, sentError == .mailFailed ? "Le mail n'a pas été envoyé" as String? : nil].compacted().joined(separator: "\n")
            Text(message)
        }
        .sheet(item: $zipFilePath) { zipFilePath in
            MailComposeView(recipients: ["support@padelclub.app"], bccRecipients: nil, body: _getBody(), subject: _getSubject(), attachmentURL: zipFilePath) { result in
                switch result {
                case .cancelled, .saved:
                    self.zipFilePath = nil
                case .failed:
                    self.zipFilePath = nil
                    self.sentError = .mailFailed
                case .sent:
                    if networkMonitor.connected == false {
                        self.zipFilePath = nil
                        self.sentError = .mailNotSent
                    }
                @unknown default:
                    break
                }
            }
            .tint(.master)
        }
    }
    
    private func _getSubject() -> String {
        let device = UIDevice.current
        let iOSVersion = device.systemVersion
        return "[\(PadelClubApp.appVersion), \(iOSVersion), \(_getDeviceIdentifier())] Support Padel Club"
        
    }
    
    private func _getBody() -> String {
        let separator = "---------------------------------------------"
        return ["Décrivez votre problème", "\n\n\n", separator, "token", Store.main.token(), separator, "userId", Store.main.userId, separator, "dataStore userId", DataStore.shared.user.id].compacted().joined(separator: "\n")
    }
    
    private func _getDeviceIdentifier() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }
        return identifier
    }
    
    private func _zip() {
        do {
            let filePath = try Club.storageDirectoryPath()
            self.zipFilePath = try Zip.quickZipFiles([filePath], fileName: "backup") // Zip
        } catch {
            Logger.error(error)
        }
    }
}
