//
//  EPTagLabel.swift

//
//  Created by Leon on 2025/7/25.
//

import SnapKit // Assuming SnapKit is used for layout instead of Masonry
import UIKit

// MARK: - Enums

enum EPTagLabelStyle: Int {
    // 灰色底，白色字
    case `default`
    case whiteOnColor
    // 黑底，白色字
    case blackOnColor
    // 紫色底，白色字
    case primary
    case warning
    case positive
    case emphasis
    case discount
    case subscribe
    // 金色边框渐变
    case legends
    case important
    // 金黄色渐变
    case vipOfficial
    // 红色渐变
    case limited
    // 浅紫到深紫
    case aiTag
}

enum EPTagLabelSize: Int {
    case size20 // height: 20
    case small // Mobile Txt/txt.label.s height: 24
    case medium // Mobile Txt/txt.label.s height: 28
    case large // Mobile Txt/txt.label.m height: 32
}

// Assuming NSStringShowFromCommunityIdentifier is a localization function
func NSStringShowFromCommunityIdentifier(_ identifier: String) -> String {
    // Placeholder implementation
    return identifier.capitalized
}

class EPTagLabel: UIView {
    // MARK: - Properties

    private let contentStackH: UIStackView
    private(set) var textLabel: UILabel
    private var cgColors: [CGColor] = []
    private var gradientLayer: CAGradientLayer?
    private var startPoint: CGPoint = CGPoint(x: 0, y: 0)
    private var endPoint: CGPoint = CGPoint(x: 1, y: 0)

    var style: EPTagLabelStyle {
        didSet { setupTheme() }
    }

    var labelSize: EPTagLabelSize {
        didSet {
            setupLayout()
            setupFont()
        }
    }

    var text: String? {
        didSet {
            textLabel.text = text
            setNeedsLayout()
        }
    }

    // MARK: - Initialization

    init(style: EPTagLabelStyle, size: EPTagLabelSize = .small, text: String? = nil) {
        self.style = style
        labelSize = size
        textLabel = UILabel()
        contentStackH = UIStackView()
        
        textLabel.text = text
        
        super.init(frame: .zero)

        addSubview(contentStackH)
        contentStackH.addArrangedSubview(textLabel)
        
        self.text = text
        startPoint = CGPoint(x: 0, y: 0)
        endPoint = CGPoint(x: 1, y: 0)

        clipsToBounds = true
        layer.cornerRadius = CLSystemToken.radius(token: .rxs)

        setupTheme()
        setupLayout()
        setupFont()

        // Setup stack view
        setupContentStack()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Public Methods

    static func innerPadding() -> CGFloat {
        return 8
    }

    func setupContentStackHUnlimitedHeight() {
        var textLRPadding = Self.innerPadding()
        if labelSize == .size20 {
            textLRPadding = 4
        }

        let edge = UIEdgeInsets(top: 7.5, left: textLRPadding, bottom: 7.5, right: textLRPadding)
        contentStackH.snp.remakeConstraints { make in
            make.edges.equalToSuperview().inset(edge)
        }
    }

    // MARK: - Layout

    override func layoutSubviews() {
        super.layoutSubviews()

        gradientLayer?.removeFromSuperlayer()
        gradientLayer = nil

        if !cgColors.isEmpty {
            let gradientLayer = CAGradientLayer()
            gradientLayer.frame = bounds
            gradientLayer.colors = cgColors
            gradientLayer.startPoint = startPoint
            gradientLayer.endPoint = endPoint
            gradientLayer.locations = cgColors.count >= 3 ? [0, 0.5, 1] : [0, 1]
            layer.insertSublayer(gradientLayer, at: 0)
            self.gradientLayer = gradientLayer
        }
    }

    // MARK: - Private Setup Methods

    private func setupContentStack() {
        contentStackH.spacing = 8
        contentStackH.alignment = .center
        addSubview(contentStackH)

        textLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        contentStackH.addArrangedSubview(textLabel)
    }

    private func setupLayout() {
        var labelH: CGFloat = 24
        var textLRPadding = Self.innerPadding()

        switch labelSize {
        case .size20:
            labelH = 20
            textLRPadding = 4
        case .medium:
            labelH = 28
        case .large:
            labelH = 32
        case .small:
            break
        }

        let edge = UIEdgeInsets(top: 0, left: textLRPadding, bottom: 0, right: textLRPadding)
        contentStackH.snp.remakeConstraints { make in
            make.edges.equalToSuperview().inset(edge)
            make.height.equalTo(labelH)
        }
    }

    private func setupFont() {
        switch labelSize {
        case .small, .medium:
            textLabel.font = .t.tls // EPSystemToken.typography("EPS_Txt_Label_s")
        case .large:
            textLabel.font = .t.tlm // EPSystemToken.typography("EPS_Txt_Label_m")
        case .size20:
            textLabel.font = .t.tls // EPSystemToken.typography("EPS_Txt_Label_s")
        }
    }

    private func setupTheme() {
        // Reset state
        textLabel.textColor = .text // EPSystemToken.color("EPS_Color_Txt_primary_normal")

        cgColors = []
        backgroundColor = nil
        layer.borderWidth = 0

        switch style {
        case .default:
            backgroundColor = .c.csen // EPSystemToken.color("EPS_Color_Surface_element_normal")

        case .whiteOnColor:
            backgroundColor = .c.cseln // EPSystemToken.color("EPS_Color_Surface_element_light_normal")

        case .blackOnColor:
            backgroundColor = .c.csedn // EPSystemToken.color("EPS_Color_Surface_element_dark_normal")

        case .primary:
            backgroundColor = .c.cpn // EPSystemToken.color("EPS_Color_Primary_normal")

        case .warning:
            backgroundColor = .c.cwn // EPSystemToken.color("EPS_Color_Warning_normal")

        case .positive:
            backgroundColor = .c.cpn // EPSystemToken.color("EPS_Color_Positive_normal")

        case .emphasis:
            backgroundColor = .c.cen // EPSystemToken.color("EPS_Color_Emphasis_normal")

        case .important:
            backgroundColor = .c.cin // EPSystemToken.color("EPS_Color_Important_normal")

        case .discount:
            let token = CLSystemToken.gradient(token: .cpgn) // EPSystemToken.gradient("EPS_Color_Primary_Gradient_normal")
            setupColorsGradient(token)

        case .subscribe:
            let token = CLSystemToken.gradient(token: .ccvn) // EPSystemToken.gradient("EPS_Color_Context_subscribe_normal")
            setupColorsGradient(token)

        case .legends:
            backgroundColor = .c.csedn // EPSystemToken.color("EPS_Color_Surface_element_dark_normal")
            layer.borderWidth = 1
            layer.borderColor = UIColor.c.csedn.cgColor // EPSystemToken.color("EPS_Color_Context_legends_variant_normal").cgColor
            textLabel.textColor = .c.csedn // EPSystemToken.color("EPS_Color_Context_legends_variant_normal")

        case .vipOfficial:
            textLabel.textColor = .c.cbd // EPSystemToken.color("EPS_Color_Background_default")
            let token = CLSystemToken.gradient(token: .ccvn) // EPSystemToken.gradient("EPS_Color_Context_legends_normal")
            setupColorsGradient(token)

        case .limited:
            let token = CLSystemToken.gradient(token: .cign) // EPSystemToken.gradient("EPS_Color_Important_Gradient_normal")
            setupColorsGradient(token)

        case .aiTag:
            setupColors([
                UIColor(hex: "#D327FF"),
                UIColor(hex: "#773DFF"),
            ])
        }

        setNeedsLayout()
    }

    private func setupColorsGradient(_ token: EPGradient) {
        cgColors = []
        if let firstColor = token.firstColor {
            cgColors.append(firstColor.cgColor)
        }
        if let secondColor = token.secondColor {
            cgColors.append(secondColor.cgColor)
        }
        setNeedsLayout()
    }

    private func setupColors(_ colors: [UIColor]) {
        cgColors = colors.map { $0.cgColor }
        setNeedsLayout()
    }
}
