//
//  LiveRoomProfilesDialogView.swift
//  SodaLive
//
//  Created by klaus on 2023/08/14.
//

import SwiftUI
import Kingfisher

struct LiveRoomProfilesDialogView: View {
    
    @Binding var isShowing: Bool
    
    let viewModel: LiveRoomViewModel
    let roomInfo: GetRoomInfoResponse
    
    var profiles: [AnyView] = []
    let accountId = UserDefaults.int(forKey: .userId)
    
    init(
        isShowing: Binding<Bool>,
        viewModel: LiveRoomViewModel,
        roomInfo: GetRoomInfoResponse,
        isShowRequestSpeaker: Bool,
        onClickRequestSpeaker: @escaping () -> Void,
        registerNotification: @escaping () -> Void,
        unRegisterNotification: @escaping () -> Void,
        onClickProfile: @escaping (Int) -> Void
    ) {
        self._isShowing = isShowing
        self.viewModel = viewModel
        self.roomInfo = roomInfo
        
        self.profiles.append(
            AnyView(
                LiveRoomProfileItemTitleView(
                    title: "스탭",
                    count: roomInfo.managerList.count,
                    totalCount: nil
                )
                .padding(.vertical, 14)
            )
        )
        
        let isStaff = viewModel.isEqualToStaffId(creatorId: UserDefaults.int(forKey: .userId)) ||
        roomInfo.creatorId == UserDefaults.int(forKey: .userId)
        
        for manager in roomInfo.managerList {
            self.profiles.append(
                AnyView(
                    LiveRoomProfileItemUserView(
                        isStaff: isStaff ,
                        userId: manager.id,
                        nickname: manager.nickname,
                        profileUrl: manager.profileImage,
                        role: manager.role,
                        onClickChangeListener: { _ in },
                        onClickInviteSpeaker: { _ in },
                        onClickKickOut: { _ in },
                        onClickProfile: onClickProfile
                    )
                )
            )
        }
        
        self.profiles.append(
            AnyView(
                LiveRoomProfileItemTitleView(
                    title: "스피커",
                    count: roomInfo.speakerList.count - 1,
                    totalCount: roomInfo.totalAvailableParticipantsCount
                )
                .padding(.vertical, 14)
            )
        )
        
        for speaker in roomInfo.speakerList {
            if speaker.id == roomInfo.creatorId {
                self.profiles.insert(
                    AnyView(
                        LiveRoomProfileItemMasterView(
                            id: speaker.id,
                            nickname: speaker.nickname,
                            profileUrl: speaker.profileImage,
                            onClickProfile: onClickProfile
                        )
                    ),
                    at: 0
                )
            } else {
                self.profiles.append(
                    AnyView(
                        LiveRoomProfileItemUserView(
                            isStaff: isStaff,
                            userId: speaker.id,
                            nickname: speaker.nickname,
                            profileUrl: speaker.profileImage,
                            role: speaker.role,
                            onClickChangeListener: {
                                if $0 == UserDefaults.int(forKey: .userId) {
                                    viewModel.setListener()
                                    return
                                }
                                
                                viewModel.changeListener(peerId: $0)
                            },
                            onClickInviteSpeaker: { _ in },
                            onClickKickOut: {
                                viewModel.kickOutId = $0
                                viewModel.isShowKickOutPopup = true
                            },
                            onClickProfile: onClickProfile
                        )
                    )
                )
            }
        }
        
        if isShowRequestSpeaker {
            self.profiles.append(
                AnyView(
                    LiveRoomProfileRequestSpeakerView {
                        onClickRequestSpeaker()
                    }
                )
            )
        }
        
        self.profiles.append(
            AnyView(
                LiveRoomProfileItemTitleView(
                    title: "리스너",
                    count: nil,
                    totalCount: nil
                )
                .padding(.top, 20)
                .padding(.bottom, 14)
            )
        )
        
        for listener in roomInfo.listenerList {
            self.profiles.append(
                AnyView(
                    LiveRoomProfileItemUserView(
                        isStaff: isStaff,
                        userId: listener.id,
                        nickname: listener.nickname,
                        profileUrl: listener.profileImage,
                        role: listener.role,
                        onClickChangeListener: { _ in },
                        onClickInviteSpeaker: {
                            if viewModel.liveRoomInfo!.speakerList.count <= 4 {
                                viewModel.inviteSpeaker(peerId: $0)
                                viewModel.popupContent = "스피커 요청을 보냈습니다.\n잠시만 기다려 주세요."
                                viewModel.isShowPopup = true
                            } else {
                                viewModel.errorMessage = "스피커 정원을 초과했습니다."
                                viewModel.isShowErrorPopup = true
                            }
                        },
                        onClickKickOut: {
                            viewModel.kickOutId = $0
                            viewModel.isShowKickOutPopup = true
                        },
                        onClickProfile: onClickProfile
                    )
                )
            )
        }
    }
    
    var body: some View {
        ZStack {
            VStack(spacing: 16.7) {
                HStack(spacing: 0) {
                    Text("참여자")
                        .font(.custom(Font.bold.rawValue, size: 15))
                        .foregroundColor(Color(hex: "eeeeee"))
                    
                    Text("\(roomInfo.participantsCount)")
                        .font(.custom(Font.medium.rawValue, size: 14))
                        .foregroundColor(Color(hex: "9970ff"))
                        .padding(.leading, 6.7)
                    
                    Text("/\(roomInfo.totalAvailableParticipantsCount)")
                        .font(.custom(Font.medium.rawValue, size: 14))
                        .foregroundColor(Color(hex: "bbbbbb"))
                    
                    Spacer()
                    
                    Image("ic_close_white")
                        .resizable()
                        .frame(width: 20, height: 20)
                        .onTapGesture { isShowing = false }
                }
                
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading, spacing: 20) {
                        ForEach(0..<profiles.count, id: \.self) { index in
                            profiles[index]
                        }
                    }
                }
            }
            .padding(.vertical, 26.7)
            .padding(.horizontal, 13.3)
            .background(Color(hex: "222222").edgesIgnoringSafeArea(.all))
            .cornerRadius(16.7)
            
            if viewModel.isShowPopup {
                LiveRoomDialogView(
                    content: viewModel.popupContent,
                    cancelTitle: viewModel.popupCancelTitle,
                    cancelAction: viewModel.popupCancelAction,
                    confirmTitle: viewModel.popupConfirmTitle,
                    confirmAction: viewModel.popupConfirmAction
                ).onAppear {
                    if viewModel.popupConfirmTitle == nil && viewModel.popupConfirmAction == nil {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                            viewModel.isShowPopup = false
                            viewModel.popupCancelTitle = nil
                            viewModel.popupCancelAction = nil
                            viewModel.popupConfirmTitle = nil
                            viewModel.popupConfirmAction = nil
                        }
                    }
                }
            }
            
            if viewModel.isShowKickOutPopup {
                SodaDialog(
                    title: "내보내기",
                    desc: viewModel.kickOutDesc,
                    confirmButtonTitle: "내보내기",
                    confirmButtonAction: {
                        viewModel.kickOut()
                    },
                    cancelButtonTitle: "취소",
                    cancelButtonAction: {
                        viewModel.isShowKickOutPopup = false
                        viewModel.kickOutDesc = ""
                        viewModel.kickOutId = 0
                    }
                )
            }
        }
    }
}