//
//  CreatorCommunityWriteView.swift
//  SodaLive
//
//  Created by klaus on 2023/12/15.
//

import SwiftUI

struct CreatorCommunityWriteView: View {
    
    @StateObject var keyboardHandler = KeyboardHandler()
    @StateObject private var viewModel = CreatorCommunityWriteViewModel()
    
    @State private var isShowRecordingVoiceView = false
    @State private var isShowPhotoPicker = false
    @State private var fileName: String = "녹음"
    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.grayee)
                                        .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 {
                                            Image("ic_logo2")
                                                .resizable()
                                                .scaledToFit()
                                                .padding(13.3)
                                                .frame(width: 107, height: 107)
                                                .background(Color.bg)
                                                .cornerRadius(8)
                                                .clipped()
                                        }
                                        
                                        Image("ic_camera")
                                            .padding(10)
                                            .background(Color.button)
                                            .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.gray77)
                                        
                                        Text("등록할 이미지가 없으면 이미지 없이 게시글만 등록 하셔도 됩니다.")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color.gray77)
                                    }
                                    .frame(maxWidth: .infinity)
                                    .padding(.top, 24)
                                    
                                    if let _ = viewModel.postImage {
                                        VStack(spacing: 13.3) {
                                            HStack(spacing: 0) {
                                                Text("오디오 녹음")
                                                    .font(.custom(Font.bold.rawValue, size: 16.7))
                                                    .foregroundColor(Color.grayee)
                                                
                                                Spacer()
                                            }
                                            
                                            Text(fileName)
                                                .font(.custom(Font.medium.rawValue, size: 16.7))
                                                .foregroundColor(Color.main)
                                                .padding(.vertical, 8)
                                                .background(Color.bg)
                                                .cornerRadius(5.3)
                                                .frame(maxWidth: .infinity)
                                                .contentShape(Rectangle())
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 5.3)
                                                        .stroke(Color.button, lineWidth: 1)
                                                )
                                                .onTapGesture { isShowRecordingVoiceView = true }
                                            
                                            
                                            Text("※ 오디오 녹음은 최대 3분입니다")
                                                .font(.custom(Font.medium.rawValue, size: 13.3))
                                                .foregroundColor(Color.gray77)
                                        }
                                        .padding(.top, 24)
                                    }
                                    
                                    HStack(spacing: 0) {
                                        Text("내용")
                                            .font(.custom(Font.bold.rawValue, size: 16.7))
                                            .foregroundColor(Color.grayee)
                                        
                                        Spacer()
                                        
                                        Text("\(viewModel.content.count)자")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color.mainRed) +
                                        Text(" / 최대 500자")
                                            .font(.custom(Font.medium.rawValue, size: 13.3))
                                            .foregroundColor(Color.gray77)
                                    }
                                    .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.grayee)
                                            .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)
                                    
                                    if UserDefaults.bool(forKey: .auth) {
                                        VStack(spacing: 13.3) {
                                            Text("연령 제한")
                                                .font(.custom(Font.bold.rawValue, size: 16.7))
                                                .foregroundColor(Color.grayee)
                                                .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)
                                    }
                                    
                                    if let _ = viewModel.postImage {
                                        VStack(spacing: 13.3) {
                                            Text("가격 설정")
                                                .font(.custom(Font.bold.rawValue, size: 16.7))
                                                .foregroundColor(Color.grayee)
                                                .frame(maxWidth: .infinity, alignment: .leading)
                                            
                                            HStack(spacing: 13.3) {
                                                SelectButtonView(
                                                    title: "무료",
                                                    isChecked: viewModel.isPriceFree
                                                ) {
                                                    if !viewModel.isPriceFree {
                                                        viewModel.isPriceFree = true
                                                    }
                                                }
                                                
                                                SelectButtonView(
                                                    title: "유료",
                                                    isChecked: !viewModel.isPriceFree
                                                ) {
                                                    if viewModel.isPriceFree {
                                                        viewModel.isPriceFree = false
                                                    }
                                                }
                                            }
                                            
                                            if !viewModel.isPriceFree {
                                                HStack(spacing: 0) {
                                                    TextField("", text: $viewModel.priceString)
                                                        .autocapitalization(.none)
                                                        .disableAutocorrection(true)
                                                        .multilineTextAlignment(.center)
                                                        .font(.custom(Font.bold.rawValue, size: 13.3))
                                                        .foregroundColor(Color.button)
                                                        .accentColor(Color.button)
                                                        .keyboardType(.numberPad)
                                                    
                                                    Spacer()
                                                    
                                                    Text("캔")
                                                        .font(.custom(Font.medium.rawValue, size: 14.7))
                                                        .foregroundColor(Color.button)
                                                }
                                                .padding(.horizontal, 13.3)
                                                .padding(.vertical, 16.7)
                                                .frame(maxWidth: .infinity)
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 6.7)
                                                        .stroke(Color.gray77, lineWidth: 1)
                                                )
                                                .background(Color.gray23)
                                            }
                                        }
                                        .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.button)
                                            .frame(maxWidth: .infinity)
                                            .frame(height: 50)
                                            .background(Color.bg)
                                            .cornerRadius(10)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 8)
                                                    .stroke(Color.button, 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.button)
                                            .cornerRadius(10)
                                            .onTapGesture {
                                                hideKeyboard()
                                                viewModel.createCommunityPost {
                                                    deleteAudioFile()
                                                    AppState.shared.back()
                                                    
                                                    DispatchQueue.main.async {
                                                        onSuccess()
                                                    }
                                                }
                                            }
                                    }
                                    .padding(13.3)
                                    .frame(maxWidth: .infinity)
                                    .background(Color.gray22)
                                    .cornerRadius(16.7, corners: [.topLeft, .topRight])
                                    
                                    Rectangle()
                                        .foregroundColor(Color.gray22)
                                        .frame(height: keyboardHandler.keyboardHeight)
                                        .frame(maxWidth: .infinity)
                                    
                                    if proxy.safeAreaInsets.bottom > 0 {
                                        Rectangle()
                                            .foregroundColor(Color.gray22)
                                            .frame(height: 15.3)
                                            .frame(maxWidth: .infinity)
                                    }
                                }
                                .padding(.top, 100)
                            }
                        }
                    }
                    
                    if isShowPhotoPicker {
                        ImagePicker(
                            isShowing: $isShowPhotoPicker,
                            selectedImage: $viewModel.postImage,
                            sourceType: .photoLibrary
                        )
                    }
                    
                    if isShowRecordingVoiceView {
                        CreatorCommunityRecordingVoiceView(
                            isShowing: $isShowRecordingVoiceView,
                            isShowPopup: $viewModel.isShowPopup,
                            errorMessage: $viewModel.errorMessage,
                            fileName: $fileName,
                            soundData: $viewModel.soundData
                        )
                    }
                }
                .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.button)
                                .foregroundColor(Color.white)
                                .multilineTextAlignment(.center)
                                .cornerRadius(20)
                                .padding(.top, 66.7)
                            Spacer()
                        }
                    }
                }
            }
        }
    }
    
    private func deleteAudioFile() {
        do {
            try FileManager.default.removeItem(at: getAudioFileURL())
        } catch {}
    }
    
    private func getAudioFileURL() -> URL {
        return getDocumentsDirectory().appendingPathComponent(fileName)
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
}

struct CreatorCommunityWriteView_Previews: PreviewProvider {
    static var previews: some View {
        CreatorCommunityWriteView {}
    }
}
