import UIKit

final class PlayerViewController: UIViewController {
    private let titleLabel = UILabel()
    private let subtitleLabel = UILabel()
    private let urlTextField = UITextField()
    private let confirmButton = UIButton(type: .system)
    private let messageLabel = UILabel()
    private let queueLabel = UILabel()
    private let queueStack = UIStackView()
    private var recentURLs: [URL] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        configureView()
        configureHierarchy()
    }

    private func configureView() {
        view.backgroundColor = UIColor(red: 0.96, green: 0.97, blue: 0.98, alpha: 1.0)
        title = "GMPlayer"

        titleLabel.text = "Video URLs"
        titleLabel.font = .systemFont(ofSize: 28, weight: .bold)
        titleLabel.textColor = .label

        subtitleLabel.text = "Enter an mp4 or m3u8 video URL to keep it in the list."
        subtitleLabel.font = .systemFont(ofSize: 15, weight: .regular)
        subtitleLabel.textColor = .secondaryLabel
        subtitleLabel.numberOfLines = 0

        urlTextField.placeholder = "https://example.com/video.m3u8"
        urlTextField.borderStyle = .none
        urlTextField.backgroundColor = .white
        urlTextField.layer.cornerRadius = 8
        urlTextField.layer.masksToBounds = true
        urlTextField.autocapitalizationType = .none
        urlTextField.autocorrectionType = .no
        urlTextField.clearButtonMode = .whileEditing
        urlTextField.keyboardType = .URL
        urlTextField.returnKeyType = .go
        urlTextField.delegate = self
        urlTextField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 14, height: 1))
        urlTextField.leftViewMode = .always

        confirmButton.setTitle("Play", for: .normal)
        confirmButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
        confirmButton.tintColor = .white
        confirmButton.backgroundColor = UIColor(red: 0.15, green: 0.42, blue: 0.45, alpha: 1.0)
        confirmButton.layer.cornerRadius = 8
        confirmButton.addTarget(self, action: #selector(addEnteredURL), for: .touchUpInside)

        messageLabel.font = .systemFont(ofSize: 13, weight: .medium)
        messageLabel.textColor = .secondaryLabel
        messageLabel.numberOfLines = 0

        queueLabel.text = "History"
        queueLabel.font = .systemFont(ofSize: 18, weight: .semibold)
        queueLabel.textColor = .label

        queueStack.axis = .vertical
        queueStack.spacing = 10
        updateQueue()
    }

    private func configureHierarchy() {
        let inputStack = UIStackView(arrangedSubviews: [urlTextField, confirmButton])
        inputStack.axis = .horizontal
        inputStack.spacing = 10
        inputStack.alignment = .fill
        inputStack.distribution = .fill

        let contentStack = UIStackView(arrangedSubviews: [
            titleLabel,
            subtitleLabel,
            inputStack,
            messageLabel,
            queueLabel,
            queueStack
        ])
        contentStack.axis = .vertical
        contentStack.spacing = 18
        contentStack.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(contentStack)

        NSLayoutConstraint.activate([
            urlTextField.heightAnchor.constraint(equalToConstant: 46),
            confirmButton.widthAnchor.constraint(equalToConstant: 76),
            contentStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
            contentStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
            contentStack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 24)
        ])
    }

    @objc private func addEnteredURL() {
        view.endEditing(true)

        guard let url = validatedURL(from: urlTextField.text) else {
            showMessage("Enter a valid http or https video URL ending in .m3u8 or .mp4.", isError: true)
            return
        }

        showMessage("Added \(url.lastPathComponent)", isError: false)
        remember(url)
        present(VideoPlayerViewController(url: url), animated: true)
    }

    private func validatedURL(from text: String?) -> URL? {
        guard
            let rawValue = text?.trimmingCharacters(in: .whitespacesAndNewlines),
            let url = URL(string: rawValue),
            let scheme = url.scheme?.lowercased(),
            ["http", "https"].contains(scheme)
        else {
            return nil
        }

        let lowercasedPath = url.path.lowercased()
        guard lowercasedPath.hasSuffix(".m3u8") || lowercasedPath.hasSuffix(".mp4") else {
            return nil
        }

        return url
    }

    private func showMessage(_ text: String, isError: Bool) {
        messageLabel.text = text
        messageLabel.textColor = isError ? .systemRed : .secondaryLabel
    }

    private func remember(_ url: URL) {
        recentURLs.removeAll { $0 == url }
        recentURLs.insert(url, at: 0)
        recentURLs = Array(recentURLs.prefix(3))
        updateQueue()
    }

    private func updateQueue() {
        queueStack.arrangedSubviews.forEach { view in
            queueStack.removeArrangedSubview(view)
            view.removeFromSuperview()
        }

        let items = recentURLs.isEmpty ? ["No videos added yet"] : recentURLs.map(\.absoluteString)
        items.forEach { item in
            let button = UIButton(type: .system)
            button.setTitle(item, for: .normal)
            button.titleLabel?.font = .systemFont(ofSize: 15, weight: .medium)
            button.titleLabel?.lineBreakMode = .byTruncatingMiddle
            button.contentHorizontalAlignment = .left
            button.tintColor = .label
            button.backgroundColor = .white
            button.layer.cornerRadius = 8
            button.contentEdgeInsets = UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14)
            button.addTarget(self, action: #selector(selectRecentURL(_:)), for: .touchUpInside)
            button.isEnabled = !recentURLs.isEmpty
            queueStack.addArrangedSubview(button)
        }
    }

    @objc private func selectRecentURL(_ sender: UIButton) {
        urlTextField.text = sender.title(for: .normal)
    }

}

extension PlayerViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        addEnteredURL()
        return true
    }
}
