//
//  ChatInputView.swift
//  Sailassist
//
//  Created by Mamoru Sugita on 2023/11/08.
//

import SwiftUI

struct ChatInputView: View {
    @EnvironmentObject private var sceneDelegate: SceneDelegate
    @ObservedObject var sessionUploadImage: SessionUploadImage = SessionUploadImage()
    @ObservedObject var msg = SharingData.message
    @State var inputText = ""
    @State private var isChatAlert: Bool = false
    @State private var isPhotAlert: Bool = false
    @State private var selectionValue = 3
    @State var isCamera: Bool = false
    @State var isPhoto: Bool = false
    @State var isImportFile: Bool = false
    @State var imageData : Data = .init(capacity:0)
    @State var source:UIImagePickerController.SourceType = .photoLibrary
    @State var isActionSheet = false
    @State var isImagePicker = false
    @FocusState var isKeyboard: Bool
    @Binding var isFocus: Bool

    var body: some View {
        VStack(spacing: 0){
            Spacer()
            Divider()

            HStack(spacing: 10){
                Button {
                    sceneDelegate.tabWindow?.isHidden = true
                    isCamera = true
                    source = .camera
                    isImagePicker.toggle()
                } label: {
                    Image(systemName: "camera")
                        .resizable()
                        .frame(width: 24, height: 24)
                        .padding(10)
                }

                Menu {
                    Button(action: {
                        print("Photo Library")
                        sceneDelegate.tabWindow?.isHidden = true
                        isCamera = true
                        source = .photoLibrary
                        isImagePicker.toggle()
                    }) {
                        Label("Photo Library", systemImage: "photo.on.rectangle")
                    }
                    Button(action: {
                        print("Take Photo")
                        sceneDelegate.tabWindow?.isHidden = true
                        isImportFile = true
                    }) {
                        Label("Take Photo", systemImage: "camera")
                    }
                    Button(action: {
                        print("Choose File")
                        sceneDelegate.tabWindow?.isHidden = true
                        isCamera = true
                        source = .photoLibrary
                        isImagePicker.toggle()
                    }) {
                        Label("Choose File", systemImage: "folder")
                    }
                } label: {
                    Image(systemName: "photo")
                        .resizable()
                        .frame(width: 24, height: 24)
                        .padding(10)
                }

                TextField("", text: $inputText, onEditingChanged: { isEdit in
                    sceneDelegate.tabWindow?.isHidden = isEdit
                    isFocus = true
                })
                .focused($isKeyboard)
                .font(FontStyle.SupplementText.font)
                .foregroundColor(ColorSet.BodyChat.color)
                .padding(10)
                .background(ColorSet.ChatForm.color)
                .cornerRadius(5)
                .padding(.vertical, 10)
                .padding(.leading, 20)

                Button{
                    sendChatMessage(message: inputText)
                } label: {
                    Image("send")
                        .resizable()
                        .frame(width: 24, height: 24)
                        .padding(10)
                }
                .padding(.vertical, 6)
                .padding(.trailing, 11)
            }
            .background(ColorSet.BackgroundSecondary.color)
            .fullScreenCover(isPresented: .constant(isImagePicker), onDismiss: {
                //シートを閉じる時に実行する処理
                sceneDelegate.tabWindow?.isHidden = false
                isKeyboard = false

                if imageData.count != 0 {
                    let jpegData = UIImage(data: imageData)!.jpegData(compressionQuality: 1.0)
                    let uploadImage = ReqUploadImage(shipId: Preferences.shipId, messageId: UUID().uuidString, location: 2, from: Preferences.UserName, fromId: String(SharingData.my.id), files: jpegData!)
                    sessionUploadImage.RequestUploadImage(uploadImage, completion: responseUploadImage)
                }
            }, content: {
                CameraView(imageData: $imageData, source: $source, isActionSheet: $isActionSheet, isImagePicker: $isImagePicker)
            })
            .fileImporter(isPresented: $isImportFile, allowedContentTypes: [.png, .jpeg, .pdf]) { result in
                switch result {
                case .success(let url):
                    guard let imageData = try? Data(contentsOf: url) else { return }

                    if imageData.count != 0 {
                        let jpegData = UIImage(data: imageData)!.jpegData(compressionQuality: 1.0)
                        let uploadImage = ReqUploadImage(shipId: Preferences.shipId, messageId: UUID().uuidString, location: 2, from: Preferences.UserName, fromId: String(SharingData.my.id), files: jpegData!)
                        sessionUploadImage.RequestUploadImage(uploadImage, completion: responseUploadImage)
                    }
                case .failure:
                    print("failure")
                }
            }
            .onChange(of: isFocus) { focus in
                if focus == false {
                    isKeyboard = false
                }
            }
        }
        .frame(maxHeight: 55)
        .alert("Error", isPresented: $isChatAlert) {
            Button("OK") {}
        } message: {
            Text("The message could not be sent.")
        }
        .alert("Error", isPresented: $isPhotAlert) {
            Button("OK") {}
        } message: {
            Text("The Image could not be sent.")
        }
    }

    /**
     * イメージレスポンス
     */
    func responseUploadImage(result: Result<Data, APIError>) {
        print(debug: "calld")
        switch result {
        case .success(let resultData):
            let serverSession = ServerSession()
            let _ = serverSession.fromJSON(resultData: resultData, resltType: ResLogin.self)

        case .failure(let errorCode):
            print(debug: errorCode)
            isPhotAlert = true
            break
        }
    }

    /**
     * チャット送信
     */
    func sendChatMessage(message: String) {
        let signalRService = SignalR()
        signalRService.chatMessage(message: inputText, completion: responseChatMessage)
    }

    /**
     * チャットレスポンス
     */
    func responseChatMessage(error: Error?) {
        if let e = error {
            print(debug: "Error chat:\(e)")
            msg.messages.removeLast()        //最後に追加したメッセージを削除
            isChatAlert = true
        } else {
            isKeyboard = false
            inputText = ""
        }
    }
}

#Preview {
    ChatInputView(isFocus: .constant(false))
        .environmentObject(SceneDelegate())
}
