import UIKit
import SwiftUI

/// Individual selected contact pill in the token list.
/// Telegram parity: 28pt height, 24pt avatar, name label, X remove button.
final class TokenChipView: UIView {

    // MARK: - Layout Constants

    private enum Layout {
        static let height: CGFloat = 28
        static let avatarSize: CGFloat = 22
        static let avatarInset: CGFloat = 3
        static let textOffset: CGFloat = 28
        static let removeSize: CGFloat = 16
        static let trailingPadding: CGFloat = 6
        static let cornerRadius: CGFloat = 14
        static let maxWidth: CGFloat = 140
    }

    // MARK: - Properties

    let dialogKey: String
    var onRemove: ((String) -> Void)?

    // MARK: - Subviews

    private let backgroundGlass = UIView()
    private let avatarBackgroundView = UIView()
    private let avatarInitialsLabel = UILabel()
    private let avatarImageView = UIImageView()
    private let nameLabel = UILabel()
    private let removeButton = UIButton(type: .system)

    private static let mantineDarkBody = UIColor(red: 0x1A/255.0, green: 0x1B/255.0, blue: 0x1E/255.0, alpha: 1)

    // MARK: - Init

    init(dialog: Dialog) {
        self.dialogKey = dialog.opponentKey
        super.init(frame: .zero)
        setupViews()
        configure(with: dialog)
    }

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

    // MARK: - Setup

    private func setupViews() {
        // Background
        backgroundGlass.backgroundColor = UIColor { traits in
            traits.userInterfaceStyle == .dark
                ? UIColor.white.withAlphaComponent(0.1)
                : UIColor.black.withAlphaComponent(0.06)
        }
        backgroundGlass.layer.cornerRadius = Layout.cornerRadius
        backgroundGlass.clipsToBounds = true
        addSubview(backgroundGlass)

        // Avatar background
        avatarBackgroundView.clipsToBounds = true
        avatarBackgroundView.layer.cornerRadius = Layout.avatarSize / 2
        addSubview(avatarBackgroundView)

        // Avatar initials
        avatarInitialsLabel.textAlignment = .center
        avatarInitialsLabel.font = .systemFont(ofSize: Layout.avatarSize * 0.38, weight: .bold)
        addSubview(avatarInitialsLabel)

        // Avatar image
        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.clipsToBounds = true
        avatarImageView.layer.cornerRadius = Layout.avatarSize / 2
        avatarImageView.isHidden = true
        addSubview(avatarImageView)

        // Name
        nameLabel.font = .systemFont(ofSize: 14, weight: .regular)
        nameLabel.textColor = UIColor(RosettaColors.Adaptive.text)
        nameLabel.lineBreakMode = .byTruncatingTail
        addSubview(nameLabel)

        // Remove button
        let xConfig = UIImage.SymbolConfiguration(pointSize: 10, weight: .bold)
        removeButton.setImage(UIImage(systemName: "xmark", withConfiguration: xConfig), for: .normal)
        removeButton.tintColor = UIColor(RosettaColors.Adaptive.textSecondary)
        removeButton.addTarget(self, action: #selector(removeTapped), for: .touchUpInside)
        addSubview(removeButton)
    }

    // MARK: - Configure

    private func configure(with dialog: Dialog) {
        // Name — use first name only for compact display
        let firstName = dialog.opponentTitle.components(separatedBy: " ").first ?? dialog.opponentTitle
        nameLabel.text = firstName

        // Avatar
        let colorPair = RosettaColors.avatarColors[dialog.avatarColorIndex % RosettaColors.avatarColors.count]
        let image = AvatarRepository.shared.loadAvatar(publicKey: dialog.opponentKey)

        avatarBackgroundView.isHidden = false
        avatarImageView.isHidden = true
        avatarInitialsLabel.isHidden = true

        if let image {
            avatarImageView.image = image
            avatarImageView.isHidden = false
            avatarBackgroundView.isHidden = true
        } else {
            let tintUIColor = UIColor(colorPair.tint)
            let textUIColor = UIColor(colorPair.text)
            avatarBackgroundView.backgroundColor = UIColor { traits in
                let dark = traits.userInterfaceStyle == .dark
                let base: UIColor = dark ? TokenChipView.mantineDarkBody : .white
                return base.blended(with: tintUIColor, alpha: dark ? 0.15 : 0.10)
            }
            avatarInitialsLabel.isHidden = false
            avatarInitialsLabel.text = dialog.initials
            avatarInitialsLabel.textColor = UIColor { traits in
                traits.userInterfaceStyle == .dark ? textUIColor : tintUIColor
            }
        }

        // Calculate size
        let textWidth = nameLabel.sizeThatFits(CGSize(width: 200, height: Layout.height)).width
        let totalWidth = min(
            Layout.maxWidth,
            Layout.avatarInset + Layout.avatarSize + 4 + textWidth + 4 + Layout.removeSize + Layout.trailingPadding
        )
        frame.size = CGSize(width: totalWidth, height: Layout.height)

        setNeedsLayout()
    }

    // MARK: - Layout

    override func layoutSubviews() {
        super.layoutSubviews()

        backgroundGlass.frame = bounds

        let avatarY = (bounds.height - Layout.avatarSize) / 2
        let avatarFrame = CGRect(
            x: Layout.avatarInset,
            y: avatarY,
            width: Layout.avatarSize,
            height: Layout.avatarSize
        )
        avatarBackgroundView.frame = avatarFrame
        avatarInitialsLabel.frame = avatarFrame
        avatarImageView.frame = avatarFrame

        let textX = Layout.avatarInset + Layout.avatarSize + 4
        let removeX = bounds.width - Layout.removeSize - Layout.trailingPadding
        let textWidth = removeX - textX - 2
        nameLabel.frame = CGRect(x: textX, y: 0, width: max(0, textWidth), height: bounds.height)

        let removeY = (bounds.height - Layout.removeSize) / 2
        removeButton.frame = CGRect(x: removeX, y: removeY, width: Layout.removeSize, height: Layout.removeSize)
    }

    override var intrinsicContentSize: CGSize {
        frame.size
    }

    // MARK: - Actions

    @objc private func removeTapped() {
        onRemove?(dialogKey)
    }
}
