//
//  ChannelSelectPopView.swift
//  RoderickRalph
//
//  Created by Neoa on 2025/9/2.
//

import Foundation
import UIKit

// MARK: - Channel Models & Popup
struct Channel: Codable, Hashable {
    let id: String
    let name: String
}

protocol ChannelSelectPopupViewDelegate: AnyObject {
    func channelSelectPopupView(_ view: ChannelSelectPopupView, didSelect channel: Channel)
}

class ChannelSelectPopupView: UIView {
    weak var delegate: ChannelSelectPopupViewDelegate?
    private let channels: [Channel]

    private let backgroundView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    private let popupBackgroundImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pqan335")
        imageView.contentMode = .scaleToFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    private let titleButton: UIButton = {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "pqan333"), for: .normal)
        button.setTitle("请选择渠道", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.isUserInteractionEnabled = false
        return button
    }()

    private let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.translatesAutoresizingMaskIntoConstraints = false
        return sv
    }()

    private let stackView: UIStackView = {
        let sv = UIStackView()
        sv.axis = .vertical
        sv.spacing = 10
        sv.alignment = .fill
        sv.distribution = .fill
        sv.translatesAutoresizingMaskIntoConstraints = false
        return sv
    }()

    private let closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "pqan334"), for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    init(channels: [Channel]) {
        self.channels = channels
        super.init(frame: .zero)
        setupUI()
        setupConstraints()
        populateChannels()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        addSubview(backgroundView)
        addSubview(popupBackgroundImageView)
        addSubview(titleButton)
        addSubview(scrollView)
        scrollView.addSubview(stackView)
        addSubview(closeButton)
        closeButton.isHidden = true
        
        closeButton.addTarget(self, action: #selector(closePopup), for: .touchUpInside)

        // Tap to dismiss on the dim background
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(closePopup))
        backgroundView.addGestureRecognizer(tapGesture)
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            backgroundView.topAnchor.constraint(equalTo: topAnchor),
            backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor),
            backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor),
            backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor),

            popupBackgroundImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            popupBackgroundImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
            popupBackgroundImageView.widthAnchor.constraint(equalToConstant: 333),
            popupBackgroundImageView.heightAnchor.constraint(equalToConstant: 333),

            titleButton.topAnchor.constraint(equalTo: popupBackgroundImageView.topAnchor, constant: 10),
            titleButton.centerXAnchor.constraint(equalTo: popupBackgroundImageView.centerXAnchor),
            titleButton.widthAnchor.constraint(equalToConstant: 132),
            titleButton.heightAnchor.constraint(equalToConstant: 37),

            scrollView.topAnchor.constraint(equalTo: titleButton.bottomAnchor, constant: 12),
            scrollView.leadingAnchor.constraint(equalTo: popupBackgroundImageView.leadingAnchor, constant: 20),
            scrollView.trailingAnchor.constraint(equalTo: popupBackgroundImageView.trailingAnchor, constant: -20),
            scrollView.bottomAnchor.constraint(equalTo: popupBackgroundImageView.bottomAnchor, constant: -20),

            stackView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),

            closeButton.topAnchor.constraint(equalTo: popupBackgroundImageView.topAnchor, constant: -12),
            closeButton.trailingAnchor.constraint(equalTo: popupBackgroundImageView.trailingAnchor, constant: 12),
            closeButton.widthAnchor.constraint(equalToConstant: 24),
            closeButton.heightAnchor.constraint(equalToConstant: 24)
        ])
    }

    private func makeChannelButton(title: String) -> UIButton {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "tqan323"), for: .normal)
        button.setTitle(title, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        button.contentHorizontalAlignment = .center
        button.heightAnchor.constraint(equalToConstant: 45).isActive = true
        return button
    }

    private func populateChannels() {
        for (idx, channel) in channels.enumerated() {
            let button = makeChannelButton(title: channel.name)
                button.tag = idx
                button.addTarget(self, action: #selector(channelButtonTapped(_:)), for: .touchUpInside)
            stackView.addArrangedSubview(button)
        }
    }

    @objc private func channelButtonTapped(_ sender: UIButton) {
        let idx = sender.tag
        guard idx >= 0 && idx < channels.count else { return }
        let channel = channels[idx]
        delegate?.channelSelectPopupView(self, didSelect: channel)
    }

    @objc private func closePopup() {
//        removeFromSuperview()
    }
}
