import UIKit

/// Telegram-exact context menu card.
///
/// Source: ContextActionsContainerNode.swift + DefaultDarkPresentationTheme.swift
/// - Background: .systemMaterialDark blur + UIColor(0x252525, alpha: 0.78) tint
/// - Items: 17pt font, icon LEFT + title RIGHT
/// - Corner radius: 14pt continuous
/// - Separator: screenPixel, white 15% alpha, full width
/// - Destructive: 0xeb5545
final class TelegramContextMenuCardView: UIView {

    // MARK: - Constants

    private static let itemHeight: CGFloat = 44
    private static let cornerRadius: CGFloat = 14
    private static let hPad: CGFloat = 16
    private static let iconSize: CGFloat = 24
    private static let screenPixel = 1.0 / max(UIScreen.main.scale, 1)

    // MARK: - Colors (adaptive light/dark)

    private static let tintBg = UIColor { traits in
        traits.userInterfaceStyle == .dark
            ? UIColor(red: 0x25/255, green: 0x25/255, blue: 0x25/255, alpha: 0.78)
            : UIColor(red: 0xF5/255, green: 0xF5/255, blue: 0xF7/255, alpha: 0.78)
    }
    private static let textColor = UIColor.label
    private static let destructiveColor = UIColor(red: 0xEB/255, green: 0x55/255, blue: 0x45/255, alpha: 1)
    private static let separatorColor = UIColor { traits in
        traits.userInterfaceStyle == .dark
            ? UIColor(white: 1, alpha: 0.15)
            : UIColor(white: 0, alpha: 0.1)
    }
    private static let highlightColor = UIColor { traits in
        traits.userInterfaceStyle == .dark
            ? UIColor(white: 1, alpha: 0.15)
            : UIColor(white: 0, alpha: 0.08)
    }

    // MARK: - Public

    let itemCount: Int
    var onItemSelected: (() -> Void)?

    // MARK: - Views

    private let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .systemMaterial))
    private let tintView = UIView()
    private let items: [TelegramContextMenuItem]

    // Row subviews stored for layout
    private var titleLabels: [UILabel] = []
    private var iconViews: [UIImageView] = []
    private var highlightViews: [UIView] = []
    private var separators: [UIView] = []

    // MARK: - Init

    init(items: [TelegramContextMenuItem]) {
        self.items = items
        self.itemCount = items.count
        super.init(frame: .zero)
        setup()
    }

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

    // MARK: - Setup

    private func setup() {
        clipsToBounds = true
        layer.cornerRadius = Self.cornerRadius
        layer.cornerCurve = .continuous

        blurView.clipsToBounds = true
        addSubview(blurView)

        tintView.backgroundColor = Self.tintBg
        tintView.isUserInteractionEnabled = false
        addSubview(tintView)

        for (i, item) in items.enumerated() {
            let color = item.isDestructive ? Self.destructiveColor : Self.textColor

            // Highlight
            let hl = UIView()
            hl.backgroundColor = Self.highlightColor
            hl.alpha = 0
            addSubview(hl)
            highlightViews.append(hl)

            // Title
            let label = UILabel()
            label.text = item.title
            label.font = .systemFont(ofSize: 17, weight: .regular)
            label.textColor = color
            addSubview(label)
            titleLabels.append(label)

            // Icon
            let iv = UIImageView()
            iv.image = UIImage(systemName: item.iconName)?
                .withConfiguration(UIImage.SymbolConfiguration(pointSize: Self.iconSize, weight: .medium))
            iv.tintColor = color
            iv.contentMode = .center
            addSubview(iv)
            iconViews.append(iv)

            // Separator
            if i < items.count - 1 {
                let sep = UIView()
                sep.backgroundColor = Self.separatorColor
                addSubview(sep)
                separators.append(sep)
            }

            // Row gesture
            let rowView = UIView()
            rowView.backgroundColor = .clear
            rowView.tag = i
            let press = UILongPressGestureRecognizer(target: self, action: #selector(rowPress(_:)))
            press.minimumPressDuration = 0
            press.cancelsTouchesInView = false
            rowView.addGestureRecognizer(press)
            addSubview(rowView)
        }
    }

    // MARK: - Layout

    override func layoutSubviews() {
        super.layoutSubviews()
        let w = bounds.width
        blurView.frame = bounds
        tintView.frame = bounds

        for i in 0..<items.count {
            let y = CGFloat(i) * Self.itemHeight
            let rowRect = CGRect(x: 0, y: y, width: w, height: Self.itemHeight)

            // Highlight fills row
            highlightViews[i].frame = rowRect

            // Icon left (Telegram: icon on LEFT side)
            let iconX = Self.hPad
            iconViews[i].frame = CGRect(x: iconX, y: y, width: Self.iconSize, height: Self.itemHeight)

            // Title right of icon (Telegram: text follows icon)
            let titleX = Self.hPad + Self.iconSize + 12
            let titleW = w - titleX - Self.hPad
            titleLabels[i].frame = CGRect(x: titleX, y: y, width: titleW, height: Self.itemHeight)

            // Gesture receiver (topmost, transparent)
            if let rv = subviews.first(where: { $0.tag == i && $0.gestureRecognizers?.isEmpty == false }) {
                rv.frame = rowRect
            }
        }

        // Separators
        for (i, sep) in separators.enumerated() {
            let y = CGFloat(i + 1) * Self.itemHeight
            sep.frame = CGRect(x: 0, y: y, width: w, height: Self.screenPixel)
        }
    }

    // MARK: - Interaction

    @objc private func rowPress(_ g: UILongPressGestureRecognizer) {
        let i = g.view?.tag ?? -1
        guard i >= 0, i < items.count else { return }

        switch g.state {
        case .began:
            UIView.animate(withDuration: 0.08) { self.highlightViews[i].alpha = 1 }
        case .ended:
            let loc = g.location(in: g.view)
            UIView.animate(withDuration: 0.12) { self.highlightViews[i].alpha = 0 }
            if g.view?.bounds.contains(loc) == true {
                let handler = items[i].handler
                onItemSelected?()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { handler() }
            }
        case .cancelled, .failed:
            UIView.animate(withDuration: 0.12) { self.highlightViews[i].alpha = 0 }
        default: break
        }
    }
}
