//
//  CaptchaVC.swift
//  WOKA
//
//  Created by Bilal on 20/09/2024.
//

import UIKit

class CaptchaVC: UIViewController {

    // Outlets for UI components
    @IBOutlet weak var totalTF: TextFieldShadow!
    @IBOutlet weak var cancelBtn: LocalisedElementsButton!
    @IBOutlet weak var doneBtn: LocalisedElementsButton!
    @IBOutlet weak var reloadCaptcha: UIButton!
    @IBOutlet weak var integer1: UILabel!
    @IBOutlet weak var integer2: UILabel!
    @IBOutlet weak var mathOperator: UILabel!
    @IBOutlet weak var calculationView: UIView!
    @IBOutlet weak var outerTransparentView: UIView!
    @IBOutlet weak var closeBtn: UIButton!
    
    // Completion block to be executed when the alert is dismissed
    var onDoneBlock: (() -> Void)?
    
    // Variables to hold the randomly generated numbers
    var num1 = Int()
    var num2 = Int()
    
    // Array of operators to randomly select from
    let operators = ["+", "-"] // "*", "÷"
    
    // MARK: - View Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        // Set text field delegate
        totalTF.delegate = self
        
        setupCaptcha()
        handleTaps()
        calculationView.addShadowAndCorner(radius: 10, shadowColor: .darkGray, shadowOpacity: 0.6, shadowOffset: CGSize(width: 0, height: 0.5), shadowRadius: 5)
    }

    // MARK: - Button Actions
    @IBAction func btnTapped(_ sender: UIButton) {
        switch sender {
        case reloadCaptcha:
            setupCaptcha()
        case doneBtn:
            handleDoneAction()
        case cancelBtn, closeBtn:
            self.dismiss(animated: true)
        default:
            break
        }
    }
    
    // setup the captcha
    func setupCaptcha(){
        // Generate random numbers and operator
        num1 = Int.random(in: 2...20)
        num2 = Int.random(in: 2...20)
        mathOperator.text = operators.randomElement()!
        
        // Animate the change in the labels with cross dissolve
        UIView.transition(with: integer1, duration: 0.3, options: .transitionCrossDissolve, animations: {
            self.integer1.text = String(self.num1)
        })

        UIView.transition(with: integer2, duration: 0.3, options: .transitionCrossDissolve, animations: {
            self.integer2.text = String(self.num2)
        })

        UIView.transition(with: mathOperator, duration: 0.3, options: .transitionCrossDissolve, animations: {
            self.mathOperator.text = self.operators.randomElement()!
        })
    }
    
    //tapgesture
    func handleTaps(){
        outerTransparentView.addTapGesture {
            self.dismiss(animated: true)
        }
    }
    
    // Function to handle the done button action
    func handleDoneAction() {
        // Ensure the user has entered a value
        guard let userInput = totalTF.text, !userInput.isEmpty else {
            Utilities.alertWithBtn(title: "CAPTCHA", msgBody: "Please enter total value", okBtnStr: "OK", vc: self)
            return
        }
        
        // Calculate the result based on the operator
        let result = calculateResult()
        
        // Validate the user's input
        validateCaptcha(result: result)
    }
    
    // Function to calculate the result based on the operator
    func calculateResult() -> Int {
        var result: Int = 0
        
        switch mathOperator.text {
        case "+":
            result = num1 + num2
        case "-":
            result = num1 - num2
//        case "*":
//            result = num1 * num2
//        case "÷":
//            if num2 != 0 {
//                result = num1 / num2
//            } else {
//                print("Division by zero is not allowed")
//            }
        default:
            print("Invalid operator")
        }
        
        return result
    }
    
    // Function to validate the CAPTCHA input
    func validateCaptcha(result: Int) {
        if let userResult = Int(totalTF.text!) {
            if userResult == result {
                self.dismiss(animated: true)
                self.onDoneBlock?()
                print("CAPTCHA validation successful!")
            } else {
                Utilities.alertWithBtn(title: "CAPTCHA", msgBody: "Captcha Validation failed", okBtnStr: "OK", vc: self)
            }
        } else {
            print("Invalid input")
        }
    }
}

// MARK: - TextField Delegate

extension CaptchaVC: UITextFieldDelegate {
    
    // Text field delegate method to handle input validation
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // Ensure only valid characters are entered
        if !string.onlyNumber() { return false }
        
        // Limit the character length to 2
        return ValidatorClass.sharedInstanec.limitCharacter(length: 10, textField, shouldChangeCharactersIn: range, replacementString: string)
    }
}
