import SwiftUI
import UIKit

// MARK: - Data Model

struct MentionCandidate {
    let username: String
    let title: String
    let publicKey: String
    let isAll: Bool

    static func allMembers() -> MentionCandidate {
        MentionCandidate(username: "all", title: "All Members", publicKey: "", isAll: true)
    }
}

// MARK: - Delegate

@MainActor
protocol MentionAutocompleteDelegate: AnyObject {
    func mentionAutocomplete(_ view: MentionAutocompleteView, didSelect candidate: MentionCandidate)
}

// MARK: - MentionAutocompleteView

/// UIKit mention autocomplete panel — Telegram-exact dimensions.
/// Appears above the composer when user types "@" in a group chat.
///
/// Reference: MentionChatInputContextPanelNode.swift + MentionChatInputPanelItem.swift
/// Row: 42pt | Avatar: 30x30 at x=12 | Text at x=55 | Font: 14pt medium/regular
/// Background: UIVisualEffectView (.ultraThinMaterial), corner radius 20pt
final class MentionAutocompleteView: UIView, UITableViewDataSource, UITableViewDelegate {

    weak var mentionDelegate: MentionAutocompleteDelegate?
    /// Corner radius matching inputContainer — passed from ComposerView.
    var panelCornerRadius: CGFloat = 21

    private let glassBackground = TelegramGlassUIView()
    private let tableView = UITableView(frame: .zero, style: .plain)
    private var candidates: [MentionCandidate] = []

    // Telegram-exact constants
    private let rowHeight: CGFloat = 42

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

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

    private func setupViews() {
        // Glass background (TelegramGlassUIView — same as input container)
        glassBackground.isUserInteractionEnabled = false
        addSubview(glassBackground)

        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.register(MentionCell.self, forCellReuseIdentifier: MentionCell.reuseID)
        tableView.rowHeight = rowHeight
        addSubview(tableView)

        clipsToBounds = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        glassBackground.frame = bounds
        tableView.frame = bounds

        // Top-only rounding via maskedCorners (not layer.mask — masks break glass backdrop).
        // Matches inputContainer radius so panel + input look like ONE unified glass element.
        layer.cornerRadius = panelCornerRadius
        layer.cornerCurve = .continuous
        layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

        glassBackground.fixedCornerRadius = panelCornerRadius
        glassBackground.applyCornerRadius()
        glassBackground.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    }

    // MARK: - Public API

    func update(candidates: [MentionCandidate]) {
        self.candidates = candidates
        tableView.reloadData()
    }

    var preferredHeight: CGFloat {
        min(CGFloat(candidates.count) * rowHeight, 5 * rowHeight)
    }

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        candidates.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MentionCell.reuseID, for: indexPath) as! MentionCell
        let candidate = candidates[indexPath.row]
        let isLast = indexPath.row == candidates.count - 1
        cell.configure(candidate: candidate, showSeparator: !isLast)
        return cell
    }

    // MARK: - UITableViewDelegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let candidate = candidates[indexPath.row]
        mentionDelegate?.mentionAutocomplete(self, didSelect: candidate)
    }
}

// MARK: - MentionCell

final class MentionCell: UITableViewCell {

    static let reuseID = "MentionCell"

    // Telegram-exact constants
    private let avatarSize: CGFloat = 30
    private let avatarLeftInset: CGFloat = 12
    private let textLeftOffset: CGFloat = 55
    private let rightPadding: CGFloat = 10

    private let avatarCircle = UIView()
    private let avatarImageView = UIImageView()
    private let avatarInitialLabel = UILabel()
    private let allLabel = UILabel()
    private let nameLabel = UILabel()
    private let usernameLabel = UILabel()
    private let separatorLine = UIView()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        selectionStyle = .none

        avatarCircle.clipsToBounds = true
        contentView.addSubview(avatarCircle)

        avatarImageView.contentMode = .scaleAspectFill
        avatarImageView.clipsToBounds = true
        avatarCircle.addSubview(avatarImageView)

        avatarInitialLabel.textAlignment = .center
        avatarInitialLabel.font = UIFont.systemFont(ofSize: 12, weight: .bold).rounded()
        avatarCircle.addSubview(avatarInitialLabel)

        allLabel.text = "@"
        allLabel.textAlignment = .center
        allLabel.textColor = .white
        allLabel.font = .systemFont(ofSize: 16, weight: .bold)
        allLabel.isHidden = true
        avatarCircle.addSubview(allLabel)

        nameLabel.font = .systemFont(ofSize: 14, weight: .medium)
        nameLabel.textColor = .white
        contentView.addSubview(nameLabel)

        usernameLabel.font = .systemFont(ofSize: 14, weight: .regular)
        usernameLabel.textColor = UIColor(white: 1, alpha: 0.55)
        contentView.addSubview(usernameLabel)

        separatorLine.backgroundColor = UIColor.white.withAlphaComponent(0.08)
        contentView.addSubview(separatorLine)
    }

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

    func configure(candidate: MentionCandidate, showSeparator: Bool) {
        let h: CGFloat = 42
        let w = UIScreen.main.bounds.width

        // Avatar
        let avatarY = (h - avatarSize) / 2
        avatarCircle.frame = CGRect(x: avatarLeftInset, y: avatarY, width: avatarSize, height: avatarSize)
        avatarCircle.layer.cornerRadius = avatarSize / 2
        avatarImageView.frame = avatarCircle.bounds
        avatarInitialLabel.frame = avatarCircle.bounds
        allLabel.frame = avatarCircle.bounds

        if candidate.isAll {
            avatarCircle.backgroundColor = UIColor(RosettaColors.primaryBlue)
            avatarImageView.isHidden = true
            avatarInitialLabel.isHidden = true
            allLabel.isHidden = false
        } else {
            allLabel.isHidden = true
            let avatar = AvatarRepository.shared.loadAvatar(publicKey: candidate.publicKey)
            if let avatar {
                avatarImageView.image = avatar
                avatarImageView.isHidden = false
                avatarInitialLabel.isHidden = true
                avatarCircle.backgroundColor = .clear
            } else {
                avatarImageView.image = nil
                avatarImageView.isHidden = true
                avatarInitialLabel.isHidden = false
                avatarInitialLabel.text = RosettaColors.initials(name: candidate.title, publicKey: candidate.publicKey)
                let colorIndex = RosettaColors.avatarColorIndex(for: candidate.title, publicKey: candidate.publicKey)
                // Mantine "light" variant: dark base + tint at 15% opacity (dark mode)
                let isDark = traitCollection.userInterfaceStyle == .dark
                let tintColor = RosettaColors.avatarColor(for: colorIndex)
                let baseColor = isDark ? UIColor(red: 0.102, green: 0.106, blue: 0.118, alpha: 1) : .white // #1A1B1E
                let overlayAlpha: CGFloat = isDark ? 0.15 : 0.10
                avatarCircle.backgroundColor = baseColor.blended(with: tintColor, alpha: overlayAlpha)
                // Text: shade-3 (text) in dark, shade-6 (tint) in light
                let textColor = isDark
                    ? RosettaColors.avatarTextColor(for: colorIndex)
                    : RosettaColors.avatarColor(for: colorIndex)
                avatarInitialLabel.textColor = textColor
            }
        }

        // Text
        nameLabel.text = candidate.title
        usernameLabel.text = " @\(candidate.username)"

        let nameSize = nameLabel.sizeThatFits(CGSize(width: w, height: h))
        let maxTextW = w - textLeftOffset - rightPadding
        let textY = (h - nameSize.height) / 2
        let nameW = min(nameSize.width, maxTextW * 0.6)
        nameLabel.frame = CGRect(x: textLeftOffset, y: textY, width: nameW, height: nameSize.height)

        let usernameSize = usernameLabel.sizeThatFits(CGSize(width: w, height: h))
        let remainingW = maxTextW - nameW
        usernameLabel.frame = CGRect(
            x: textLeftOffset + nameW, y: textY,
            width: min(usernameSize.width, remainingW), height: usernameSize.height
        )

        // Separator (1px, Telegram: itemPlainSeparatorColor)
        separatorLine.isHidden = !showSeparator
        let sepH: CGFloat = 1.0 / UIScreen.main.scale
        separatorLine.frame = CGRect(x: textLeftOffset, y: h - sepH, width: w - textLeftOffset, height: sepH)
    }

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)
        UIView.animate(withDuration: highlighted ? 0 : 0.4) {
            self.contentView.backgroundColor = highlighted
                ? UIColor.white.withAlphaComponent(0.08)
                : .clear
        }
    }
}

// MARK: - Helpers

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

// UIColor.blended(with:alpha:) is defined in ChatListCell.swift
