import UIKit

// MARK: - ProfileTabBarDelegate

protocol ProfileTabBarDelegate: AnyObject {
    func tabBar(_ tabBar: ProfileTabBarView, didSelectTabAt index: Int)
}

// MARK: - ProfileTabBarView

/// Telegram-parity capsule tab bar with animated selection indicator.
/// Used by both OpponentProfileViewController and GroupInfoViewController.
final class ProfileTabBarView: UIView {

    weak var delegate: ProfileTabBarDelegate?

    private let titles: [String]
    private var tabButtons: [UIButton] = []
    private let selectionIndicator = UIView()
    private let containerView = UIView()
    private(set) var selectedIndex = 0

    // Colors (adaptive)
    private let activeColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }
    private let inactiveColor = UIColor { $0.userInterfaceStyle == .dark
        ? UIColor(white: 1.0, alpha: 0.6)
        : UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
    }
    private let indicatorFill = UIColor { $0.userInterfaceStyle == .dark
        ? UIColor(white: 1.0, alpha: 0.18)
        : UIColor(red: 0, green: 0, blue: 0, alpha: 0.08)
    }
    private let containerFill = UIColor { $0.userInterfaceStyle == .dark
        ? UIColor(red: 28/255, green: 28/255, blue: 29/255, alpha: 1)
        : UIColor(red: 242/255, green: 242/255, blue: 247/255, alpha: 1)
    }

    // MARK: - Init

    init(titles: [String]) {
        self.titles = titles
        super.init(frame: .zero)
        setupViews()
    }

    @available(*, unavailable) required init?(coder: NSCoder) { fatalError() }

    // MARK: - Setup

    private func setupViews() {
        containerView.layer.cornerCurve = .continuous
        containerView.backgroundColor = containerFill
        addSubview(containerView)

        selectionIndicator.backgroundColor = indicatorFill
        containerView.addSubview(selectionIndicator)

        for (index, title) in titles.enumerated() {
            let button = UIButton(type: .system)
            button.setTitle(title, for: .normal)
            button.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
            button.setTitleColor(index == 0 ? activeColor : inactiveColor, for: .normal)
            button.tag = index
            button.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
            containerView.addSubview(button)
            tabButtons.append(button)
        }
    }

    // MARK: - Layout

    override func layoutSubviews() {
        super.layoutSubviews()

        let containerH: CGFloat = 38
        containerView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: containerH)
        containerView.layer.cornerRadius = containerH / 2

        let padding: CGFloat = 3
        let innerW = containerView.bounds.width - padding * 2
        let tabW = innerW / CGFloat(titles.count)

        for (index, button) in tabButtons.enumerated() {
            button.frame = CGRect(
                x: padding + CGFloat(index) * tabW,
                y: padding,
                width: tabW,
                height: containerH - padding * 2
            )
        }

        layoutIndicator(animated: false)
    }

    override var intrinsicContentSize: CGSize {
        CGSize(width: UIView.noIntrinsicMetric, height: 38)
    }

    private func layoutIndicator(animated: Bool) {
        guard selectedIndex < tabButtons.count else { return }
        let button = tabButtons[selectedIndex]
        let indicatorFrame = button.frame
        selectionIndicator.layer.cornerRadius = indicatorFrame.height / 2

        if animated {
            UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0) {
                self.selectionIndicator.frame = indicatorFrame
            }
        } else {
            selectionIndicator.frame = indicatorFrame
        }
    }

    // MARK: - Selection

    @objc private func tabTapped(_ sender: UIButton) {
        let index = sender.tag
        guard index != selectedIndex else { return }
        selectTab(at: index, animated: true)
        delegate?.tabBar(self, didSelectTabAt: index)
    }

    func selectTab(at index: Int, animated: Bool) {
        guard index >= 0, index < titles.count else { return }
        selectedIndex = index

        for (i, button) in tabButtons.enumerated() {
            button.setTitleColor(i == index ? activeColor : inactiveColor, for: .normal)
        }

        layoutIndicator(animated: animated)
    }
}
