//
//  CreatorCommunityModifyView.swift
//  SodaLive
//
//  Created by klaus on 2023/12/21.
//

import SwiftUI
import Kingfisher

struct CreatorCommunityModifyView: View {
    
    let postId: Int
    @StateObject var keyboardHandler = KeyboardHandler()
    @StateObject private var viewModel = CreatorCommunityModifyViewModel()
    
    @State private var isShowPhotoPicker = false
    let onSuccess: () -> Void
    
    var body: some View {
        BaseView(isLoading: $viewModel.isLoading) {
            GeometryReader { proxy in
                ZStack {
                    VStack(spacing: 0) {
                        DetailNavigationBar(title: "게시글 수정")
                        
                        ScrollView(.vertical, showsIndicators: false) {
                            VStack(spacing: 0) {
                                VStack(spacing: 0) {
                                    Text("이미지")
                                        .font(.custom(Font.bold.rawValue, size: 16.7))
                                        .foregroundColor(Color(hex: "eeeeee"))
                                        .frame(maxWidth: .infinity, alignment: .leading)
                                    
                                    ZStack {
                                        if let selectedImage = viewModel.postImage {
                                            Image(uiImage: selectedImage)
                                                .resizable()
                                                .scaledToFill()
                                                .frame(width: 107, height: 107)
                                                .background(Color(hex: "3e3358"))
                                                .cornerRadius(8)
                                                .clipped()
                                        } else if let postImageUrl = viewModel.postImageUrl {
                                            KFImage(URL(string: postImageUrl))
                                                .cancelOnDisappear(true)
                                                .downsampling(
                                                    size: CGSize(
                                                        width: 107,
                                                        height: 107
                                                    )
                                                )
                                                .resizable()
                                                .scaledToFill()
                                                .frame(width: 107, height: 107)
                                                .background(Color(hex: "3e3358"))
                                                .cornerRadius(8)
                                                .clipped()
                                        } else {
                                            Image("ic_logo2")
                                                .resizable()
                                                .scaledToFit()
                                                .padding(13.3)
                                                .frame(width: 107, height: 107)
                                                .background(Color(hex: "13181B"))
                                                .cornerRadius(8)
                                                .clipped()
                                        }
                                        
                                        Image("ic_camera")
                                            .padding(10)
                                            .background(Color(hex: "3BB9F1"))
                                            .cornerRadius(30)
                                            .offset(x: 50, y: 36)
                                    }
                                    .frame(alignment: .bottomTrailing)
                                    .contentShape(Rectangle())
                                    .onTapGesture { isShowPhotoPicker = true }
                                    
                                    HStack(alignment: .top, spacing: 0) {
                                        Text("※ ")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color(hex: "777777"))
                                        
                                        Text("등록할 이미지가 없으면 이미지 없이 게시글만 등록 하셔도 됩니다.")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color(hex: "777777"))
                                    }
                                    .frame(maxWidth: .infinity, alignment: .leading)
                                    .padding(.top, 24)
                                    
                                    HStack(spacing: 0) {
                                        Text("내용")
                                            .font(.custom(Font.bold.rawValue, size: 16.7))
                                            .foregroundColor(Color(hex: "eeeeee"))
                                        
                                        Spacer()
                                        
                                        Text("\(viewModel.content.count)자")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color(hex: "ff5c49")) +
                                        Text(" / 최대 500자")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color(hex: "777777"))
                                    }
                                    .padding(.top, 26.7)
                                    
                                    TextViewWrapper(
                                        text: $viewModel.content,
                                        placeholder: viewModel.placeholder,
                                        textColorHex: "eeeeee",
                                        backgroundColorHex: "222222"
                                    )
                                    .frame(height: 184)
                                    .cornerRadius(6.7)
                                    .padding(.top, 13.3)
                                    
                                    VStack(spacing: 13.3) {
                                        Text("댓글 가능 여부")
                                            .font(.custom(Font.bold.rawValue, size: 16.7))
                                            .foregroundColor(Color(hex: "eeeeee"))
                                            .frame(maxWidth: .infinity, alignment: .leading)
                                        
                                        HStack(spacing: 13.3) {
                                            SelectButtonView(
                                                title: "댓글 가능",
                                                isChecked: viewModel.isAvailableComment
                                            ) {
                                                if !viewModel.isAvailableComment {
                                                    viewModel.isAvailableComment = true
                                                }
                                            }
                                            
                                            SelectButtonView(
                                                title: "댓글 불가",
                                                isChecked: !viewModel.isAvailableComment
                                            ) {
                                                if viewModel.isAvailableComment {
                                                    viewModel.isAvailableComment = false
                                                }
                                            }
                                        }
                                    }
                                    .padding(.top, 26.7)
                                    
                                    VStack(spacing: 13.3) {
                                        Text("연령 제한")
                                            .font(.custom(Font.bold.rawValue, size: 16.7))
                                            .foregroundColor(Color(hex: "eeeeee"))
                                            .frame(maxWidth: .infinity, alignment: .leading)
                                        
                                        HStack(spacing: 13.3) {
                                            SelectButtonView(
                                                title: "전체 연령",
                                                isChecked: !viewModel.isAdult
                                            ) {
                                                if viewModel.isAdult {
                                                    viewModel.isAdult = false
                                                }
                                            }
                                            
                                            SelectButtonView(
                                                title: "19세 이상",
                                                isChecked: viewModel.isAdult
                                            ) {
                                                if !viewModel.isAdult {
                                                    viewModel.isAdult = true
                                                }
                                            }
                                        }
                                    }
                                    .padding(.top, 26.7)
                                }
                                .padding(13.3)
                                
                                VStack(spacing: 0) {
                                    HStack(spacing: 13.3) {
                                        Text("닫기")
                                            .font(.custom(Font.bold.rawValue, size: 18.3))
                                            .foregroundColor(Color(hex: "3BB9F1"))
                                            .frame(maxWidth: .infinity)
                                            .frame(height: 50)
                                            .background(Color(hex: "13181B"))
                                            .cornerRadius(10)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 8)
                                                    .stroke(Color(hex: "3BB9F1"), lineWidth: 1)
                                            )
                                            .onTapGesture {
                                                hideKeyboard()
                                                AppState.shared.back()
                                            }
                                        
                                        Text("수정")
                                            .font(.custom(Font.bold.rawValue, size: 18.3))
                                            .foregroundColor(Color.white)
                                            .frame(maxWidth: .infinity)
                                            .frame(height: 50)
                                            .background(Color(hex: "3BB9F1"))
                                            .cornerRadius(10)
                                            .onTapGesture {
                                                hideKeyboard()
                                                viewModel.modifyCommunityPost {
                                                    AppState.shared.back()
                                                    
                                                    DispatchQueue.main.async {
                                                        onSuccess()
                                                    }
                                                }
                                            }
                                    }
                                    .padding(13.3)
                                    .frame(maxWidth: .infinity)
                                    .background(Color(hex: "222222"))
                                    .cornerRadius(16.7, corners: [.topLeft, .topRight])
                                    
                                    Rectangle()
                                        .foregroundColor(Color(hex: "222222"))
                                        .frame(height: keyboardHandler.keyboardHeight)
                                        .frame(maxWidth: .infinity)
                                    
                                    if proxy.safeAreaInsets.bottom > 0 {
                                        Rectangle()
                                            .foregroundColor(Color(hex: "222222"))
                                            .frame(height: 15.3)
                                            .frame(maxWidth: .infinity)
                                    }
                                }
                                .padding(.top, 100)
                            }
                        }
                    }
                    
                    if isShowPhotoPicker {
                        ImagePicker(
                            isShowing: $isShowPhotoPicker,
                            selectedImage: $viewModel.postImage,
                            sourceType: .photoLibrary
                        )
                    }
                }
                .onTapGesture { hideKeyboard() }
                .edgesIgnoringSafeArea(.bottom)
                .popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
                    GeometryReader { geo in
                        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(hex: "9970ff"))
                                .foregroundColor(Color.white)
                                .multilineTextAlignment(.center)
                                .cornerRadius(20)
                                .padding(.top, 66.7)
                            Spacer()
                        }
                    }
                }
                .onAppear {
                    viewModel.postId = postId
                    viewModel.getCommunityPostDetail {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            AppState.shared.back()
                        }
                    }
                }
            }
        }
    }
}

struct CreatorCommunityModifyView_Previews: PreviewProvider {
    static var previews: some View {
        CreatorCommunityModifyView(postId: 0) {}
    }
}
