import UIKit
import SwiftUI

/// Reusable contact row cell for ComposeViewController and GroupContactPickerViewController.
/// Manual frame layout for scroll performance (same approach as ChatListCell).
final class ComposeContactCell: UICollectionViewCell {

    static let reuseID = "ComposeContactCell"

    // MARK: - Layout Constants

    private enum Layout {
        static let avatarDiameter: CGFloat = 40
        static let avatarLeading: CGFloat = 16
        static let textLeading: CGFloat = 12
        static let textTrailing: CGFloat = 48
        static let cellHeight: CGFloat = 56
        static let checkSize: CGFloat = 22
        static let checkTrailing: CGFloat = 16
        static let separatorLeading: CGFloat = 68 // avatarLeading + diameter + textLeading
    }

    // MARK: - Subviews

    let avatarBackgroundView = UIView()
    let avatarInitialsLabel = UILabel()
    let avatarImageView = UIImageView()
    let nameLabel = UILabel()
    let usernameLabel = UILabel()
    let checkmarkView = UIImageView()
    let separatorView = UIView()

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

    // MARK: - Init

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

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

    // MARK: - Setup

    private func setupViews() {
        backgroundColor = .clear
        contentView.backgroundColor = .clear

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

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

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

        // Name label
        nameLabel.font = .systemFont(ofSize: 17, weight: .regular)
        nameLabel.textColor = UIColor(RosettaColors.Adaptive.text)
        contentView.addSubview(nameLabel)

        // Username label
        usernameLabel.font = .systemFont(ofSize: 14, weight: .regular)
        usernameLabel.textColor = UIColor(RosettaColors.Adaptive.textSecondary)
        contentView.addSubview(usernameLabel)

        // Checkmark
        checkmarkView.contentMode = .scaleAspectFit
        checkmarkView.isHidden = true
        contentView.addSubview(checkmarkView)

        // Separator
        separatorView.backgroundColor = UIColor { traits in
            traits.userInterfaceStyle == .dark
                ? UIColor.white.withAlphaComponent(0.08)
                : UIColor.black.withAlphaComponent(0.08)
        }
        contentView.addSubview(separatorView)
    }

    // MARK: - Layout

    override func layoutSubviews() {
        super.layoutSubviews()
        let bounds = contentView.bounds

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

        let textX = Layout.avatarLeading + Layout.avatarDiameter + Layout.textLeading
        let rightEdge = checkmarkView.isHidden
            ? bounds.width - 16
            : bounds.width - Layout.checkTrailing - Layout.checkSize - 8

        let hasUsername = !(usernameLabel.text?.isEmpty ?? true)

        if hasUsername {
            let nameY = bounds.height / 2 - 20
            nameLabel.frame = CGRect(x: textX, y: nameY, width: rightEdge - textX, height: 22)
            usernameLabel.frame = CGRect(x: textX, y: nameY + 22, width: rightEdge - textX, height: 18)
        } else {
            nameLabel.frame = CGRect(x: textX, y: (bounds.height - 22) / 2, width: rightEdge - textX, height: 22)
            usernameLabel.frame = .zero
        }

        let checkY = (bounds.height - Layout.checkSize) / 2
        checkmarkView.frame = CGRect(
            x: bounds.width - Layout.checkTrailing - Layout.checkSize,
            y: checkY,
            width: Layout.checkSize,
            height: Layout.checkSize
        )

        separatorView.frame = CGRect(
            x: Layout.separatorLeading,
            y: bounds.height - 0.5,
            width: bounds.width - Layout.separatorLeading,
            height: 0.5
        )
    }

    // MARK: - Configure

    func configure(with dialog: Dialog, isSelected: Bool, showCheckmark: Bool) {
        nameLabel.text = dialog.opponentTitle
        let username = dialog.opponentUsername
        usernameLabel.text = username.isEmpty ? nil : "@\(username)"

        // Avatar
        configureAvatar(dialog: dialog)

        // Checkmark
        checkmarkView.isHidden = !showCheckmark
        if showCheckmark {
            updateCheckmark(isSelected: isSelected)
        }

        setNeedsLayout()
    }

    func updateCheckmark(isSelected: Bool) {
        let config = UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)
        if isSelected {
            checkmarkView.image = UIImage(systemName: "checkmark.circle.fill", withConfiguration: config)
            checkmarkView.tintColor = UIColor(RosettaColors.figmaBlue)
        } else {
            checkmarkView.image = UIImage(systemName: "circle", withConfiguration: config)
            checkmarkView.tintColor = UIColor { traits in
                traits.userInterfaceStyle == .dark
                    ? UIColor.white.withAlphaComponent(0.3)
                    : UIColor.black.withAlphaComponent(0.2)
            }
        }
    }

    // MARK: - Avatar (ChatListCell parity)

    private func configureAvatar(dialog: Dialog) {
        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 ? ComposeContactCell.mantineDarkBody : .white
                return base.blended(with: tintUIColor, alpha: dark ? 0.15 : 0.10)
            }
            avatarInitialsLabel.isHidden = false
            avatarInitialsLabel.text = dialog.initials
            avatarInitialsLabel.font = .systemFont(
                ofSize: Layout.avatarDiameter * 0.38, weight: .bold
            ).rounded()
            avatarInitialsLabel.textColor = UIColor { traits in
                traits.userInterfaceStyle == .dark ? textUIColor : tintUIColor
            }
        }
    }

    // MARK: - Highlight

    override var isHighlighted: Bool {
        didSet {
            UIView.animate(withDuration: 0.15) {
                self.contentView.alpha = self.isHighlighted ? 0.6 : 1.0
            }
        }
    }
}

// MARK: - UIFont+Rounded

private extension UIFont {
    func rounded() -> UIFont {
        guard let descriptor = fontDescriptor.withDesign(.rounded) else { return self }
        return UIFont(descriptor: descriptor, size: pointSize)
    }
}

