//
//  HomeView.swift
//  SodaLive
//
//  Created by klaus on 2023/08/09.
//

import SwiftUI

import Firebase
import Kingfisher

struct HomeView: View {
    
    @AppStorage("pushToken") private var pushToken: String = UserDefaults.string(forKey: .pushToken)
    
    @StateObject var viewModel = HomeViewModel()
    @StateObject var liveViewModel = LiveViewModel()
    @StateObject var appState = AppState.shared
    @StateObject var contentPlayManager = ContentPlayManager.shared
    
    private let liveView = LiveView()
    private let explorer = ExplorerView()
    private let messageView = MessageView()
    private let contentView = ContentMainView()
    
    var body: some View {
        GeometryReader { proxy in
            ZStack(alignment: .bottom) {
                VStack(spacing: 0) {
                    ZStack {
                        contentView
                            .frame(width: viewModel.currentTab == .content ? proxy.size.width : 0)
                            .opacity(viewModel.currentTab == .content ? 1.0 : 0.01)
                        
                        liveView
                            .frame(width: viewModel.currentTab == .live ? proxy.size.width : 0)
                            .opacity(viewModel.currentTab == .live ? 1.0 : 0.01)
                        
                        explorer
                            .frame(width: viewModel.currentTab == .explorer ? proxy.size.width : 0)
                            .opacity(viewModel.currentTab == .explorer ? 1.0 : 0.01)
                        
                        messageView
                            .frame(width: viewModel.currentTab == .message ? proxy.size.width : 0)
                            .opacity(viewModel.currentTab == .message ? 1.0 : 0.01)
                        
                        if viewModel.currentTab == .mypage {
                            MyPageView()
                        }
                    }
                    .padding(.bottom, appState.isShowPlayer ? 72 : 0)
                    
                    Spacer()
                    
                    if contentPlayManager.isShowingMiniPlayer {
                        HStack(spacing: 0) {
                            KFImage(URL(string: contentPlayManager.coverImage))
                                .resizable()
                                .frame(width: 36.7, height: 36.7)
                                .cornerRadius(5.3)
                            
                            VStack(alignment: .leading, spacing: 2.3) {
                                Text(contentPlayManager.title)
                                    .font(.custom(Font.medium.rawValue, size: 13))
                                    .foregroundColor(Color(hex: "eeeeee"))
                                    .lineLimit(2)
                                
                                Text(contentPlayManager.nickname)
                                    .font(.custom(Font.medium.rawValue, size: 11))
                                    .foregroundColor(Color(hex: "d2d2d2"))
                            }
                            .padding(.horizontal, 10.7)
                            
                            Spacer()
                            
                            Image(contentPlayManager.isPlaying ? "ic_noti_pause" : "btn_bar_play")
                                .resizable()
                                .frame(width: 25, height: 25)
                                .onTapGesture {
                                    if contentPlayManager.isPlaying {
                                        contentPlayManager.pauseAudio()
                                    } else {
                                        contentPlayManager
                                            .playAudio(contentId: contentPlayManager.contentId)
                                    }
                                }
                            
                            Image("ic_noti_stop")
                                .resizable()
                                .frame(width: 25, height: 25)
                                .padding(.leading, 16)
                                .onTapGesture { contentPlayManager.stopAudio() }
                        }
                        .padding(.vertical, 10.7)
                        .padding(.horizontal, 13.3)
                        .background(Color(hex: "222222"))
                        .contentShape(Rectangle())
                        .onTapGesture {
                            appState
                                .setAppStep(
                                    step: .contentDetail(contentId: contentPlayManager.contentId)
                                )
                        }
                    }
                    
                    BottomTabView(width: proxy.size.width, currentTab: $viewModel.currentTab)
                    
                    if proxy.safeAreaInsets.bottom > 0 {
                        Rectangle()
                            .foregroundColor(Color(hex: "111111"))
                            .frame(width: proxy.size.width, height: 15.3)
                    }
                }
                .onAppear {
                    pushTokenUpdate()
                    viewModel.fetchAndUpdateIdfa()
                    viewModel.getMemberInfo()
                    viewModel.getEventPopup()
                    viewModel.addAllPlaybackTracking()
                }
                
                if appState.isShowPlayer {
                    LiveRoomViewV2()
                }
                
                if appState.isShowNotificationSettingsDialog {
                    NotificationSettingsDialog()
                }
                
                if liveViewModel.isShowPaymentDialog {
                    LivePaymentDialog(
                        title: liveViewModel.paymentDialogTitle,
                        desc: liveViewModel.paymentDialogDesc,
                        desc2: liveViewModel.paymentDialogDesc2,
                        confirmButtonTitle: liveViewModel.paymentDialogConfirmTitle,
                        confirmButtonAction: liveViewModel.paymentDialogConfirmAction,
                        cancelButtonTitle: liveViewModel.paymentDialogCancelTitle,
                        cancelButtonAction: liveViewModel.hidePopup,
                        startDateTime: liveViewModel.liveStartDate,
                        nowDateTime: liveViewModel.nowDate
                    )
                }
                
                if liveViewModel.isShowPasswordDialog {
                    LiveRoomPasswordDialog(
                        isShowing: $liveViewModel.isShowPasswordDialog,
                        can: liveViewModel.secretOrPasswordDialogCan,
                        confirmAction: liveViewModel.passwordDialogConfirmAction
                    )
                }
                
                if let eventItem = appState.eventPopup {
                    VStack(spacing: 0) {
                        Spacer()
                        
                        EventPopupDialogView(eventPopup: eventItem)
                        
                        if proxy.safeAreaInsets.bottom > 0 {
                            Rectangle()
                                .foregroundColor(Color(hex: "222222"))
                                .frame(width: proxy.size.width, height: 15.3)
                        }
                    }
                    .background(Color(hex: "222222").opacity(0.7))
                    .onTapGesture {
                        AppState.shared.eventPopup = nil
                    }
                }
            }
            .edgesIgnoringSafeArea(.bottom)
            .valueChanged(value: appState.pushRoomId) { value in
                DispatchQueue.main.async {
                    appState.setAppStep(step: .main)
                    
                    if value > 0 {
                        liveViewModel.enterLiveRoom(roomId: value)
                    }
                }
            }
            .valueChanged(value: appState.pushChannelId) { value in
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    if value > 0 {
                        appState.setAppStep(step: .main)
                        appState.setAppStep(step: .creatorDetail(userId: value))
                    }
                }
            }
            .valueChanged(value: appState.pushMessageId) { value in
                DispatchQueue.main.async {
                    appState.setAppStep(step: .main)
                    
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        if value > 0 {
                            viewModel.currentTab = .message
                        }
                    }
                }
            }
            .valueChanged(value: appState.pushAudioContentId) { value in
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    if value > 0 {
                        appState.setAppStep(step: .main)
                        appState.setAppStep(step: .contentDetail(contentId: value))
                    }
                }
            }
            .onAppear {
                if appState.pushMessageId > 0 {
                    viewModel.currentTab = .message
                }
            }
        }
    }
    
    private func pushTokenUpdate() {
        if !pushToken.trimmingCharacters(in: .whitespaces).isEmpty {
            self.viewModel.pushTokenUpdate(pushToken: pushToken)
        }
    }
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}