//
//  CreateBroadcastVC.swift
//  WoWonder
//
//  Created by iMac on 20/05/24.
//  Copyright © 2024 ScriptSun. All rights reserved.
//

import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift

protocol CreateBroadcastVCDelegate {
    func handleCreateBroadcast(broadcast: Broadcast?)
}

class CreateBroadcastVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var broadcastImage: UIImageView!
    @IBOutlet weak var cameraImage: UIImageView!
    @IBOutlet weak var broadcastNameTextField: EmojiTextField!
    @IBOutlet weak var broadcastNameBorderView: 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
    var delegate: CreateBroadcastVCDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        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.broadcastNameTextField.isEmojiKeyboard = !(self.broadcastNameTextField.isEmojiKeyboard)
        self.broadcastNameTextField.becomeFirstResponder()
        self.broadcastNameTextField.reloadInputViews()
        self.keyboardTypeButton.setImage(self.broadcastNameTextField.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.broadcastNameTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            self.view.makeToast("Please enter name")
            return
        }
        if self.selectedUsersArray.count < 2 {
            self.view.makeToast("Please select at least two users")
            return
        }
        self.createBroadcast()
    }
    
    // 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.broadcastNameTextField.attributedPlaceholder = NSAttributedString(
            string: "Enter name broadcast",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.broadcastNameTextField.delegate = self
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension CreateBroadcastVC {
    
    private func createBroadcast() {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        let sessionToken = AppInstance.instance.sessionId ?? ""
        let broadcast_name  = self.broadcastNameTextField.text ?? ""
        let imageData = self.imageData
        let users = self.idsString
        Async.background {
            BroadcastManager.instance.createBroadcast(session_Token: sessionToken, broadcast_name: broadcast_name, users: users, avatar_data: imageData, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("success = \(success?.api_status ?? 0)")
                            if let broadcastData = success?.data {
                                self.navigationController?.popViewController(animated: true)
                                let broadcast = Broadcast(broadcast: broadcastData)
                                self.delegate?.handleCreateBroadcast(broadcast: broadcast)                                
                            }
                        }
                    }
                } 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 CreateBroadcastVC: 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 CreateBroadcastVC: 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 CreateBroadcastVC: 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 CreateBroadcastVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                self.broadcastImage.image = image
                self.cameraImage.isHidden = true
                self.imageData = image.jpegData(compressionQuality: 1)
            }
        }
    }
    
}

// MARK: deleteParticipantDelegate Methods
extension CreateBroadcastVC: 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 CreateBroadcastVC: 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 CreateBroadcastVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case self.broadcastNameTextField:
            self.broadcastNameBorderView.backgroundColor = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case self.broadcastNameTextField:
            self.broadcastNameBorderView.backgroundColor = UIColor(hex: "DDDDDD")
            self.broadcastNameTextField.isEmojiKeyboard = false
            self.keyboardTypeButton.setImage(self.broadcastNameTextField.isEmojiKeyboard ? R.image.icon_keyboard_vector() : R.image.icon_emoji_vector(), for: .normal)
        default:
            break
        }
    }
    
}
