//
//  YHSurveyTableViewCell.swift
//  galaxy
//
//  Created by alexzzw on 2025/3/26.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import AttributedString
import UIKit

class YHSurveyTableViewCell: YHResignDocumentCell {
    static let cellReuseIdentifier = "YHSurveyTableViewCell"

    // MARK: - Question Type

    enum QuestionType {
        case singleChoice // 单选 (圆形按钮)
        case multipleChoice // 多选 (方框按钮)
    }

    // MARK: - UI Elements

    private lazy var questionLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_M(ofSize: 15)
        label.numberOfLines = 0
        label.textColor = .mainTextColor
        return label
    }()

    private lazy var optionsStackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 16
        stack.distribution = .fillProportionally
        return stack
    }()
    
    private lazy var infoFailLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = .failColor
        label.text = "请选择"
        label.isHidden = true
        return label
    }()

    // MARK: - Properties

    var optionSelected: ((Int) -> Void)?
    private var questionType: QuestionType = .singleChoice

    // MARK: - Lifecycle

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Setup

    private func setupUI() {
        updateCellCorner(.single)
        subContainerView.addSubview(questionLabel)
        subContainerView.addSubview(optionsStackView)
        subContainerView.addSubview(infoFailLabel)

        questionLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(24)
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
        }

        optionsStackView.snp.makeConstraints { make in
            make.top.equalTo(questionLabel.snp.bottom).offset(16)
            make.left.equalToSuperview().offset(28)
            make.right.equalToSuperview().offset(-18)
            make.bottom.equalToSuperview().offset(-24).priority(.high)
        }
        
        infoFailLabel.snp.makeConstraints { make in
            make.left.equalTo(questionLabel)
            make.right.lessThanOrEqualToSuperview().offset(-18)
            make.bottom.equalToSuperview().offset(-24).priority(.high)
        }
        infoFailLabel.isHidden = true
    }

    // MARK: - Configuration

    func configure(with question: String, isRequired: Bool = true, options: [String], selectedIndices: [Int], type: QuestionType = .singleChoice, needShowFailButton: Bool = false) {
        let questionAttr: ASAttributedString = .init("\(question)", .font(UIFont.PFSC_M(ofSize: 15)), .foreground(UIColor.mainTextColor))
        if isRequired {
            let starAttr: ASAttributedString = .init("*", .font(UIFont.PFSC_M(ofSize: 15)), .foreground(UIColor.failColor))
            questionLabel.attributed.text = starAttr + questionAttr
        } else {
            questionLabel.attributed.text = questionAttr
        }
        questionType = type

        // Clear previous options
        optionsStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }

        // Add new options
        for (index, option) in options.enumerated() {
            let optionView = createOptionView(text: option, isSelected: selectedIndices.contains(index), index: index)
            optionsStackView.addArrangedSubview(optionView)
        }
        updateFailState(needShowFailButton)
    }
    
    private func updateFailState(_ needShowFailButton: Bool = false) {
        if needShowFailButton {
            optionsStackView.snp.remakeConstraints { make in
                make.top.equalTo(questionLabel.snp.bottom).offset(16)
                make.left.equalToSuperview().offset(28)
                make.right.equalToSuperview().offset(-18)
            }
            infoFailLabel.snp.remakeConstraints { make in
                make.top.equalTo(optionsStackView.snp.bottom).offset(8)
                make.left.equalTo(questionLabel)
                make.right.lessThanOrEqualToSuperview().offset(-18)
                make.bottom.equalToSuperview().offset(-24).priority(.high)
            }
            infoFailLabel.isHidden = false
        } else {
            optionsStackView.snp.remakeConstraints { make in
                make.top.equalTo(questionLabel.snp.bottom).offset(16)
                make.left.equalToSuperview().offset(28)
                make.right.equalToSuperview().offset(-18)
                make.bottom.equalToSuperview().offset(-24).priority(.high)
            }
            infoFailLabel.snp.remakeConstraints { make in
                make.left.equalTo(questionLabel)
                make.right.lessThanOrEqualToSuperview().offset(-18)
                make.bottom.equalToSuperview().offset(-24).priority(.high)
            }
            infoFailLabel.isHidden = true
        }
    }

    private func createOptionView(text: String, isSelected: Bool, index: Int) -> UIView {
        let item = YHSurveyQuestionItemView()
        item.tag = index
        item.addTarget(self, action: #selector(optionButtonTapped(_:)), for: .touchUpInside)
        item.setup(text: text, isSelected: isSelected)
        return item
    }

    // MARK: - Actions

    @objc private func optionButtonTapped(_ sender: UIControl) {
        optionsStackView.arrangedSubviews.enumerated().forEach { index, subView in
            guard let item = subView as? YHSurveyQuestionItemView else {
                return
            }
            item.updateState(isSelected: sender.tag == index)
        }
        optionSelected?(sender.tag)
    }
}

class YHSurveyQuestionItemView: UIControl {
    
    private lazy var iconView: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.textColor = .mainTextColor
        label.font = .PFSC_R(ofSize: 14)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        addSubview(contentLabel)

        iconView.snp.makeConstraints { make in
            make.left.centerY.equalToSuperview()
            make.width.height.equalTo(14)
        }

        contentLabel.snp.makeConstraints { make in
            make.left.equalTo(iconView.snp.right).offset(8)
            make.right.top.bottom.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setup(text: String, isSelected: Bool) {
        updateState(isSelected: isSelected)
        contentLabel.text = text
    }
    
    func updateState(isSelected: Bool) {
        iconView.image = isSelected ? UIImage(named: "plan_question_checked") : UIImage(named: "plan_question_unchecked")
    }
}
