//
//  CreateGroupViewController.swift
//  WoWonder
//
//  Created by Mac on 16/11/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift

class CreateGroupViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var groupImage: UIImageView!
    @IBOutlet weak var cameraImage: UIImageView!
    @IBOutlet weak var groupNameTextField: EmojiTextField!
    @IBOutlet weak var groupNameBorderView: UIView!
    @IBOutlet weak var keyboardTypeButton: UIButton!
    @IBOutlet weak var viewTableView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
    
    // MARK: - Properties
    
    private var selectedUsersArray: [UserData] = []
    private var idsString = ""
    private var imagePicker = UIImagePickerController()
    private var imageData: Data? = nil
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.viewTableView.isHidden = false
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Keyboard Type Button Action
    @IBAction func keyboardTypeButtonAction(_ sender: UIButton) {
        self.groupNameTextField.isEmojiKeyboard = !(self.groupNameTextField.isEmojiKeyboard)
        self.groupNameTextField.becomeFirstResponder()
        self.groupNameTextField.reloadInputViews()
        self.keyboardTypeButton.setImage(self.groupNameTextField.isEmojiKeyboard ? R.image.icon_keyboard_vector() : R.image.icon_emoji_vector(), for: .normal)
    }
    
    // Add Image Button Action
    @IBAction func addImageButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.imageAlertVC() {
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            newVC.delegate = self
            self.present(newVC, animated: true)
        }
    }
    
    // Add Participants Button Action
    @IBAction func addParticipantsButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.group.addParticipantsListViewController() {
            newVC.delegate = self
            newVC.selectedUserArray = self.selectedUsersArray
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Create Button Action
    @IBAction func createButtonAction(_ sender: UIButton) {
        self.idsString = self.selectedUsersArray.map { userData in
            return userData.user_id ?? ""
        }.joined(separator: ", ")
        print("idsString >>>>>", self.idsString)
        if self.imageData == nil {
            self.view.makeToast("Please select image")
            return
        }
        if self.groupNameTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            self.view.makeToast("Please enter name")
            return
        }
        if self.selectedUsersArray.count == 0 {
            self.view.makeToast("Please select at least one user")
            return
        }
        self.createGroup()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.textFieldSetup()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib(resource: R.nib.groupAddParticipantsCell), forCellReuseIdentifier: R.reuseIdentifier.groupAddParticipantsCell.identifier)
    }
    
    // TextField Setup
    func textFieldSetup() {
        self.groupNameTextField.attributedPlaceholder = NSAttributedString(
            string: "Enter group name",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.groupNameTextField.delegate = self
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension CreateGroupViewController {
    
    private func createGroup() {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        let sessionToken = AppInstance.instance.sessionId ?? ""
        let groupName  = self.groupNameTextField.text ?? ""
        let imageData = self.imageData
        let parts = self.idsString
        Async.background {
            GroupChatManager.instance.createGroup(session_Token: sessionToken, groupName: groupName, parts: parts, type: "create", avatar_data: imageData, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("success = \(success?.apiStatus ?? 0)")
                            appDelegate.window?.rootViewController?.view.makeToast("Group created successfully...")
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            self.view.makeToast(sessionError?.errors?.error_text ?? "")
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                            self.view.makeToast(serverError?.errors?.error_text ?? "")
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            print("error = \(error?.localizedDescription ?? "")")
                            self.view.makeToast(error?.localizedDescription ?? "")
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: TableView Setup
extension CreateGroupViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return selectedUsersArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "GroupAddParticipantsCell", for: indexPath) as! GroupAddParticipantsCell
        let userData = self.selectedUsersArray[indexPath.row]
        cell.delegate = self
        cell.indexPath = indexPath
        cell.setData(object: userData)
        return cell
    }
    
}

//MARK: AddParticipantsListViewControllerDelegate Methods
extension CreateGroupViewController: AddParticipantsListViewControllerDelegate {
    
    func sendSelectedParticipants(selectedParticipants: [UserData]) {
        self.selectedUsersArray = selectedParticipants
        self.tableView.reloadData()
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
}

// MARK: ImageAlertVCDelegate Methods
extension CreateGroupViewController: ImageAlertVCDelegate {
    
    func handleImageFromGalleryTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .PHOTO_LIBRARY)
    }
    
    func handleTakePictureFromCameraTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .CAMERA)
    }
    
    func setupImagePicker(imagePickerSourceType: ImagePickerSourceType) {
        self.view.endEditing(true)
        self.imagePicker.delegate = self
        switch imagePickerSourceType {
        case .CAMERA:
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePicker.sourceType = .camera
            } else {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.messageText = "You don't have camera"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.isHidden = true
                    return
                }
            }
        case .PHOTO_LIBRARY:
            self.imagePicker.sourceType = .photoLibrary
        }
        self.imagePicker.mediaTypes = ["public.image"]
        self.imagePicker.allowsEditing = false
        self.present(self.imagePicker, animated: true, completion: nil)
    }
    
}

// MARK: UIImagePickerControllerDelegate Methods
extension CreateGroupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                self.groupImage.image = image
                self.cameraImage.isHidden = true
                self.imageData = image.jpegData(compressionQuality: 1)
            }
        }
    }
    
}

// MARK: deleteParticipantDelegate Methods
extension CreateGroupViewController: GroupAddParticipantsCellDelegate {
    
    func handleDeleteParticipant(indexPath: IndexPath) {
        if let alertVC = R.storyboard.group.groupAlertVC() {
            alertVC.delegate = self
            alertVC.messageText = "Remove " + (self.selectedUsersArray[indexPath.row].name ?? "")
            alertVC.okText = "YES"
            alertVC.cancelText = "NO"
            self.present(alertVC, animated: true, completion: nil)
            alertVC.okButton.tag = indexPath.row
        }
    }
    
}

// MARK: GroupAlertVCDelegate Methods
extension CreateGroupViewController: GroupAlertVCDelegate {
    
    func groupAlertOKButtonPressed(_ sender: UIButton) {
        self.selectedUsersArray.remove(at: sender.tag)
        self.tableView.reloadData()
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
}

// MARK: UITextFieldDelegate Methods
extension CreateGroupViewController: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case self.groupNameTextField:
            self.groupNameBorderView.backgroundColor = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case self.groupNameTextField:
            self.groupNameBorderView.backgroundColor = UIColor(hex: "DDDDDD")
            self.groupNameTextField.isEmojiKeyboard = false
            self.keyboardTypeButton.setImage(self.groupNameTextField.isEmojiKeyboard ? R.image.icon_keyboard_vector() : R.image.icon_emoji_vector(), for: .normal)
        default:
            break
        }
    }
    
}

class EmojiTextField: UITextField {
    
    var isEmojiKeyboard = false
    
    // required for iOS 13
    override var textInputContextIdentifier: String? { "" }
    
    override var textInputMode: UITextInputMode? {
        if self.isEmojiKeyboard {
            for mode in UITextInputMode.activeInputModes {
                if mode.primaryLanguage == "emoji" {
                    return mode
                }
            }
        } else {
            return UITextInputMode.activeInputModes.first
        }
        return nil
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        
        commonInit()
    }
    
    func commonInit() {
        NotificationCenter.default.addObserver(self, selector: #selector(inputModeDidChange), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
    }
    
    @objc func inputModeDidChange(_ notification: Notification) {
        guard isFirstResponder else {
            return
        }
        DispatchQueue.main.async { [weak self] in
            self?.reloadInputViews()
        }
    }
    
}
