//
//  UserProfileView.swift
//  SodaLive
//
//  Created by klaus on 2023/08/11.
//

import SwiftUI

struct UserProfileView: View {
    
    let userId: Int
    @StateObject var viewModel = UserProfileViewModel()
    
    @State private var memberId: Int = 0
    @State private var isShowMemberProfilePopup: Bool = false
    @State private var isShowFollowNotifyDialog: Bool = false
    @State private var isShowRouletteSettings: Bool = false
    @State private var isShowMenuSettings: Bool = false
    
    var body: some View {
        GeometryReader { proxy in
            BaseView(isLoading: $viewModel.isLoading) {
                VStack(spacing: 0) {
                    HStack(spacing: 0) {
                        Button {
                            AppState.shared.back()
                        } label: {
                            Image("ic_back")
                                .resizable()
                                .frame(width: 20, height: 20)
                            
                            Text(viewModel.navigationTitle)
                                .font(.custom(Font.bold.rawValue, size: 18.3))
                                .foregroundColor(Color(hex: "eeeeee"))
                        }
                        
                        Spacer()
                        
                        if userId != UserDefaults.int(forKey: .userId) {
                            Image("ic_seemore_vertical")
                                .onTapGesture {
                                    viewModel.isShowReportMenu = true
                                }
                        }
                    }
                    .padding(.horizontal, 13.3)
                    .frame(height: 50)
                    .background(Color.black)
                    
                    ScrollView(.vertical, showsIndicators: false) {
                        VStack(spacing: 0) {
                            if let creatorProfile = viewModel.creatorProfile {
                                VStack(spacing: 0) {
                                    UserProfileCreatorView(
                                        creator: creatorProfile.creator) {
                                            viewModel.creatorFollow()
                                        } showCreatorFollowNotifyDialog: {
                                            isShowFollowNotifyDialog = true
                                        } shareChannel: {
                                            viewModel.shareChannel(userId: userId)
                                        }
                                    
                                    UserProfileActivitySummaryView(item: creatorProfile.activitySummary)
                                        .padding(.top, 13.3)
                                        .padding(.horizontal, 13.3)
                                    
                                    if viewModel.communityPostList.count > 0 {
                                        ScrollView(.horizontal, showsIndicators: false) {
                                            LazyHStack(spacing: 13.3) {
                                                if UserDefaults.int(forKey: .userId) == creatorProfile.creator.creatorId {
                                                    CreatorCommunityWriteItemView()
                                                        .onTapGesture {
                                                            AppState.shared.setAppStep(
                                                                step: .creatorCommunityWrite(
                                                                    onSuccess: creatorCommunityWriteSuccess
                                                                )
                                                            )
                                                        }
                                                }
                                                
                                                ForEach(0..<viewModel.communityPostList.count, id: \.self) { index in
                                                    let item = viewModel.communityPostList[index]
                                                    CreatorCommunityItemView(item: item)
                                                        .frame(width: 320)
                                                        .onTapGesture {
                                                            AppState.shared
                                                                .setAppStep(
                                                                    step: .creatorCommunityAll(creatorId: userId)
                                                                )
                                                        }
                                                }
                                                
                                                CreatorCommunityMoreItemView {
                                                    AppState.shared
                                                        .setAppStep(
                                                            step: .creatorCommunityAll(creatorId: userId)
                                                        )
                                                }
                                            }
                                            .padding(.horizontal, 13.3)
                                        }
                                        .frame(minHeight: 146)
                                        .padding(.top, 26.7)
                                    } else {
                                        if UserDefaults.int(forKey: .userId) == creatorProfile.creator.creatorId {
                                            CreatorCommunityNoPostsItemView(
                                                onSuccess: creatorCommunityWriteSuccess
                                            )
                                            .padding(.top, 26.7)
                                            .padding(.horizontal, 13.3)
                                        }
                                    }
                                }
                                
                                if !creatorProfile.seriesList.isEmpty {
                                    UserProfileSeriesView(
                                        creatorId: creatorProfile.creator.creatorId,
                                        items: creatorProfile.seriesList
                                    )
                                        .padding(.top, 26.7)
                                        .padding(.horizontal, 13.3)
                                }
                                
                                if creatorProfile.contentList.count > 0 ||
                                    userId == UserDefaults.int(forKey: .userId)
                                {
                                    UserProfileContentView(
                                        userId: userId,
                                        items: creatorProfile.contentList
                                    )
                                    .padding(.top, 26.7)
                                    .padding(.horizontal, 13.3)
                                }
                                
                                if creatorProfile.creator.creatorId == UserDefaults.int(forKey: .userId) || creatorProfile.liveRoomList.count > 0 {
                                    VStack(alignment: .leading, spacing: 26.7) {
                                        Text("라이브")
                                            .font(.custom(Font.bold.rawValue, size: 16.7))
                                            .foregroundColor(Color.grayee)
                                        
                                        if creatorProfile.creator.creatorId == UserDefaults.int(forKey: .userId) {
                                            HStack(spacing: 8) {
                                                Text("룰렛 설정")
                                                    .font(.custom(Font.bold.rawValue, size: 15))
                                                    .foregroundColor(Color.grayee)
                                                    .padding(.vertical, 17)
                                                    .frame(maxWidth: .infinity)
                                                    .background(Color.button)
                                                    .cornerRadius(5.3)
                                                    .onTapGesture { isShowRouletteSettings = true }
                                                
                                                Text("메뉴 설정")
                                                    .font(.custom(Font.bold.rawValue, size: 15))
                                                    .foregroundColor(Color.grayee)
                                                    .padding(.vertical, 17)
                                                    .frame(maxWidth: .infinity)
                                                    .background(Color.button)
                                                    .cornerRadius(5.3)
                                                    .onTapGesture { isShowMenuSettings = true }
                                            }
                                        }
                                        
                                        if creatorProfile.liveRoomList.count > 0 {
                                            UserProfileLiveView(
                                                userId: userId,
                                                liveRoomList: creatorProfile.liveRoomList,
                                                onClickParticipant: { liveRoom in
                                                    if creatorProfile.creator.creatorId == UserDefaults.int(forKey: .userId) {
                                                        viewModel.errorMessage = "현재 라이브 중입니다."
                                                        viewModel.isShowPopup = true
                                                    } else {
                                                        AppState.shared.isShowPlayer = false
                                                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                                            viewModel.enterLiveRoom(roomId: liveRoom.roomId)
                                                        }
                                                    }
                                                },
                                                onClickReservation: { liveRoom in
                                                    if creatorProfile.creator.creatorId == UserDefaults.int(forKey: .userId) {
                                                        viewModel.errorMessage = "내가 만든 라이브는 예약할 수 없습니다."
                                                        viewModel.isShowPopup = true
                                                    } else {
                                                        viewModel.reservationLiveRoom(roomId: liveRoom.roomId)
                                                    }
                                                }
                                            )
                                        }
                                    }
                                    .padding(.top, 26.7)
                                    .padding(.horizontal, 13.3)
                                }
                                
                                VStack(spacing: 26.7) {
                                    let introduce = creatorProfile.creator.introduce
                                    UserProfileIntroduceView(
                                        introduce: introduce.trimmingCharacters(in: .whitespaces).count <= 0 ?
                                        "채널 소개내용이 없습니다." :
                                            introduce)
                                    
                                    Rectangle()
                                        .frame(height: 1)
                                        .foregroundColor(Color(hex: "909090").opacity(0.5))
                                        .padding(.horizontal, 13.3)
                                }
                                .padding(.top, 26.7)
                                
                                if creatorProfile.userDonationRanking.count > 0 {
                                    VStack(spacing: 26.7) {
                                        UserProfileDonationView(userId: userId, donationRankingResponse: creatorProfile.userDonationRanking)
                                            .padding(.horizontal, 13.3)
                                        
                                        Rectangle()
                                            .frame(height: 6.7)
                                            .foregroundColor(Color.gray90.opacity(0.5))
                                    }
                                    .padding(.top, 26.7)
                                }
                                
                                UserProfileFanTalkView(
                                    userId: userId,
                                    cheers: creatorProfile.cheers,
                                    errorPopup: { message in
                                        viewModel.errorMessage = message
                                        viewModel.isShowPopup = true
                                    },
                                    reportPopup: { cheerId in
                                        viewModel.cheersId = cheerId
                                        viewModel.isShowCheersReportView = true
                                    },
                                    deletePopup: { cheerId in
                                        viewModel.cheersId = cheerId
                                        viewModel.isShowCheersDeleteView = true
                                    },
                                    profilePopup: {
                                        self.memberId = $0
                                        self.isShowMemberProfilePopup = true
                                    },
                                    isLoading: $viewModel.isLoading
                                )
                                .padding(.top, 26.7)
                            }
                        }
                    }
                }
                .popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .bottom, autohideIn: 2) {
                    HStack {
                        Spacer()
                        Text(viewModel.errorMessage)
                            .padding(.vertical, 13.3)
                            .frame(width: screenSize().width - 66.7, alignment: .center)
                            .font(.custom(Font.medium.rawValue, size: 12))
                            .background(Color.button)
                            .foregroundColor(Color.white)
                            .multilineTextAlignment(.leading)
                            .cornerRadius(20)
                            .padding(.bottom, 66.7)
                        Spacer()
                    }
                }
                
                ZStack {
                    if viewModel.isShowPaymentDialog {
                        LivePaymentDialog(
                            title: viewModel.paymentDialogTitle,
                            desc: viewModel.paymentDialogDesc,
                            desc2: viewModel.paymentDialogDesc2,
                            confirmButtonTitle: viewModel.paymentDialogConfirmTitle,
                            confirmButtonAction: viewModel.paymentDialogConfirmAction,
                            cancelButtonTitle: viewModel.paymentDialogCancelTitle,
                            cancelButtonAction: viewModel.hidePaymentPopup,
                            startDateTime: viewModel.liveStartDate,
                            nowDateTime: viewModel.nowDate
                        )
                    }
                    
                    if viewModel.isShowPasswordDialog {
                        LiveRoomPasswordDialog(
                            isShowing: $viewModel.isShowPasswordDialog,
                            can: viewModel.secretOrPasswordDialogCan,
                            confirmAction: viewModel.passwordDialogConfirmAction
                        )
                    }
                    
                    if viewModel.isShowCheersDeleteView {
                        SodaDialog(
                            title: "응원글 삭제",
                            desc: "삭제하시겠습니까?",
                            confirmButtonTitle: "삭제",
                            confirmButtonAction: {
                                viewModel.deleteCheers(creatorId: userId)
                                viewModel.isShowCheersDeleteView = false
                            },
                            cancelButtonTitle: "취소",
                            cancelButtonAction: { viewModel.isShowCheersDeleteView = false }
                        )
                    }
                    
                    if viewModel.isShowCheersReportView {
                        CheersReportDialogView(
                            isShowing: $viewModel.isShowCheersReportView,
                            confirmAction: { reason in
                                viewModel.report(type: .CHEERS, reason: reason)
                            }
                        )
                    }
                    
                    if let creatorProfile = viewModel.creatorProfile, viewModel.isShowReportMenu {
                        VStack(spacing: 0) {
                            ProfileReportMenuView(
                                isShowing: $viewModel.isShowReportMenu,
                                isBlockedUser: creatorProfile.isBlock,
                                userBlockAction: { viewModel.isShowUesrBlockConfirm = true },
                                userUnBlockAction: { viewModel.userUnBlock(userId: userId) },
                                userReportAction: { viewModel.isShowUesrReportView = true },
                                profileReportAction: { viewModel.isShowProfileReportConfirm = true }
                            )
                            
                            if proxy.safeAreaInsets.bottom > 0 {
                                Rectangle()
                                    .foregroundColor(Color(hex: "222222"))
                                    .frame(width: proxy.size.width, height: 15.3)
                            }
                        }
                        .ignoresSafeArea()
                    }
                    
                    if let creatorProfile = viewModel.creatorProfile,
                       viewModel.isShowUesrBlockConfirm {
                        UserBlockConfirmDialogView(
                            isShowing: $viewModel.isShowUesrBlockConfirm,
                            nickname: creatorProfile.creator.nickname,
                            confirmAction: { viewModel.userBlock(userId: userId) }
                        )
                    }
                    
                    if viewModel.isShowUesrReportView {
                        UserReportDialogView(
                            isShowing: $viewModel.isShowUesrReportView,
                            confirmAction: { reason in
                                viewModel.report(type: .USER, userId: userId, reason: reason)
                            }
                        )
                    }
                    
                    if viewModel.isShowProfileReportConfirm {
                        ProfileReportDialogView(
                            isShowing: $viewModel.isShowProfileReportConfirm,
                            confirmAction: {
                                viewModel.report(type: .PROFILE, userId: userId)
                            }
                        )
                    }
                    
                    if isShowMemberProfilePopup {
                        MemberProfileDialog(isShowing: $isShowMemberProfilePopup, memberId: memberId)
                    }
                }
                
                if isShowFollowNotifyDialog {
                    CreatorFollowNotifyDialog(
                        isShowing: $isShowFollowNotifyDialog,
                        onClickNotifyAll: {
                            viewModel.creatorFollow(follow: true, notify: true)
                        },
                        onClickNotifyNone: {
                            viewModel.creatorFollow(follow: true, notify: false)
                        },
                        onClickUnFollow: {
                            viewModel.creatorFollow(follow: false, notify: false)
                        }
                    )
                }
                
                if isShowRouletteSettings {
                    RouletteSettingsView(isShowing: $isShowRouletteSettings, availableActive: false) { _, message in
                        viewModel.errorMessage = message
                        viewModel.isShowPopup = true
                    }
                }
                
                if isShowMenuSettings {
                    MenuSettingsView(isShowing: $isShowMenuSettings)
                }
            }
            .sheet(
                isPresented: $viewModel.isShowShareView,
                onDismiss: { viewModel.shareMessage = "" },
                content: {
                    ActivityViewController(activityItems: [viewModel.shareMessage])
                }
            )
            .onAppear {
                viewModel.getCreatorProfile(userId: userId)
                AppState.shared.pushChannelId = 0
            }
        }
    }
    
    private func creatorCommunityWriteSuccess() {
        viewModel.getCreatorProfile(userId: userId)
    }
}

struct UserProfileView_Previews: PreviewProvider {
    static var previews: some View {
        UserProfileView(userId: 0)
    }
}
