//
//  YHIncomeDocumentationConfirmationCell.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import AttributedString
import UIKit

class YHIncomeDocumentationConfirmationCell: YHResignDocumentCell {
    static let cellReuseIdentifier = "YHIncomeDocumentationConfirmationCell"
    var didSelectSureButton: ((YHIncomeRecordHasAllFile) -> Void)?
    private var documentationViews: [YHIncomeDocumentationView] = []
    private var lastDocuments: [String] = []
    
    var selectedSureButton: YHIncomeRecordHasAllFile = .unknown {
        didSet {
            updateButtonsState(selectedSureButton)
        }
    }
    
    private lazy var infoTitleLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_M(ofSize: 17)
        label.textColor = UIColor.mainTextColor
        return label
    }()
    
    private lazy var topLineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#E9ECF0")
        return view
    }()
    
    private lazy var dotIcon: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "red_dot_6"))
        return imageView
    }()
    
    private lazy var infoQuestionLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 14)
        label.textColor = UIColor.mainTextColor
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        return label
    }()
    
    private lazy var sureButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .PFSC_M(ofSize: 13)
        button.setTitle("是", for: .normal)
        button.setTitleColor(.mainTextColor, for: .normal)
        button.setTitleColor(.brandMainColor, for: .selected)
        button.addTarget(self, action: #selector(sureButtonDidClick(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 16.0
        button.clipsToBounds = true
        return button
    }()
    
    private lazy var cancelButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .PFSC_M(ofSize: 13)
        button.setTitle("否", for: .normal)
        button.setTitleColor(.mainTextColor, for: .normal)
        button.setTitleColor(.brandMainColor, for: .selected)
        button.addTarget(self, action: #selector(cancelButtonDidClick(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 16
        button.clipsToBounds = true
        return button
    }()
    
    private lazy var containerView: YHBaseDynamicCornerRadiusView = {
        let view = YHBaseDynamicCornerRadiusView(cornerRadius: 3, corner: .allCorners)
        view.backgroundColor = .contentBkgColor
        return view
    }()
    
    private lazy var infoFailLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textColor = .failColor
        label.text = "请选择"
        label.numberOfLines = 0
        label.lineBreakMode = .byCharWrapping
        return label
    }()
    
    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")
    }
    
    func setupCellInfo(title: String, question: String, documents: [String], needShowFailButton: Bool) {
        infoTitleLabel.text = title
        infoQuestionLabel.text = question
        if lastDocuments != documents || documentationViews.count != documents.count {
            lastDocuments = documents
            documentationViews.forEach {
                $0.removeFromSuperview()
            }
            documentationViews.removeAll()
            let count = documents.count
            documents.enumerated().forEach { [weak self] index, title in
                guard let self = self else {
                    return
                }
                let documentationView = YHIncomeDocumentationView()
                documentationView.setupInfo(title)
                
                self.documentationViews.append(documentationView)
                self.containerView.addSubview(documentationView)

                documentationView.snp.makeConstraints { make in
                    if index == 0 {
                        make.top.equalToSuperview().offset(16)
                    } else {
                        make.top.equalTo(self.documentationViews[index - 1].snp.bottom).offset(12)
                    }
                    make.left.equalToSuperview().offset(16)
                    make.right.lessThanOrEqualToSuperview().offset(-8)
                    if index == count - 1 {
                        make.bottom.equalToSuperview().offset(-16)
                    }
                }
            }
        }
        
        updateFailLabel(needShowFailButton)
    }
}

extension YHIncomeDocumentationConfirmationCell {
    private func updateFailLabel(_ needShowFailButton: Bool) {
        if needShowFailButton || selectedSureButton == .false {
            infoFailLabel.isHidden = false
            infoFailLabel.attributed.text = selectedSureButton.selectedTips()
            containerView.snp.remakeConstraints { make in
                make.left.equalTo(infoTitleLabel.snp.left)
                make.right.equalToSuperview().offset(-18)
                make.top.equalTo(infoQuestionLabel.snp.bottom).offset(16)
            }
            
            infoFailLabel.snp.remakeConstraints { make in
                make.top.equalTo(containerView.snp.bottom).offset(6)
                make.left.equalTo(containerView)
                make.right.lessThanOrEqualToSuperview().offset(-18)
                make.bottom.equalToSuperview().offset(-16)
            }
            
        } else {
            infoFailLabel.isHidden = true
            infoFailLabel.attributed.text = selectedSureButton.selectedTips()
            containerView.snp.remakeConstraints { make in
                make.left.equalTo(infoTitleLabel.snp.left)
                make.right.equalToSuperview().offset(-18)
                make.top.equalTo(infoQuestionLabel.snp.bottom).offset(16)
                make.bottom.equalToSuperview().offset(-16)
            }
            
            infoFailLabel.snp.remakeConstraints { make in
                make.left.equalTo(containerView)
                make.right.lessThanOrEqualToSuperview().offset(-18)
                make.bottom.equalToSuperview().offset(-16)
            }
        }
    }
    
    @objc private func cancelButtonDidClick(_ sender: UIButton) {
        guard !sender.isSelected else {
            return
        }
        selectedSureButton = .false
        didSelectSureButton?(.false)
    }

    @objc private func sureButtonDidClick(_ sender: UIButton) {
        guard !sender.isSelected else {
            return
        }
        selectedSureButton = .true
        didSelectSureButton?(.true)
    }

    private func setupUI() {
        updateCellCorner(.single)
        subContainerView.addSubview(infoTitleLabel)
        subContainerView.addSubview(topLineView)
        subContainerView.addSubview(dotIcon)
        subContainerView.addSubview(infoQuestionLabel)
        subContainerView.addSubview(sureButton)
        subContainerView.addSubview(cancelButton)
        subContainerView.addSubview(containerView)
        subContainerView.addSubview(infoFailLabel)

        sureButton.setContentCompressionResistancePriority(.required, for: .horizontal)
        cancelButton.setContentCompressionResistancePriority(.required, for: .horizontal)
        infoQuestionLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        
        infoTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.top.equalToSuperview().offset(16)
            make.right.lessThanOrEqualToSuperview().offset(-18)
        }

        topLineView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(infoTitleLabel.snp.bottom).offset(12)
        }

        dotIcon.snp.makeConstraints { make in
            make.left.equalTo(infoTitleLabel.snp.left)
            make.height.width.equalTo(6)
            make.top.equalTo(infoQuestionLabel.snp.top).offset(7)
        }

        infoQuestionLabel.snp.makeConstraints { make in
            make.left.equalTo(dotIcon.snp.right).offset(2)
            make.top.equalTo(topLineView.snp.bottom).offset(16)
            make.height.greaterThanOrEqualTo(40)
            make.width.lessThanOrEqualTo(113)
        }

        cancelButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(32)
            make.width.equalTo(69)
            make.centerY.equalTo(infoQuestionLabel)
        }

        sureButton.snp.makeConstraints { make in
            make.right.equalTo(cancelButton.snp.left).offset(-8)
            make.height.equalTo(32)
            make.width.equalTo(69)
            make.centerY.equalTo(infoQuestionLabel)
            make.left.greaterThanOrEqualTo(infoQuestionLabel.snp.right).offset(8)
        }
        
        containerView.snp.makeConstraints { make in
            make.left.equalTo(infoTitleLabel.snp.left)
            make.right.equalToSuperview().offset(-18)
            make.top.equalTo(infoQuestionLabel.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        infoFailLabel.snp.makeConstraints { make in
            make.left.equalTo(containerView)
            make.right.lessThanOrEqualToSuperview().offset(-18)
            make.bottom.equalToSuperview().offset(-16)
        }
        infoFailLabel.isHidden = true
        selectedSureButton = .unknown
    }

    private func updateButtonsState(_ state: YHIncomeRecordHasAllFile) {
        switch state {
        case .unknown:
            sureButton.isSelected = false
            sureButton.backgroundColor = .contentBkgColor
            sureButton.layer.borderColor = nil
            sureButton.layer.borderWidth = 0
            cancelButton.isSelected = false
            cancelButton.backgroundColor = .contentBkgColor
            cancelButton.layer.borderColor = nil
            cancelButton.layer.borderWidth = 0
        case .true:
            sureButton.isSelected = true
            sureButton.backgroundColor = UIColor(hexString: "#EBF0F9")
            sureButton.layer.borderColor = UIColor.brandMainColor.cgColor
            sureButton.layer.borderWidth = 1
            
            cancelButton.isSelected = false
            cancelButton.backgroundColor = .contentBkgColor
            cancelButton.layer.borderColor = nil
            cancelButton.layer.borderWidth = 0
        case .false:
            cancelButton.isSelected = true
            cancelButton.backgroundColor = UIColor(hexString: "#EBF0F9")
            cancelButton.layer.borderColor = UIColor.brandMainColor.cgColor
            cancelButton.layer.borderWidth = 1
            sureButton.isSelected = false
            sureButton.backgroundColor = .contentBkgColor
            sureButton.layer.borderColor = nil
            sureButton.layer.borderWidth = 0
        }
    }
}

class YHIncomeDocumentationView: UIView {

    private lazy var infoDetailLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 14)
        label.textColor = .mainTextColor
        label.numberOfLines = 0
        label.lineBreakMode = .byCharWrapping
        return label
    }()
    
    private lazy var dotView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#B3C8E9")
        view.layer.cornerRadius = 1
        view.clipsToBounds = true
        return view
    }()

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

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

    func setupInfo(_ detail: String, font: UIFont = .PFSC_R(ofSize: 14)) {
        infoDetailLabel.text = detail
        infoDetailLabel.font = font
    }

    private func setupUI() {
        addSubview(dotView)
        addSubview(infoDetailLabel)
        dotView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.height.width.equalTo(5)
            make.top.equalTo(infoDetailLabel.snp.top).offset(6)
        }
        
        infoDetailLabel.snp.makeConstraints { make in
            make.left.equalTo(dotView.snp.right).offset(8)
            make.top.bottom.right.equalToSuperview()
        }
    }
}

private extension YHIncomeRecordHasAllFile {
    func selectedTips() -> ASAttributedString? {
        switch self {
        case .unknown:
            return .init(string: "请选择", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.failColor))
        case .true:
            return nil
        case .false:
            let first: ASAttributedString = .init(string: "若不能提供以上证明材料，将导致您的该收入", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
            let second: ASAttributedString = .init(string: "不被认可不予加分", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.failColor))
            let third: ASAttributedString = .init(string: "，请尽可能准备以上材料并修改此选项。", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor(hexString: "#8993A2") ?? .gray))
            return first + second + third
        }
    }
}
