import Foundation
import UIKit

/// delegate protocol for people view
protocol OsobyViewDelegate: AnyObject {
    func showError(title: String, subtite: String)
    func searchForPerson(query: String, jednotky: Bool, skauti: Bool)
}

/// people view
class OsobyView: UIView {
    
    weak var delegate: OsobyViewDelegate?
    
    private let title: UILabel = {
        let view = UILabel()
        view.text = "Zadej jmeno nebo prezdivku dane osoby"
        view.textColor = scoutBlue
        view.textAlignment = .center
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    private let jednotkyLabel: UILabel = {
        let view = UILabel()
        view.text = "Hledat v jednotkach"
        view.textColor = scoutBlue
        return view
    }()
    
    private let SkautLabel: UILabel = {
        let view = UILabel()
        view.text = "Hledat i ve Skautskem adresari"
        view.textColor = scoutBlue
        return view
    }()
    
    private let jednotkySwitch: UISwitch = {
        let view = UISwitch()
        view.setOn(false, animated: false)
        return view
    }()
    
    private let adresarSwitch: UISwitch = {
        let view = UISwitch()
        view.setOn(false, animated: false)
        return view
    }()
    
    private let inputText: UITextField = {
        let view = UITextField()
        view.text = "Jmeno"
        view.layer.borderWidth = 1
        view.leftViewMode = .always
        view.leftView = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
        view.layer.borderColor = UIColor.black.cgColor
        view.textColor = UIColor.lightGray
        view.translatesAutoresizingMaskIntoConstraints = false
        view.heightAnchor.constraint(equalToConstant: 45).isActive = true
        return view
    }()
    
    private let button: UIButton = {
        let button = UIButton()
        button.setTitle("Hledat", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.showsTouchWhenHighlighted = true
        button.backgroundColor = scoutBlue
        button.layer.cornerRadius = 10
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    private let stackView: UIStackView = {
        let view = UIStackView()
        view.axis = .vertical
        view.spacing = 20
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    /// initialization function
    /// - Parameter frame: frame
    override init(frame: CGRect) {
        super.init(frame: frame)
        inputText.delegate = self
        button.addTarget(self, action: #selector(tap), for: .touchUpInside)
        addSubview(title)
        addSubview(inputText)
        setupStackView()
        addSubview(stackView)
        addSubview(button)
        backgroundColor = .white
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// setup function for stack views
    private func setupStackView() {
        let first = setupStack(title: jednotkyLabel, labelSwitch: jednotkySwitch)
        let second = setupStack(title: SkautLabel, labelSwitch: adresarSwitch)
        stackView.addArrangedSubview(first)
        stackView.addArrangedSubview(second)
    }
    
    /// setup function for stack view
    /// - Parameters:
    ///   - title: title for stack view
    ///   - labelSwitch: switch
    /// - Returns: configured stack based on parameters
    private func setupStack(title: UILabel, labelSwitch: UISwitch) -> UIStackView {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.addArrangedSubview(title)
        stack.addArrangedSubview(labelSwitch)
        return stack
    }
    
    /// function that sets up the view based on given constraints
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            title.topAnchor.constraint(equalTo: topAnchor, constant: 80),
            title.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12),
            title.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12),
            
            inputText.topAnchor.constraint(equalTo: title.bottomAnchor, constant: 12),
            inputText.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 40),
            inputText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -40),

            stackView.topAnchor.constraint(equalTo: inputText.bottomAnchor, constant: 25),
            stackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 30),
            stackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -30),

            button.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 25),
            button.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 40),
            button.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -40),
            button.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor)
        ])
    }
    
    /// function that gets called when user taps on button, it checks the given inputs and shows error if non is selected or no input is provided
    @objc private func tap() {
        if (inputText.text?.isEmpty ?? false) {
            delegate?.showError(title: "Pozor", subtite: "Nebylo zadáno jméno. Hledání bez uvedení jména je možné pouze ve Skautském adresáři. Musíš však zvolit nějakou činnost.")
            return
        }
        if (!jednotkySwitch.isOn && !adresarSwitch.isOn) {
            delegate?.showError(title: "Pozor", subtite: "Není povoleno hledání ani mezi členy jednotky, ani ve Skautském adresáři. Povol alespoň jednu možnost, pak bude možné hledat.")
            return
        }
        guard let input = inputText.text else { return }
        delegate?.searchForPerson(query: input, jednotky: jednotkySwitch.isOn, skauti: adresarSwitch.isOn)
    }
}

extension OsobyView: UITextFieldDelegate {
    
    /// delegate function that shows that text field began editing
    /// - Parameter textView: text view
    func textFieldDidBeginEditing(_ textView: UITextField) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }
    
    /// delegate function that shows that text field ended editing
    /// - Parameter textView: text view
    func textFieldDidEndEditing(_ textView: UITextField) {
        if textView.text?.isEmpty ?? false {
            textView.text = "Jmeno"
            textView.textColor = UIColor.lightGray
        }
    }
}
