//
//  MainTabView.swift
//  forShip
//
//  Created by Mamoru Sugita on 2023/10/13.
//

import SwiftUI

enum Tab: String, CaseIterable{
    case map = "tab_map"
    case chat = "tab_chat"
    case alert = "tab_notification"
    case menu = "tab_menu"
    
    var title: String{
        ""
    }
}

struct MainTabView: View {
    @EnvironmentObject var selectedTabModel: SelectedTabModel
    @EnvironmentObject private var sceneDelegate: SceneDelegate
    @State var isSignout = false

    init() {
        let appearance: UITabBarAppearance = UITabBarAppearance()
        appearance.backgroundColor = .clear
        UITabBar.appearance().scrollEdgeAppearance = appearance
        UITabBar.appearance().standardAppearance = appearance
        SharingData.location.focusOwnShip = true
//        EcaCoordinatesTable().setEcaData()
    }

    var body: some View {
        if UIDevice.current.userInterfaceIdiom == .phone {
            @State var isTabShow: Bool = sceneDelegate.tabWindow != nil
            @State var isTaskSel: Bool = selectedTabModel.activeTab == .map

            TabView(selection: $selectedTabModel.activeTab){
                if SharingData.my.isCommunication {
                    ChatView()
                        .tag(Tab.chat)
                }

                ZStack {
                    MapRepresentable()
                    MapInformation()
                }
                .ignoresSafeArea()
                .tag(Tab.map)

                NotificationView()
                    .tag(Tab.alert)

                MenuView(isSignout: $isSignout)
                    .tag(Tab.menu)
            }
            .hideNativeTabBar()
//            .sheet(isPresented: .constant(isTaskSel && isTabShow && SharingData.my.isFuelSwitchTask), content: {
            .sheet(isPresented: .constant(isTaskSel && isTabShow), content: {
                MenuTaskView()
                    .zIndex(0)
                    .presentationDragIndicator(.hidden)
                    .presentationDetents([.height(150), .medium, .fraction(0.99)])
                    .presentationCornerRadius(15)
                    .presentationBackgroundInteraction(.enabled(upThrough: .medium))
                    .presentationBackground(ColorSet.BackgroundSecondary.color)
                    .interactiveDismissDisabled()
            })
        } else if UIDevice.current.userInterfaceIdiom == .pad {
            @State var isPopover: Bool = selectedTabModel.isPoppver

            TabView(selection: $selectedTabModel.activeTab){
                if SharingData.my.isCommunication {
                    ChatView()
                        .tag(Tab.chat)
                }

                ZStack {
                    MapRepresentable()
                    MapInformation()
                }
                .ignoresSafeArea()
                .tag(Tab.map)

                NotificationView()
                    .tag(Tab.alert)

                MenuView(isSignout: $isSignout)
                    .tag(Tab.menu)
            }
            .hideNativeTabBar()
//            .popover(isPresented: .constant(isPopover && SharingData.my.isFuelSwitchTask), attachmentAnchor: .point(.bottom)) {
            .popover(isPresented: .constant(isPopover), attachmentAnchor: .point(.bottom)) {
                MenuTaskView()
                    .presentationCompactAdaptation(.popover)
                    .zIndex(0)
                    .frame(minWidth: 500, maxHeight: 500)
                    .aspectRatio(contentMode: .fit)
                    .presentationCornerRadius(15)
                    .presentationBackgroundInteraction(.enabled(upThrough: .medium))
                    .presentationBackground(ColorSet.BackgroundSecondary.color)
                    .interactiveDismissDisabled()
            }
        }
    }
}

struct CustomTabBar: View {
    @EnvironmentObject private var selectedTabModel: SelectedTabModel
    @State var isLocationAlert = false
    @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
                    Button(action: {
                        selectedTabModel.activeTab = tab
                        if tab == .map {
                            selectedTabModel.isPoppver.toggle()
                            location.focusOwnShip = true
                        } else if tab == .chat {
                            let message = GetMessage()
                            message.readNotification()
                            message.checkUnreadMessages()

                            selectedTabModel.isPoppver = false
                        } else {
                            selectedTabModel.isPoppver = false
                        }
                    }, label: {
                        VStack{
                            ZStack(alignment: .bottomTrailing) {
                                Image(selectedTabModel.activeTab == tab ? tab.rawValue + "_selected" : tab.rawValue)
                                    .font(.title2)

                                //チャットTab上の既読マーク
                                if tab == Tab.chat {
                                    if message.viewCnt != 0 {
                                        if message.viewCnt < 10 {
                                            Ellipse()
                                                .fill(Color.red)
                                                .frame(width: 12, height: 12)
                                                .overlay(
                                                    Text(String(message.viewCnt))
                                                        .font(FontStyle.VersionText.font)
                                                        .foregroundColor(.white)
                                                )
                                        } else {
                                            Ellipse()
                                                .fill(Color.red)
                                                .frame(width: 12, height: 12)
                                                .overlay(
                                                    Text("-")
                                                        .font(FontStyle.VersionText.font)
                                                        .foregroundColor(.white)
                                                )
                                        }
                                    }
                                }

                                if tab == Tab.alert {
                                    if pushHistory.viewCnt != 0 {
                                        if pushHistory.viewCnt < 10 {
                                            Ellipse()
                                                .fill(Color.red)
                                                .frame(width: 12, height: 12)
                                                .overlay(
                                                    Text(String(pushHistory.viewCnt))
                                                        .font(FontStyle.VersionText.font)
                                                        .foregroundColor(.white)
                                                )
                                        } else {
                                            Ellipse()
                                                .fill(Color.red)
                                                .frame(width: 12, height: 12)
                                                .overlay(
                                                    Text("-")
                                                        .font(FontStyle.VersionText.font)
                                                        .foregroundColor(.white)
                                                )
                                        }
                                    }
                                }
                            }

                            Text(tab.title)
                                .font(.caption)
                        }
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .contentShape(.rect)
                    })
                        
                }
            }
            .frame(height: 50)
        }
        .background(ColorSet.BottomNav.color)
        .alert("", isPresented: $selectedTabModel.isShowChangeEmrMode) {
            Button("Yes"){
                var chatMode = SharingData.message.mode
                chatMode.toggle()
                let signalRService = SignalR()
                signalRService.chatMode(mode: chatMode, completion: responseChatMode)
            }
            Button("No"){
                
            }
        } message: {
            Text("Do you change an warning mode?")
        }
        .alert("Location", isPresented: $selectedTabModel.isLocationAlert) {
            Button("Cancel") {}
            Button("Setting") {
                guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else {
                    return
                }
                UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
            }
        } message: {
            Text("To use ECA,set the permission to use location information to ALWAYS.")
        }
        .alert("Update", isPresented: $my.isUpDate) {
            Button("Go to app page"){
                openURL(URL(string: HttpRequestType.AppStore.rawValue)!)
            }
        } message: {
            Text("A new version of this app is available.")
        }
    }

    /**
     * Warninngモードレスポンス
     */
    func responseChatMode(error: Error?) {
        if let e = error {
            print(debug: "Error chat:\(e)")
        } else {
            SharingData.message.changeMode()
        }
    }
}

#Preview {
    MainTabView()
        .environmentObject(SelectedTabModel())
        .environmentObject(SceneDelegate())
}
