import UIKit
import SwiftUI

/// Option row cell for "New Group" / "Join Group" actions in ComposeViewController.
final class ComposeOptionCell: UICollectionViewCell {

    static let reuseID = "ComposeOptionCell"

    // MARK: - Layout Constants

    private enum Layout {
        static let iconSize: CGFloat = 28
        static let iconLeading: CGFloat = 20
        static let textLeading: CGFloat = 14
        static let cellHeight: CGFloat = 48
        static let separatorLeading: CGFloat = 62 // iconLeading + iconSize + textLeading
    }

    // MARK: - Subviews

    private let iconView = UIImageView()
    private let titleLabel = UILabel()
    private let separatorView = UIView()

    // 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

        iconView.contentMode = .scaleAspectFit
        iconView.tintColor = UIColor(RosettaColors.figmaBlue)
        contentView.addSubview(iconView)

        titleLabel.font = .systemFont(ofSize: 17, weight: .regular)
        titleLabel.textColor = UIColor(RosettaColors.figmaBlue)
        contentView.addSubview(titleLabel)

        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 iconY = (bounds.height - Layout.iconSize) / 2
        iconView.frame = CGRect(
            x: Layout.iconLeading,
            y: iconY,
            width: Layout.iconSize,
            height: Layout.iconSize
        )

        let textX = Layout.iconLeading + Layout.iconSize + Layout.textLeading
        titleLabel.frame = CGRect(
            x: textX,
            y: 0,
            width: bounds.width - textX - 16,
            height: bounds.height
        )

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

    // MARK: - Configure

    func configure(icon: UIImage?, title: String, showSeparator: Bool = true) {
        iconView.image = icon
        titleLabel.text = title
        separatorView.isHidden = !showSeparator
    }

    // MARK: - Highlight

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