//
//  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()
    @State var inputText = ""
    @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

    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 Phot", 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
                })
                .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{
                    isKeyboard = false
                    let signalRService = SignalR()
                    signalRService.chatMessage(message: inputText)
                    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

                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")
                }
            }
        }
        .frame(maxHeight: 55)
    }

    func responseUploadImage(result: Result<Data, APIError>) {
        print(debug: "calld")
        switch result {
        case .success(let resultData):
            let serverSession = ServerSession()
            let resjson = serverSession.fromJSON(resultData: resultData, resltType: ResLogin.self)

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

#Preview {
    ChatInputView()
        .environmentObject(SceneDelegate())
}
