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

import UIKit

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

class BroadcastMessageOptionVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var copyIcon: UIImageView!
    @IBOutlet weak var copyView: 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: BroadcastMessageOptionDelegate?
    var indexPath = IndexPath()
    var isCopy = false
    var message: Messages?
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        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)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.sheetHeight = 48 + 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()
    }
    
    // SetUp UI
    func setUpUI() {
        if let objColor = UserDefaults.standard.value(forKey: "ColorTheme") as? String, objColor != "" {
            self.copyIcon.tintColor = UIColor(hex: objColor)
        }
    }
    
    // Set Pan Gesture
    func setPanGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction))
        view.addGestureRecognizer(panGesture)
    }
    
    // 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)
        }
    }

}
