//
//  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 = "라이브 공지를 입력하세요"
    
    let 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 = 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 {
            GeometryReader { proxy in
                ScrollView(.vertical, showsIndicators: false) {
                    VStack(alignment: .leading, spacing: 0) {
                        HStack(spacing: 0) {
                            Text("라이브 수정")
                                .font(.custom(Font.bold.rawValue, size: 18.3))
                                .foregroundColor(Color(hex: "eeeeee"))
                            
                            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_220")
                                        .resizable()
                                        .scaledToFit()
                                        .frame(width: 80, height: 116.8)
                                        .background(Color(hex: "3e3358"))
                                        .cornerRadius(10)
                                }
                                
                                Image("ic_camera")
                                    .padding(10)
                                    .background(Color(hex: "9970ff"))
                                    .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)
                        
                        HStack(spacing: 13.3) {
                            Text("취소")
                                .font(.custom(Font.bold.rawValue, size: 18.3))
                                .foregroundColor(Color(hex: "9970ff"))
                                .padding(.vertical, 16)
                                .frame(width: (screenSize().width - 40) / 2)
                                .background(Color(hex: "9970ff").opacity(0.2))
                                .cornerRadius(10)
                                .overlay(
                                    RoundedRectangle(cornerRadius: 10)
                                        .strokeBorder(lineWidth: 1)
                                        .foregroundColor(Color(hex: "9970ff"))
                                )
                                .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(hex: "9970ff"))
                                .cornerRadius(10)
                                .onTapGesture {
                                    confirmAction(
                                        title,
                                        notice.trimmingCharacters(in: .whitespacesAndNewlines) != placeholder ? notice : ""
                                    )
                                    isShowing = false
                                }
                        }
                        .padding(.top, 45)
                        
                        Spacer()
                    }
                    .padding(13.3)
                    .frame(width: proxy.size.width, height: proxy.size.height)
                    .onTapGesture { hideKeyboard() }
                }
                .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(hex: "eeeeee"))
                .accentColor(Color(hex: "9970ff"))
                .keyboardType(.default)
                .padding(.top, 12)
                .padding(.horizontal, 6.7)
            
            Rectangle()
                .frame(height: 1)
                .foregroundColor(Color(hex: "909090").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(hex: "eeeeee"))
                
                Spacer()
                
                Text("\(notice.count)자")
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color(hex: "ff5c49")) +
                Text(" / 1000자")
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color(hex: "777777"))
            }
            
            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)
        }
    }
}