import SwiftUI

struct CustomTabBar: View {
    @EnvironmentObject private var selectedTabModel: SelectedTabModel
    @StateObject private var viewModel = CustomTabBarViewModel()
    @Environment(\.openURL) var openURL
    @ObservedObject var my = SharingData.my
    @ObservedObject var message = SharingData.message
    @ObservedObject var location = SharingData.location
    @ObservedObject var pushHistory = SharingData.pushHistory

    var body: some View {
        VStack(spacing: 0){
            Divider()

            HStack(spacing: 0){
                ForEach(Tab.allCases, id: \.rawValue) { tab in
                    VStack{
                        ZStack(alignment: .bottomTrailing) {
                            if !SharingData.my.isCommunication && tab == Tab.chat {
                                Image("tab_chat_Invalid")
                                    .onTapGesture {
                                        viewModel.handleTabSelection(
                                            selectedTabModel: selectedTabModel,
                                            tab: tab,
                                            message: message,
                                            history: pushHistory,
                                            location: location,
                                        )
                                    }
                            } else {
                                Image(selectedTabModel.activeTab == tab ? tab.rawValue + "_selected" : tab.rawValue)
                                    .onTapGesture {
                                        viewModel.handleTabSelection(
                                            selectedTabModel: selectedTabModel,
                                            tab: tab,
                                            message: message,
                                            history: pushHistory,
                                            location: location,
                                        )
                                    }
                            }

                            if tab == Tab.chat {
                                NotificationBadge(viewModel: viewModel.chatBadgeViewModel, font: FontStyle.VersionText.font)
                            }

                            if tab == Tab.alert {
                                NotificationBadge(viewModel: viewModel.alertBadgeViewModel, font: FontStyle.VersionText.font)
                            }
                        }

                        Text(tab.title)
                            .font(.caption)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .contentShape(Rectangle())
                }
            }
            .frame(height: LayoutConstants.tabHeight)
        }
        .background(ColorSet.BottomNav.color)
        .modifier(ChangeModeAlertModifier(
            isPresented: $selectedTabModel.isShowChangeEmrMode,
            currentMode: message.mode,
            onConfirm: {
                var chatMode = message.mode
                chatMode.toggle()
                let signalRService = SignalR()
                signalRService.chatMode(mode: chatMode, completion: responseChatMode)
                message.sendInf = true

                DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                    restartChatMode()
                }
            }))
        .modifier(LocationAlertModifier(isPresented: $selectedTabModel.isLocationAlert))
        .modifier(UpdateAlertModifier(isPresented: $my.isUpDate, appStoreURL: URL(string: HttpRequestType.AppStore.rawValue)!))
        .modifier(WarningModeAlertModifier(isPresented: $viewModel.isModeAlert, isSignalrRestert: $viewModel.isSignalrRestart,
            onConfirm: {
                let signalRService = SignalR()
                signalRService.startConnection()
                viewModel.isSignalrRestart = false
            }))
        //MARK: - チャットTab上の既読マーク
        .onChange(of: message.viewCnt) { newValue in
            viewModel.chatBadgeViewModel.updateViewCnt(to: newValue)
        }
        //MARK: - アラートTab上の既読マーク
        .onChange(of: pushHistory.viewCnt) { newValue in
            viewModel.alertBadgeViewModel.updateViewCnt(to: newValue)
        }
    }

    //MARK: - Warninngモードレスポンス
    func responseChatMode(error: Error?) {
        print(debug: "responseChatMode")
        message.sendInf = false

        if let e = error {
            print(debug: "Error chat:\(e)")
            viewModel.isModeAlert = true
        } else {
            message.changeMode()
        }
    }

    //MARK: - モード変更レスポンスが無かった場合
    func restartChatMode() {
        if message.sendInf {
            let signalRService = SignalR()
            signalRService.stopConnection()
            Thread.sleep(forTimeInterval: 1.0)

            viewModel.isSignalrRestart = true
        }
    }
}

