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

import UIKit
import Async

class GroupChatSearchConversationVC: BaseVC {
    
    // MARK: - IBOutlets

    @IBOutlet weak var headerLabel: UILabel!
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var searchClearButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    var isSearch = false
    var groupData: GroupData?
    var messagesArray: [MessageModel] = []
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        if self.isSearch {
            self.isSearch = false
            self.searchButton.isHidden = false
            self.headerLabel.isHidden = false
            self.searchTextField.text = ""
            self.searchTextField.resignFirstResponder()
            self.searchTextField.isHidden = true
            self.searchClearButton.isHidden = true
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    // Search Button Action
    @IBAction func searchButtonAction(_ sender: UIButton) {
        self.isSearch = true
        self.searchButton.isHidden = true
        self.headerLabel.isHidden = true
        self.searchTextField.isHidden = false
        self.searchTextField.becomeFirstResponder()
    }
    
    // Search Clear Button Action
    @IBAction func searchClearButtonAction(_ sender: UIButton) {
        self.searchTextField.text = ""
        self.searchClearButton.isHidden = true
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
        self.tableView.addGestureRecognizer(longPressRecognizer)
        self.registerCell()
        self.textFieldSetup()
    }
    
    func textFieldSetup() {
        self.searchTextField.attributedPlaceholder = NSAttributedString(
            string: "Search the conversation",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.searchTextField.delegate = self
    }
    
    // Register Cell
    func registerCell() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        if #available(iOS 15.0, *) {
            UITableView.appearance().isPrefetchingEnabled = false
        }
        self.tableView.register(UINib(resource: R.nib.leftTextTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftTextTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightTextTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightTextTableViewCell.identifier)
    }
    
    // TableView longPressed Click
    @objc func longPressed(sender: UILongPressGestureRecognizer) {
        let objSender = sender.location(in: self.tableView)
        let indexPath = self.tableView.indexPathForRow(at: objSender)
        let objCopyMessageArray = self.messagesArray[indexPath?.row ?? 0]
        if let newVC = R.storyboard.group.groupChatSearchConversationOptionsVC() {
            newVC.delegate = self
            newVC.indexPath = indexPath ?? IndexPath()
            newVC.isCopy = true
            newVC.isRightUser = AppInstance.instance.userId == self.messagesArray[indexPath?.row ?? 0].messageUser?.user_id
            self.present(newVC, animated: true)
        }
    }

}

// MARK: - Extensions

// MARK: Api Call
extension GroupChatSearchConversationVC {
    
    // Get Pin Message Api Call
    private func getSearchMessages(text: String) {
        Async.background {
            GroupChatManager.instance.getSearchMessage(group_id: self.groupData?.group_id ?? "", text: text, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.messagesArray = success?.data ?? []
                            if self.messagesArray.count == 0 {
                                self.tableView.isHidden = true
                                self.emptyView.isHidden = false
                            } else {
                                self.tableView.isHidden = false
                                self.emptyView.isHidden = true
                            }
                            self.tableView.reloadData()
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(sessionError?.errors?.error_text)
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(serverError?.errors?.error_text)
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            })
        }
    }
    
    // Delete Message Api
    private func deleteMessage(messageID: String, indexPath: Int) {
        let sessionID = AppInstance.instance._sessionId
        Async.background {
            ChatManager.instance.deleteChatMessage(messageId: messageID , session_Token: sessionID, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("userList = \(success?.message ?? "")")
                            let appDelegate = (UIApplication.shared.delegate) as? AppDelegate
                            let context = appDelegate?.persistentContainer.viewContext
                            guard let msg = Messages.getMessageByID(self.messagesArray[indexPath].id ?? "") else { return }
                            context?.delete(msg)
                            do {
                                try context?.save()
                            } catch {
                                print("failed so save data after deleting object")
                            }
                            self.messagesArray.remove(at: indexPath)
                            self.tableView.reloadData()
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(sessionError?.errors?.error_text)
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(serverError?.errors?.error_text)
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: TableView Setup
extension GroupChatSearchConversationVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messagesArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightTextTableViewCell.identifier, for: indexPath) as! RightTextTableViewCell
            self.setRightTextData(cell: cell, indexPathForCell: indexPath)
            return cell
        } else {
            let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftTextTableViewCell.identifier, for: indexPath) as! LeftTextTableViewCell
            self.setLeftTextData(cell: cell, indexPathForCell: indexPath)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    // Set Left Text Data
    private func setLeftTextData(cell: LeftTextTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.masageTextLabel.text = objChatList.text ?? ""
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        let userAvatarUrl = URL(string: objChatList.messageUser?.avatar ?? "")
        DispatchQueue.global(qos: .userInteractive).async {
            cell.userImageView.sd_setImage(with: userAvatarUrl, placeholderImage: UIImage(named: ""))
        }
        cell.userNameLabel.text = objChatList.messageUser?.name ?? ""
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Text Data
    private func setRightTextData(cell: RightTextTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messaageTextLabel.text = objChatList.text ?? ""
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageVIew.isHidden = false
        } else {
            cell.starImageVIew.isHidden = true
        }
    }
    
}

// MARK: UITextFieldDelegate
extension GroupChatSearchConversationVC: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        let updatedText = (currentText as NSString).replacingCharacters(in: range, with: string)
        if updatedText.count == 0 {
            self.searchClearButton.isHidden = true
        } else {
            self.searchClearButton.isHidden = false
        }
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.getSearchMessages(text: currentText)
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.getSearchMessages(text: currentText)
        }
    }
    
}

// MARK: GroupChatSearchConversationOptionsVCDelegate
extension GroupChatSearchConversationVC: GroupChatSearchConversationOptionsVCDelegate {
    
    func handleMessageOptionTap(index: Int, optionName: String, indexPath: IndexPath) {
        let object = self.messagesArray[indexPath.row]
        if index == 0 {
            let messageString = object.orginal_text
            UIPasteboard.general.string = messageString
        } else if index == 1 {
            if let newVC = R.storyboard.favorite.messageInfoViewController() {
                if let message = Messages.getMessageByID(object.id ?? "") {
                    newVC.object = message
                }
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        } else if index == 2 {
            self.deleteMessage(messageID: object.id ?? "", indexPath: indexPath.row)
        } else if index == 3 {
            if let newVC = R.storyboard.favorite.getFriendVC() {
                if let message = Messages.getMessageByID(object.id ?? "") {
                    newVC.message = message
                }
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        }
    }
    
}
