//
//  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{
        switch self {
        case .map: return "Map"
        case .chat: return "Chat"
        case .alert: return "Alert"
        case .menu: return "Menu"
        }
    }
}

struct MainTabView: View {
    @EnvironmentObject var selectedTabModel: SelectedTabModel
    @EnvironmentObject private var sceneDelegate: SceneDelegate
    @ObservedObject var location = SharingData.location
    @State private var offset = CGSize.zero
    @State var isSignout = false

    var isTabWindowActive: Bool {
        sceneDelegate.tabWindow != nil
    }

    var isTaskSel: Bool {
        selectedTabModel.activeTab == .map
    }

    var body: some View {
        Group {
            if UIDevice.current.userInterfaceIdiom == .phone {
                phoneView
            } else {
                padView
            }
        }
        .onAppear {
            SharingData.location.focusOwnShip = true
            configureTabBarAppearance()
        }
    }

    private var phoneView: some View {
        GeometryReader { geometry in
            ZStack(alignment: .bottom) {
                TabView(selection: $selectedTabModel.activeTab) {
                    mapTab
                    if SharingData.my.isCommunication {
                        ChatView(contentWidth: UIScreen.main.bounds.width).tag(Tab.chat)
                    }
                    NotificationView().tag(Tab.alert)
                    MenuView(isSignout: $isSignout).tag(Tab.menu)
                }
                .sheet(isPresented: .constant(isTaskSel && isTabWindowActive)) {
                    MenuTaskView()
                        .zIndex(0)
                        .presentationDragIndicator(.hidden)
                        .presentationDetents([
                            .height(LayoutConstants.menuMinimumHeight + geometry.safeAreaInsets.bottom),
                            .medium,
                            .fraction(0.99)
                        ])
                        .presentationCornerRadius(15)
                        .presentationBackgroundInteraction(.enabled(upThrough: .medium))
                        .presentationBackground(ColorSet.BackgroundSecondary.color)
                        .interactiveDismissDisabled()
                }
            }
        }
    }

    enum OverlayHeightMode: CaseIterable {
        case titleOnly
//        case half
        case full

        var heightRatio: CGFloat {
            switch self {
            case .titleOnly: return 0.15
//            case .half: return 0.5
            case .full: return 1.0
            }
        }
    }

    @State private var overlayHeightMode: OverlayHeightMode = .full
    private var padView: some View {
        GeometryReader { geometry in
            let overlayWidth = LayoutConstants.menuViewWidth
            let fullHeight = geometry.size.height - (LayoutConstants.menuTitleHeight + geometry.safeAreaInsets.top + 15)
            let overlayHeight = fullHeight * overlayHeightMode.heightRatio

            ZStack(alignment: .bottomLeading) {
                MapRepresentable()
                    .ignoresSafeArea()

                if selectedTabModel.activeTab == .menu {
                    MenuView(isSignout: $isSignout)
                        .frame(width: geometry.size.width, height: geometry.size.height)
                        .background(ColorSet.BackgroundPrimary.color)
                        .ignoresSafeArea()
                } else {
                    VStack(spacing: 0) {
                        Rectangle()
                            .fill(Color.gray.opacity(0.3))
                            .frame(height: 20)
                            .overlay(
                                Image(systemName: "line.horizontal.3")
                                    .foregroundColor(.gray)
                            )
                            .gesture(
                                DragGesture()
                                    .onEnded { _ in
                                        withAnimation {
                                            let allModes = OverlayHeightMode.allCases
                                            if let currentIndex = allModes.firstIndex(of: overlayHeightMode) {
                                                let nextIndex = (currentIndex + 1) % allModes.count
                                                overlayHeightMode = allModes[nextIndex]
                                            }
                                        }
                                    }
                            )

                        TabView(selection: $selectedTabModel.activeTab) {
                            MenuTaskView()
                                .tag(Tab.map)
                            if SharingData.my.isCommunication {
                                ChatView(contentWidth: overlayWidth)
                                    .tag(Tab.chat)
                            }
                            NotificationView()
                                .tag(Tab.alert)
                        }
                        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                    }
                    .frame(width: overlayWidth, height: overlayHeight)
                    .background(ColorSet.BackgroundPrimary.color)
                    .cornerRadius(12)
                    .shadow(radius: 4)
                    .padding(.bottom, LayoutConstants.menuTitleHeight + 5)
                    .padding(.leading, 5)
                }
            }
        }
    }

    @ViewBuilder
    private var mapTab: some View {
        ZStack {
            MapRepresentable()
            MapInformation().zIndex(1)
        }
        .ignoresSafeArea(edges: .top)
        .tag(Tab.map)
    }

    private func configureTabBarAppearance() {
        let appearance = UITabBarAppearance()
        appearance.backgroundColor = .clear
        UITabBar.appearance().scrollEdgeAppearance = appearance
        UITabBar.appearance().standardAppearance = appearance
    }
}

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