import UIKit
import SwiftUI

// MARK: - Glass Back Button (Chevron)

/// Circular glass button with Telegram SVG back chevron.
/// Reuses exact `TelegramIconPath.backChevron` path data.
final class ComposeGlassBackButton: UIControl {

    private let glassView = TelegramGlassUIView(frame: .zero)
    private let chevronLayer = CAShapeLayer()
    private static let viewBox = CGSize(width: 10.7, height: 19.63)

    override init(frame: CGRect) {
        super.init(frame: frame)
        glassView.isUserInteractionEnabled = false
        addSubview(glassView)
        chevronLayer.fillColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }.cgColor
        layer.addSublayer(chevronLayer)
    }

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

    override var intrinsicContentSize: CGSize { CGSize(width: 44, height: 44) }

    override func layoutSubviews() {
        super.layoutSubviews()
        glassView.frame = bounds
        glassView.fixedCornerRadius = bounds.height * 0.5
        glassView.updateGlass()
        updateChevronPath()
    }

    private func updateChevronPath() {
        guard bounds.width > 0 else { return }
        let iconSize = CGSize(width: 11, height: 20)
        let origin = CGPoint(
            x: (bounds.width - iconSize.width) / 2,
            y: (bounds.height - iconSize.height) / 2
        )
        var parser = SVGPathParser(pathData: TelegramIconPath.backChevron)
        let rawPath = parser.parse()
        let vb = Self.viewBox
        var transform = CGAffineTransform(translationX: origin.x, y: origin.y)
            .scaledBy(x: iconSize.width / vb.width, y: iconSize.height / vb.height)
        let scaledPath = rawPath.copy(using: &transform)
        chevronLayer.path = scaledPath
        chevronLayer.frame = bounds
    }

    override var isHighlighted: Bool {
        didSet { alpha = isHighlighted ? 0.6 : 1.0 }
    }

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
            chevronLayer.fillColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }.cgColor
        }
    }
}

// MARK: - Glass Close Button (X)

/// Circular glass button with X icon for dismissing modal-like screens.
final class ComposeGlassCloseButton: UIControl {

    private let glassView = TelegramGlassUIView(frame: .zero)
    private let xLayer = CAShapeLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        glassView.isUserInteractionEnabled = false
        addSubview(glassView)

        xLayer.strokeColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }.cgColor
        xLayer.fillColor = UIColor.clear.cgColor
        xLayer.lineWidth = 2.0
        xLayer.lineCap = .round
        layer.addSublayer(xLayer)
    }

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

    override var intrinsicContentSize: CGSize { CGSize(width: 44, height: 44) }

    override func layoutSubviews() {
        super.layoutSubviews()
        glassView.frame = bounds
        glassView.fixedCornerRadius = bounds.height * 0.5
        glassView.updateGlass()
        updateXPath()
    }

    private func updateXPath() {
        guard bounds.width > 0 else { return }
        // Telegram exact: two diagonal lines in 40×40 canvas, inset 12pt (0.3×40)
        // Source: SearchBarPlaceholderNode.swift — 2pt lineWidth, round cap
        let canvasSize = min(bounds.width, bounds.height)
        let inset = canvasSize * 0.3
        let offsetX = (bounds.width - canvasSize) / 2
        let offsetY = (bounds.height - canvasSize) / 2

        let path = UIBezierPath()
        path.move(to: CGPoint(x: offsetX + inset, y: offsetY + inset))
        path.addLine(to: CGPoint(x: offsetX + canvasSize - inset, y: offsetY + canvasSize - inset))
        path.move(to: CGPoint(x: offsetX + canvasSize - inset, y: offsetY + inset))
        path.addLine(to: CGPoint(x: offsetX + inset, y: offsetY + canvasSize - inset))

        xLayer.path = path.cgPath
        xLayer.frame = bounds
    }

    override var isHighlighted: Bool {
        didSet { alpha = isHighlighted ? 0.6 : 1.0 }
    }

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
            xLayer.strokeColor = UIColor { $0.userInterfaceStyle == .dark ? .white : .black }.cgColor
        }
    }
}

// MARK: - Glass Action Button (text capsule)

/// Glass capsule button with text label (e.g. "Next", "Create").
final class ComposeGlassActionButton: UIControl {

    private let glassView = TelegramGlassUIView(frame: .zero)
    private let titleLabel = UILabel()

    var title: String? {
        get { titleLabel.text }
        set {
            titleLabel.text = newValue
            invalidateIntrinsicContentSize()
        }
    }

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

        glassView.isUserInteractionEnabled = false
        addSubview(glassView)

        titleLabel.font = .systemFont(ofSize: 17, weight: .semibold)
        titleLabel.textColor = UIColor(RosettaColors.Adaptive.text)
        titleLabel.textAlignment = .center
        addSubview(titleLabel)
    }

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

    override var intrinsicContentSize: CGSize {
        let textWidth = titleLabel.intrinsicContentSize.width
        return CGSize(width: textWidth + 28, height: 44)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        glassView.frame = bounds
        glassView.fixedCornerRadius = bounds.height * 0.5
        glassView.updateGlass()
        titleLabel.frame = bounds
    }

    override var isEnabled: Bool {
        didSet {
            titleLabel.textColor = isEnabled
                ? UIColor(RosettaColors.Adaptive.text)
                : UIColor(RosettaColors.Adaptive.textSecondary)
            alpha = isEnabled ? 1.0 : 0.5
        }
    }

    override var isHighlighted: Bool {
        didSet { alpha = isHighlighted ? 0.6 : (isEnabled ? 1.0 : 0.5) }
    }
}

// MARK: - Glass Search Bar

/// Solid capsule search bar matching Telegram search bar (SearchBarNode.swift).
/// Inactive: centered icon + placeholder (Auto Layout centerX/Y).
/// Active: left-aligned icon + textField + inline clear button.
/// Uses Auto Layout internally; parent positions this view via manual `.frame`.
final class ComposeGlassSearchBar: UIView, UITextFieldDelegate {

    var onTextChanged: ((String) -> Void)?
    var placeholder: String = "Search" {
        didSet {
            placeholderLabel.text = placeholder
            updatePlaceholderAttributes()
        }
    }

    private(set) var isActive = false

    // Capsule background
    private let capsuleView = UIView()

    // Inactive: centered placeholder stack
    private let placeholderStack = UIStackView()
    private let placeholderIcon = UIImageView(image: UIImage(systemName: "magnifyingglass"))
    private let placeholderLabel = UILabel()

    // Active: left-aligned active stack
    private let activeStack = UIStackView()
    private let activeIcon = UIImageView(image: UIImage(systemName: "magnifyingglass"))
    let textField = UITextField()
    private let inlineClearButton = UIButton(type: .system)

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        clipsToBounds = false
        setupUI()
        applyColors()
        updateVisualState(animated: false)
    }

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

    // MARK: - Setup (Auto Layout internal, matches ChatListSearchHeaderView)

    private func setupUI() {
        // Capsule fills parent bounds via autoresizingMask (parent sets .frame)
        capsuleView.clipsToBounds = true
        capsuleView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(capsuleView)

        // Inactive: centered placeholder stack (Telegram: spacing 4pt)
        placeholderStack.translatesAutoresizingMaskIntoConstraints = false
        placeholderStack.axis = .horizontal
        placeholderStack.alignment = .center
        placeholderStack.spacing = 4
        placeholderIcon.contentMode = .scaleAspectFit
        placeholderIcon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)
        placeholderLabel.text = placeholder
        placeholderLabel.font = .systemFont(ofSize: 17)
        placeholderStack.addArrangedSubview(placeholderIcon)
        placeholderStack.addArrangedSubview(placeholderLabel)
        capsuleView.addSubview(placeholderStack)

        // Active: left-aligned stack (Telegram: spacing 2pt, leading 8pt)
        activeStack.translatesAutoresizingMaskIntoConstraints = false
        activeStack.axis = .horizontal
        activeStack.alignment = .center
        activeStack.spacing = 2
        activeIcon.contentMode = .scaleAspectFit
        activeIcon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 15, weight: .medium)

        textField.translatesAutoresizingMaskIntoConstraints = false
        textField.font = .systemFont(ofSize: 17)
        textField.autocapitalizationType = .none
        textField.autocorrectionType = .no
        textField.returnKeyType = .search
        textField.clearButtonMode = .never
        textField.delegate = self
        textField.addTarget(self, action: #selector(handleTextChanged), for: .editingChanged)

        inlineClearButton.translatesAutoresizingMaskIntoConstraints = false
        inlineClearButton.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal)
        inlineClearButton.addTarget(self, action: #selector(handleInlineClearTapped), for: .touchUpInside)

        activeStack.addArrangedSubview(activeIcon)
        activeStack.addArrangedSubview(textField)
        activeStack.addArrangedSubview(inlineClearButton)
        capsuleView.addSubview(activeStack)

        // Tap to activate
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleCapsuleTapped))
        capsuleView.addGestureRecognizer(tap)

        // Constraints (matches ChatListSearchHeaderView lines 1252-1264)
        NSLayoutConstraint.activate([
            // Placeholder: centered in capsule
            placeholderStack.centerXAnchor.constraint(equalTo: capsuleView.centerXAnchor),
            placeholderStack.centerYAnchor.constraint(equalTo: capsuleView.centerYAnchor),

            // Active stack: leading 8pt, trailing 10pt, fill height
            activeStack.leadingAnchor.constraint(equalTo: capsuleView.leadingAnchor, constant: 8),
            activeStack.trailingAnchor.constraint(equalTo: capsuleView.trailingAnchor, constant: -10),
            activeStack.topAnchor.constraint(equalTo: capsuleView.topAnchor),
            activeStack.bottomAnchor.constraint(equalTo: capsuleView.bottomAnchor),

            // Fixed widths to prevent stretching
            activeIcon.widthAnchor.constraint(equalToConstant: 20),
            inlineClearButton.widthAnchor.constraint(equalToConstant: 24),
            inlineClearButton.heightAnchor.constraint(equalToConstant: 24),
        ])
    }

    private func applyColors() {
        let isDark = traitCollection.userInterfaceStyle == .dark
        let placeholderColor = isDark
            ? UIColor(red: 0x8f/255.0, green: 0x8f/255.0, blue: 0x8f/255.0, alpha: 1.0)
            : UIColor(red: 0x8e/255.0, green: 0x8e/255.0, blue: 0x93/255.0, alpha: 1.0)
        let solidFill = isDark
            ? UIColor(red: 0x27/255.0, green: 0x27/255.0, blue: 0x28/255.0, alpha: 1.0)
            : UIColor(red: 0xE9/255.0, green: 0xE9/255.0, blue: 0xE9/255.0, alpha: 1.0)

        capsuleView.backgroundColor = solidFill
        placeholderLabel.textColor = placeholderColor
        placeholderIcon.tintColor = placeholderColor
        activeIcon.tintColor = placeholderColor
        inlineClearButton.tintColor = placeholderColor
        textField.textColor = isDark ? .white : .black
        textField.tintColor = UIColor(RosettaColors.figmaBlue)

        updatePlaceholderAttributes()
    }

    private func updatePlaceholderAttributes() {
        let isDark = traitCollection.userInterfaceStyle == .dark
        let placeholderColor = isDark
            ? UIColor(red: 0x8f/255.0, green: 0x8f/255.0, blue: 0x8f/255.0, alpha: 1.0)
            : UIColor(red: 0x8e/255.0, green: 0x8e/255.0, blue: 0x93/255.0, alpha: 1.0)
        let attrs: [NSAttributedString.Key: Any] = [
            .foregroundColor: placeholderColor,
            .font: UIFont.systemFont(ofSize: 17)
        ]
        textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attrs)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        capsuleView.frame = bounds
        capsuleView.layer.cornerRadius = bounds.height * 0.5
    }

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
            applyColors()
        }
    }

    // MARK: - Visual State

    private func updateVisualState(animated: Bool) {
        let updates = {
            self.placeholderStack.alpha = self.isActive ? 0 : 1
            self.activeStack.alpha = self.isActive ? 1 : 0
        }

        if animated {
            UIView.animate(
                withDuration: 0.5, delay: 0,
                usingSpringWithDamping: 0.78, initialSpringVelocity: 0,
                options: [.beginFromCurrentState],
                animations: updates
            )
        } else {
            updates()
        }
    }

    private func updateClearButtonVisibility() {
        let hasText = !(textField.text?.isEmpty ?? true) && isActive
        inlineClearButton.alpha = hasText ? 1 : 0
        inlineClearButton.isUserInteractionEnabled = hasText
    }

    // MARK: - Activation

    @objc private func handleCapsuleTapped() {
        guard !isActive else { return }
        setActive(true, animated: true)
    }

    func setActive(_ active: Bool, animated: Bool) {
        guard active != isActive else { return }
        isActive = active

        if active {
            DispatchQueue.main.async { [weak self] in
                self?.textField.becomeFirstResponder()
            }
        } else {
            textField.resignFirstResponder()
            textField.text = ""
            onTextChanged?("")
        }

        updateClearButtonVisibility()
        updateVisualState(animated: animated)
    }

    // MARK: - UITextFieldDelegate

    @objc private func handleTextChanged() {
        updateClearButtonVisibility()
        onTextChanged?(textField.text ?? "")
    }

    @objc private func handleInlineClearTapped() {
        textField.text = ""
        updateClearButtonVisibility()
        onTextChanged?("")
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}
