//
//  LiveRoomInfoEditDialog.swift
//  SodaLive
//
//  Created by klaus on 2023/08/15.
//

import SwiftUI
import Kingfisher

struct LiveRoomInfoEditDialog: View {
    
    @Binding var isShowing: Bool
    @Binding var isShowPhotoPicker: Bool
    
    @State private var title = ""
    @State private var notice = ""
    
    let placeholder = "라이브 공지를 입력하세요"
    
    @StateObject var viewModel: LiveRoomViewModel
    
    let isLoading: Bool
    let coverImageUrl: String?
    let coverImage: UIImage?
    var confirmAction: (String, String) -> Void
    
    init(
        isShowing: Binding<Bool>,
        isShowPhotoPicker: Binding<Bool>,
        viewModel: LiveRoomViewModel,
        isLoading: Bool,
        currentTitle: String,
        currentNotice: String,
        coverImageUrl: String,
        coverImage: UIImage?,
        confirmAction: @escaping (String, String) -> Void
    ) {
        self._isShowing = isShowing
        self._isShowPhotoPicker = isShowPhotoPicker
        
        self._viewModel = StateObject(wrappedValue: viewModel)
        self.isLoading = isLoading
        
        self.title = currentTitle
        self.notice = currentNotice
        self.coverImageUrl = coverImageUrl
        self.coverImage = coverImage
        self.confirmAction = confirmAction
        
        UITextView.appearance().backgroundColor = .clear
    }
    
    var body: some View {
        ZStack {
            ScrollView(.vertical, showsIndicators: false) {
                VStack(alignment: .leading, spacing: 0) {
                    HStack(spacing: 0) {
                        Text("라이브 수정")
                            .font(.custom(Font.bold.rawValue, size: 18.3))
                            .foregroundColor(Color.grayee)
                        
                        Spacer()
                        
                        Image("ic_close_white")
                            .onTapGesture {
                                isShowing = false
                            }
                    }
                    
                    HStack {
                        Spacer()
                        
                        ZStack {
                            if let coverImage = coverImage {
                                Image(uiImage: coverImage)
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 80, height: 116.8, alignment: .top)
                                    .clipped()
                                    .cornerRadius(10)
                            } else if let coverImageUrl = coverImageUrl {
                                KFImage(URL(string: coverImageUrl))
                                    .resizable()
                                    .scaledToFill()
                                    .frame(width: 80, height: 116.8, alignment: .top)
                                    .clipped()
                                    .cornerRadius(10)
                            } else {
                                Image("ic_logo")
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: 80, height: 116.8)
                                    .background(Color.bg)
                                    .cornerRadius(10)
                            }
                            
                            Image("ic_camera")
                                .padding(10)
                                .background(Color.button)
                                .cornerRadius(30)
                                .offset(x: 40, y: 40)
                        }
                        .frame(alignment: .bottomTrailing)
                        .padding(.top, 13.3)
                        .onTapGesture {
                            isShowPhotoPicker = true
                        }
                        
                        Spacer()
                    }
                    
                    TitleInputView()
                        .padding(.top, 40)
                    
                    ContentInputView()
                        .padding(.top, 33.3)
                    
                    LiveRoomMenuSelectView(
                        menu: $viewModel.menu,
                        isActivate: $viewModel.isActivateMenu,
                        menuCount: viewModel.menuList.count,
                        selectedMenu: viewModel.selectedMenu,
                        selectMenu: { viewModel.selectMenuPreset(selectedMenuPreset: $0) }
                    )
                    .padding(.top, 33.3)
                    
                    HStack(spacing: 13.3) {
                        Text("취소")
                            .font(.custom(Font.bold.rawValue, size: 18.3))
                            .foregroundColor(Color.button)
                            .padding(.vertical, 16)
                            .frame(width: (screenSize().width - 40) / 2)
                            .background(Color.button.opacity(0.2))
                            .cornerRadius(10)
                            .overlay(
                                RoundedRectangle(cornerRadius: 10)
                                    .strokeBorder(lineWidth: 1)
                                    .foregroundColor(Color.button)
                            )
                            .onTapGesture {
                                isShowing = false
                            }
                        
                        Text("수정하기")
                            .font(.custom(Font.bold.rawValue, size: 18.3))
                            .foregroundColor(.white)
                            .padding(.vertical, 16)
                            .frame(width: (screenSize().width - 40) / 2)
                            .background(Color.button)
                            .cornerRadius(10)
                            .onTapGesture {
                                confirmAction(
                                    title,
                                    notice.trimmingCharacters(in: .whitespacesAndNewlines) != placeholder ? notice : ""
                                )
                                isShowing = false
                            }
                    }
                    .padding(.top, 45)
                    
                    Spacer()
                }
                .padding(13.3)
                .onTapGesture { hideKeyboard() }
                .onAppear {
                    viewModel.getAllMenuPreset {
                        self.isShowing = false
                    }
                }
            }
            .background(Color(hex: "222222").edgesIgnoringSafeArea(.all))
            
            if viewModel.isShowPopup {
                LiveRoomDialogView(
                    content: viewModel.errorMessage,
                    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
                        }
                    }
                }
            }
            
            if isLoading {
                LoadingView()
            }
        }
    }
    
    @ViewBuilder
    func TitleInputView() -> some View {
        VStack(alignment: .leading, spacing: 0) {
            Text("제목")
                .font(.custom(Font.bold.rawValue, size: 16.7))
                .foregroundColor(Color(hex: "eeeeee"))
            
            TextField("라이브 제목을 입력하세요", text: $title)
                .autocapitalization(.none)
                .disableAutocorrection(true)
                .font(.custom(Font.medium.rawValue, size: 13.3))
                .foregroundColor(Color.grayee)
                .accentColor(Color.button)
                .keyboardType(.default)
                .padding(.top, 12)
                .padding(.horizontal, 6.7)
            
            Rectangle()
                .frame(height: 1)
                .foregroundColor(Color.gray90.opacity(0.7))
                .padding(.top, 8.3)
        }
    }
    
    @ViewBuilder
    func ContentInputView() -> some View {
        VStack(spacing: 13.3) {
            HStack(spacing: 0) {
                Text("공지")
                    .font(.custom(Font.bold.rawValue, size: 16.7))
                    .foregroundColor(Color.grayee)
                
                Spacer()
                
                Text("\(notice.count)자")
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color.mainRed) +
                Text(" / 1000자")
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color.gray77)
            }
            
            TextViewWrapper(
                text: $notice,
                placeholder: placeholder,
                textColorHex: "eeeeee",
                backgroundColorHex: "303030"
            )
            .frame(width: screenSize().width - 26.7, height: 133.3)
            .cornerRadius(6.7)
            .padding(.top, 13.3)
        }
    }
}