//
//  MessageOptionViewController.swift
//  WoWonder
//
//  Created by UnikApp on 04/03/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit

protocol MessageOptionDelegate: AnyObject {
    func handleReactionTap(reaction: Int, optionName: String, indexPath: IndexPath)
    func handleMessageOptionTap(index: Int, optionName: String, indexPath: IndexPath)
}

class MessageOptionViewController: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var reactionView: UIView!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var copyIcon: UIImageView!
    @IBOutlet weak var copyView: UIControl!
    @IBOutlet weak var messageInfoIcon: UIImageView!
    @IBOutlet weak var messageInfoView: UIControl!
    @IBOutlet weak var deleteMessageIcon: UIImageView!
    @IBOutlet weak var deleteMessageView: UIControl!
    @IBOutlet weak var replyIcon: UIImageView!
    @IBOutlet weak var replyView: UIControl!
    @IBOutlet weak var forwardIcon: UIImageView!
    @IBOutlet weak var forwardView: UIControl!
    @IBOutlet weak var pinIcon: UIImageView!
    @IBOutlet weak var pinTitleLabel: UILabel!
    @IBOutlet weak var pinView: UIControl!
    @IBOutlet weak var favouriteIcon: UIImageView!
    @IBOutlet weak var favouriteTitleLabel: UILabel!
    @IBOutlet weak var favouriteView: UIControl!
    
    // MARK: - Properties
    
    var sheetHeight: CGFloat = 0
    var sheetBackgroundColor: UIColor = .color_fill
    var sheetCornerRadius: CGFloat = 20
    private var hasSetOriginPoint = false
    private var originPoint: CGPoint?
    var delegate: MessageOptionDelegate?
    var indexPath = IndexPath()
    var isCopy = false
    var message: Messages?
    let reactionGifArray = ["gif_like", "gif_love", "gif_haha", "gif_wow", "gif_sad", "gif_angry"]
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        self.initialConfig()
    }
    
    override func viewDidLayoutSubviews() {
        if !hasSetOriginPoint {
            hasSetOriginPoint = true
            originPoint = view.frame.origin
        }
    }
    
    // MARK: - Selectors

    // Copy Button Action
    @IBAction func copyButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 0, optionName: "Copy", indexPath: self.indexPath)
        }
    }
    
    // Message Button Action
    @IBAction func messageInfoButtonAction(_ sender: UIColor) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 1, optionName: "Message Info", indexPath: self.indexPath)
        }
    }
    
    // Delete Message Button Action
    @IBAction func deleteMessaageButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 2, optionName: "Delete Message", indexPath: self.indexPath)
        }
    }
    
    // Reply Button Action
    @IBAction func replyButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 3, optionName: "Relpy", indexPath: self.indexPath)
        }
    }
    
    // Forward Button Action
    @IBAction func forwardButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 4, optionName: "Forward", indexPath: self.indexPath)
        }
    }
    
    // Pin Button Action
    @IBAction func PinButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 5, optionName: "Pin", indexPath: self.indexPath)
        }
    }
    
    // Favourite Button Action
    @IBAction func favouriteButtonAction(_ sender: UIControl) {
        self.dismiss(animated: true) {
            self.delegate?.handleMessageOptionTap(index: 6, optionName: "Favourite", indexPath: self.indexPath)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.sheetHeight = ((self.message?.type?.contains("right_") ?? false) ? (self.isCopy ? 336 : 288) : (self.isCopy ? 320 : 272)) + 32 + self.view.safeAreaBottom
        view.frame.size.height = sheetHeight
        view.isUserInteractionEnabled = true
        view.backgroundColor = sheetBackgroundColor
        view.roundCorners(corners: [.topLeft, .topRight], radius: sheetCornerRadius)
        self.setPanGesture()
        self.setUpUI()
        self.setUpReactionView()
    }
    
    // SetUp UI
    func setUpUI() {
        self.copyView.isHidden = !self.isCopy
        self.messageInfoView.isHidden = !(self.message?.type?.contains("right_") ?? false)
        self.deleteMessageView.isHidden = !(self.message?.type?.contains("right_") ?? false)
        self.pinTitleLabel.text = (self.message?.pin == "yes") ? "Unpin" : "Pin"
        self.favouriteTitleLabel.text = (self.message?.fav == "yes") ? "UnFavourite" : "Favourite"
        if let objColor = UserDefaults.standard.value(forKey: "ColorTheme") as? String, objColor != "" {
            self.copyIcon.tintColor = UIColor(hex: objColor)
            self.messageInfoIcon.tintColor = UIColor(hex: objColor)
            self.deleteMessageIcon.tintColor = UIColor(hex: objColor)
            self.replyIcon.tintColor = UIColor(hex: objColor)
            self.forwardIcon.tintColor = UIColor(hex: objColor)
            self.pinIcon.tintColor = UIColor(hex: objColor)
            self.favouriteIcon.tintColor = UIColor(hex: objColor)
        }
    }
    
    // Set Pan Gesture
    func setPanGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction))
        view.addGestureRecognizer(panGesture)
    }
    
    // Setup Reaction View
    func setUpReactionView() {
        if (self.message?.type?.contains("left_") ?? false) {
            self.reactionView.isHidden = false
            self.collectionViewSetUp()
        } else {
            self.reactionView.isHidden = true
        }
    }
    
    // Collection View SetUp
    func collectionViewSetUp() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.reactionGifCell), forCellWithReuseIdentifier: R.reuseIdentifier.reactionGifCell.identifier)
    }
    
    // Gesture Recognizer
    @objc func panGestureRecognizerAction(sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: view)
        // Not allowing the user to drag the view upward
        guard translation.y >= 0 else { return }
        view.frame.origin = CGPoint(
            x: 0,
            y: self.originPoint!.y + translation.y
        )
        if sender.state == .ended {
            self.dismiss(animated: true, completion: nil)
        }
    }
    
}

// MARK: - Extensions

// MARK: Collection View SetUp
extension MessageOptionViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.reactionGifArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.reactionGifCell.identifier, for: indexPath) as! ReactionGifCell
        let gif = self.reactionGifArray[indexPath.item]
        cell.setReactionGif(gif: gif)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.dismiss(animated: true) {
            self.delegate?.handleReactionTap(reaction: (indexPath.item + 1), optionName: "Reaction", indexPath: self.indexPath)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let totalWidth = collectionView.frame.width - 48
        let totalCellWidth = collectionView.height * CGFloat(self.reactionGifArray.count)
        if CGFloat(totalCellWidth) < totalCellWidth {
            return CGSize(width: collectionView.height, height: collectionView.height)
        } else {
            let width = totalWidth * collectionView.height / CGFloat(totalCellWidth)
            return CGSize(width: width, height: width)
        }
    }
    
}

extension MessageOptionDelegate {
    
    func handleReactionTap(reaction: Int, optionName: String, indexPath: IndexPath) {
        
    }
    
}
