import UIKit
import SwiftUI

/// UIKit cell for a group member row (Telegram parity).
/// Avatar 40pt, name, status (online/username/last seen), admin badge.
final class GroupMemberCell: UIView {

    private let avatarContainer = UIView()
    private var avatarHosting: UIHostingController<AvatarView>?
    private let nameLabel = UILabel()
    private let statusLabel = UILabel()
    private var verifiedHosting: UIHostingController<VerifiedBadge>?
    private var adminHosting: UIHostingController<VerifiedBadge>?

    private let accentBlue = UIColor(red: 0x3E/255, green: 0x88/255, blue: 0xF7/255, alpha: 1)
    private let textColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }
    private let textSecondary = UIColor { $0.userInterfaceStyle == .dark
        ? UIColor(red: 0x8D/255, green: 0x8E/255, blue: 0x93/255, alpha: 1)
        : UIColor(red: 0x8E/255, green: 0x8E/255, blue: 0x93/255, alpha: 1)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    private func setupViews() {
        addSubview(avatarContainer)

        nameLabel.font = .systemFont(ofSize: 17)
        nameLabel.textColor = textColor
        nameLabel.lineBreakMode = .byTruncatingTail
        addSubview(nameLabel)

        statusLabel.font = .systemFont(ofSize: 14)
        statusLabel.textColor = textSecondary
        statusLabel.lineBreakMode = .byTruncatingTail
        addSubview(statusLabel)
    }

    func configure(member: GroupMember) {
        nameLabel.text = member.title

        if member.isOnline {
            statusLabel.text = "online"
            statusLabel.textColor = accentBlue
        } else if !member.username.isEmpty {
            statusLabel.text = "@\(member.username)"
            statusLabel.textColor = textSecondary
        } else {
            statusLabel.text = "last seen recently"
            statusLabel.textColor = textSecondary
        }

        // Avatar
        avatarHosting?.view.removeFromSuperview()
        avatarHosting?.removeFromParent()

        let initials = RosettaColors.initials(name: member.title, publicKey: member.id)
        let colorIdx = RosettaColors.avatarColorIndex(for: member.title, publicKey: member.id)
        let avatar = AvatarRepository.shared.loadAvatar(publicKey: member.id)
        let sectionFill = Color(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)
        })

        let avatarView = AvatarView(
            initials: initials,
            colorIndex: colorIdx,
            size: 40,
            isOnline: member.isOnline,
            isSavedMessages: false,
            image: avatar,
            onlineBorderColor: sectionFill
        )
        let hosting = UIHostingController(rootView: avatarView)
        hosting.view.backgroundColor = .clear
        hosting.view.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        avatarContainer.addSubview(hosting.view)
        avatarHosting = hosting

        // Verified badge
        verifiedHosting?.view.removeFromSuperview()
        verifiedHosting = nil
        if member.verified > 0 {
            let badge = VerifiedBadge(verified: member.verified, size: 14)
            let vc = UIHostingController(rootView: badge)
            vc.view.backgroundColor = .clear
            addSubview(vc.view)
            verifiedHosting = vc
        }

        // Admin badge
        adminHosting?.view.removeFromSuperview()
        adminHosting = nil
        if member.isAdmin {
            let badge = VerifiedBadge(verified: 3, size: 20)
            let vc = UIHostingController(rootView: badge)
            vc.view.backgroundColor = .clear
            addSubview(vc.view)
            adminHosting = vc
        }

        setNeedsLayout()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let w = bounds.width
        let h = bounds.height

        avatarContainer.frame = CGRect(x: 0, y: (h - 40) / 2, width: 40, height: 40)

        let nameX: CGFloat = 49
        let nameSize = nameLabel.sizeThatFits(CGSize(width: w - nameX - 40, height: 22))
        nameLabel.frame = CGRect(x: nameX, y: 10, width: min(nameSize.width, w - nameX - 40), height: 22)

        if let badgeView = verifiedHosting?.view {
            badgeView.frame = CGRect(x: nameLabel.frame.maxX + 4, y: 14, width: 14, height: 14)
        }

        statusLabel.frame = CGRect(x: nameX, y: 34, width: w - nameX - 40, height: 18)

        if let adminView = adminHosting?.view {
            adminView.frame = CGRect(x: w - 20, y: (h - 20) / 2, width: 20, height: 20)
        }
    }
}
