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

// import AttributedString
import UIKit

// 问卷页
class YHCustomerInformationQuestionnaireVC: YHBaseViewController {

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight), style: .grouped)
        view.estimatedSectionHeaderHeight = 0.01
        view.estimatedSectionFooterHeight = 16
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHSurveyTableViewCell.self, forCellReuseIdentifier: YHSurveyTableViewCell.cellReuseIdentifier)
        return view
    }()

    private var imageHeight: CGFloat {
        return KScreenWidth
    }

    private lazy var topImageView: UIImageView = {
        let view = UIImageView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: imageHeight))
        return view
    }()

    private lazy var submitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        let buttonName = "提交"
        button.setTitle(buttonName, for: .normal)
        button.setTitle(buttonName, for: .highlighted)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .normal)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .highlighted)
        button.addTarget(self, action: #selector(submitButtonClick), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = UIColor(hexString: "#121A26")
        return button
    }()

    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    /*
     private lazy var privacyButton: UIButton = {
         let button = UIButton(type: .custom)
         button.setImage(UIImage(named: "plan_privacy_unchecked"), for: .normal)
         button.setImage(UIImage(named: "plan_privacy_checked"), for: .selected)
         button.addTarget(self, action: #selector(privacyButtonClicked), for: .touchUpInside)
         return button
     }()

     private lazy var privacyLabel: UILabel = {
         let label = UILabel()
         let normal: ASAttributedString = .init("同意用户隐私信息收集协议《 ", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor.withAlphaComponent(0.5))).add(attributes: .action { [weak self] in
             self?.privacyButtonClicked()
         })

         let attributed: ASAttributedString = .init("隐私协议", .font(UIFont.PFSC_M(ofSize: 13)), .foreground(UIColor.mainTextColor), .action { [weak self] in
             self?.gotoPrivacyPage()
         })
         let end: ASAttributedString = .init(" 》", .font(UIFont.PFSC_R(ofSize: 13)), .foreground(UIColor.mainTextColor.withAlphaComponent(0.5)))
         let content = normal + attributed + end
         label.attributed.text = content
         return label
     }()
      */

    private var sections: [YHSurveyQuestionType] {
        return YHSurveyQuestionType.allCases
    }

    private lazy var viewModel = YHSurveyViewModel()

    private var allQuestions: [YHSurveyQuestionItem] = []
    private var displayedQuestions: [YHSurveyQuestionItem] = []
    /// key:  问题Id, value: 答案
    private var answerDic: [String: [YHSurveyConditionOptionExtra]] = [:]
    private var needShowFail: Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        fetchData()
    }

    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navBackgroundColor = .clear
        gk_backImage = UIImage(named: "back_icon_white")
        updateRightBarButtonItem(true)
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(bottomView)
        bottomView.addSubview(submitButton)
        // bottomView.addSubview(privacyButton)
        // bottomView.addSubview(privacyLabel)
        view.addSubview(tableView)
        view.addSubview(topImageView)
        view.bringSubviewToFront(tableView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-64)
        }
        /*
         privacyButton.snp.makeConstraints { make in
             make.left.equalToSuperview().offset(20)
             make.width.height.equalTo(13)
             make.centerY.equalTo(privacyLabel)
         }
         privacyLabel.snp.makeConstraints { make in
             make.left.equalTo(privacyButton.snp.right).offset(6)
             make.top.equalToSuperview().offset(12)
             make.right.lessThanOrEqualToSuperview().offset(-16)
         }
          */

        submitButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48)
        }

        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top).offset(-8)
        }
        tableView.contentInset = UIEdgeInsets(top: imageHeight - 115, left: 0, bottom: 0, right: 0)
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
    }

    @objc private func share() {
        let url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/renewal-evaluation"
        YHShareManager.shared.sendLinkContent("香港身份方案评估", "您的朋友邀请您进行香港身份申请到永居一站式解决方案评估，来试试吧", UIImage(named: "survey_share_icon") ?? UIImage(), link: url)
    }

    @objc private func submitButtonClick() {
        guard let surveyContent = viewModel.surveyContainerModel?.surveyContent else {
            return
        }
        if let lastQuestion = displayedQuestions.last, lastQuestion.isRequired == 1, answerDic[lastQuestion.id] == nil {
            needShowFail = true
            let sections = tableView.numberOfSections
            if sections > 0 {
                tableView.reloadSections(IndexSet(integer: sections - 1), with: .automatic)
            }
            needShowFail = false
            return
        }
        YHHUD.show(.progress(message: "加载中..."))
        var answers: [YHSurveyArticleAnswerItem] = []
        displayedQuestions.forEach { [weak self] question in
            guard let self = self else {
                return
            }
            let ans = self.answerDic[question.id] ?? []
            let extras: [YHSurveyAnswerItemOptionExtra] = ans.compactMap { optionExtra in
                YHSurveyAnswerItemOptionExtra.init(extra: optionExtra.extra, optionId: optionExtra.optionId, optionKey: "", title: optionExtra.title)
            }
            let answer = YHSurveyArticleAnswerItem.init(fileList: [], optionExtra: extras, questionId: question.id, questionKey: question.businessKey, questionType: question.type, text: "", title: question.title)
            answers.append(answer)
        }
        let requestModel = YHSurveySubmitRequestModel(answerDetails: answers, surveyId: surveyContent.id)
        viewModel.submitSurveyAnswer(requestModel: requestModel) { [weak self] responseModel, error in
            YHHUD.hide()
            guard let self = self else {
                return
            }
            guard let responseModel = responseModel else {
                var errorMsg: String = "提交失败，请重试"
                if let msg = error?.errorMsg, !msg.isEmpty {
                    errorMsg = msg
                }
                YHHUD.flash(message: errorMsg)
                return
            }
            if responseModel.hasHkIdentity {
                self.gotoMatchingVC()
            } else {
                self.gotoSubmitDoneVC()
            }
        }
    }
    
    private func gotoSubmitDoneVC() {
        let ctl = YHSurveySubmitDoneViewController()
        navigationController?.pushViewController(ctl)
    }
    
    private func gotoMatchingVC() {
        let ctl = YHSurveyMatchingViewController()
        navigationController?.pushViewController(ctl)
    }

    /*
     @objc private func privacyButtonClicked() {
         privacyButton.isSelected.toggle()
     }

     private func gotoPrivacyPage() {
         let vc = YHWebViewViewController()
         vc.url = YHBaseUrlManager.shared.curPrivacyAgreementUrl()
         vc.navTitle = "银河港生活隐私协议"
         navigationController?.pushViewController(vc)
     }
      */

    private func updateRightBarButtonItem(_ isWhite: Bool) {
        let rightButtonItem = UIBarButtonItem(image: UIImage(named: isWhite ? "video_share" : "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
        gk_navRightBarButtonItem = rightButtonItem
        gk_navItemRightSpace = 16
    }

    private func fetchData() {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getSurveyContent { [weak self] _, _ in
            YHHUD.hide()
            self?.configureQuestions()
        }
    }

    private func configureQuestions() {
        guard let surveyContainerModel = viewModel.surveyContainerModel else {
            tableView.reloadData()
            return
        }
        let questions = surveyContainerModel.surveyContent.questions
        allQuestions = questions
        displayedQuestions.removeAll()
        let isNew = surveyContainerModel.isNewCustomer
        if isNew {
            topImageView.image = UIImage(named: "plan_question_top_new")
            for question in questions where question.showWhenV1.conditions.isEmpty {
                displayedQuestions.append(question)
            }
        } else {
            topImageView.image = UIImage(named: "plan_question_top_old")
            if let first = questions.first, surveyContainerModel.defaultAnswers.contains(where: { answer in
                answer.questionKey == first.businessKey
            }) {
                /*
                for answer in surveyContainerModel.defaultAnswers {
                    if let question = questions.first(where: { item in
                        item.businessKey == answer.questionKey
                    }) {
                        displayedQuestions.append(question)
                        let options = answer.optionKey.compactMap { optionKey in
                            let option = question.options.first { optionItem in
                                optionItem.businessKey == optionKey
                            }
                            return YHSurveyConditionOptionExtra(extra: "", optionId: option?.id ?? "", title: option?.title ?? "", optionKey: answer.questionKey)
                        }
                        self.answerDic[question.id] = options
                    }
                }
                 */
                
                for (index, answer) in surveyContainerModel.defaultAnswers.enumerated() {
                    if let question = questions.first(where: { item in
                        item.businessKey == answer.questionKey
                    }) {
                        displayedQuestions.append(question)
                        let options = answer.optionKey.compactMap { optionKey in
                            let option = question.options.first { optionItem in
                                optionItem.businessKey == optionKey
                            }
                            return YHSurveyConditionOptionExtra(extra: "", optionId: option?.id ?? "", title: option?.title ?? "", optionKey: answer.questionKey)
                        }
                        self.answerDic[question.id] = options
                    }
                    if surveyContainerModel.defaultAnswers.count > index + 1, let lastModel = displayedQuestions.last, let nextQuestion = self.findNextQuestion(allQuestions: self.allQuestions, displayedQuestions: self.displayedQuestions, answerDic: self.answerDic, currentIndex: displayedQuestions.count - 1, currentOptionId: lastModel.id), nextQuestion.businessKey != surveyContainerModel.defaultAnswers[index + 1].questionKey {
                        self.displayedQuestions.append(nextQuestion)
                        break
                    }
                }
                
                if let lastModel = displayedQuestions.last, let nextQuestion = self.findNextQuestion(allQuestions: self.allQuestions, displayedQuestions: self.displayedQuestions, answerDic: self.answerDic, currentIndex: displayedQuestions.count - 1, currentOptionId: lastModel.id) {
                    self.displayedQuestions.append(nextQuestion)
                }
            } else {
                for question in questions where question.showWhenV1.conditions.isEmpty {
                    displayedQuestions.append(question)
                }
            }
        }
        tableView.reloadData()
    }
    
    private func scrollToBottom(_ animated: Bool = true) {
        guard displayedQuestions.count > 0 else {
            return
        }
        let sections = tableView.numberOfSections
        let count = tableView.numberOfRows(inSection: sections - 1)
        if count > 0 {
            tableView.scrollToRow(at: IndexPath(row: count - 1, section: sections - 1), at: .bottom, animated: animated)
        }
    }
}

extension YHCustomerInformationQuestionnaireVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return displayedQuestions.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard displayedQuestions.count > section else {
            return 0
        }
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard displayedQuestions.count > indexPath.section else {
            return UITableViewCell()
        }
        let model = displayedQuestions[indexPath.section]
        if let cell = tableView.dequeueReusableCell(withIdentifier: YHSurveyTableViewCell.cellReuseIdentifier) as? YHSurveyTableViewCell {
            var selectedIndices: [Int] = []
            if let options = answerDic[model.id] {
                options.forEach { outerOption in
                    if let index = model.options.firstIndex(where: { innerOption in
                        innerOption.id == outerOption.optionId
                    }) {
                        selectedIndices.append(index)
                    }
                }
            }
            var needShowFailButton = false
            if needShowFail, model.isRequired == 1, answerDic[model.id] == nil {
                needShowFailButton = true
            }
            cell.configure(with: "\(indexPath.section + 1). " + model.title, isRequired: model.isRequired == 1, options: model.options.compactMap { $0.title }, selectedIndices: selectedIndices, needShowFailButton: needShowFailButton)
            cell.optionSelected = { [weak self] index in
                guard let self = self else {
                    return
                }
                let option = model.options.count > index ? model.options[index] : nil
                if let option = option {
                    self.answerDic[model.id] = [YHSurveyConditionOptionExtra(extra: "", optionId: option.id, title: option.title, optionKey: option.businessKey)]
                    if let currentIndex = self.displayedQuestions.firstIndex(where: { $0.id == model.id }) {
                        self.tableView.reloadSections(IndexSet(integer: currentIndex), with: .automatic)
                        if self.displayedQuestions.count > currentIndex + 1 {
                            let nextQuestion = self.displayedQuestions[currentIndex + 1]
                            if option.jumpQuestionId.count > 0, option.jumpQuestionId != nextQuestion.id {
                                var questionIds: [String] = []
                                self.displayedQuestions.enumerated().forEach { index, item in
                                    if index > currentIndex {
                                        questionIds.append(item.id)
                                    }
                                }
                                self.answerDic.removeAll(keys: questionIds)
                                self.displayedQuestions.removeSubrange((currentIndex + 1)...)
                                if let nextQuestion = self.findNextQuestion(allQuestions: self.allQuestions, displayedQuestions: self.displayedQuestions, answerDic: self.answerDic, currentIndex: currentIndex, currentOptionId: model.id) {
                                    self.displayedQuestions.append(nextQuestion)
                                }
                                self.tableView.reloadData()
                                UIView.performWithoutAnimation {
                                    self.scrollToBottom(false)
                                }
                            }
                        } else {
                            if let nextQuestion = self.findNextQuestion(allQuestions: self.allQuestions, displayedQuestions: self.displayedQuestions, answerDic: self.answerDic, currentIndex: currentIndex, currentOptionId: model.id) {
                                
                                self.tableView.performBatchUpdates { [weak self] in
                                    guard let self = self else {
                                        return
                                    }
                                    self.displayedQuestions.append(nextQuestion)
                                    self.tableView.insertSections(IndexSet(integer: currentIndex + 1), with: .bottom)
                                } completion: { [weak self] _ in
                                    self?.scrollToBottom()
                                }
                            }
                        }
                    }
                } else {
                    self.answerDic[model.id] = nil
                }
            }
            return cell
        }
        return UITableViewCell()
    }

    private func findNextQuestion(allQuestions: [YHSurveyQuestionItem], displayedQuestions: [YHSurveyQuestionItem], answerDic: [String: [YHSurveyConditionOptionExtra]], currentIndex: Int, currentOptionId: String) -> YHSurveyQuestionItem? {
        let currentQuestion = displayedQuestions[currentIndex]
        let prefixQuestions = displayedQuestions.prefix(currentIndex + 1)
        guard let currentAnswer = answerDic[currentQuestion.id] else {
            return nil
        }
        let currentAnswerIds = currentAnswer.compactMap { $0.optionId }
        let currentSelction = YHSurveyQuestionAndOptions(questionsId: currentQuestion.id, optionIds: Set(currentAnswerIds))
        var retItem: YHSurveyQuestionItem?
        for allItem in allQuestions {
            if !prefixQuestions.contains(where: { prefixItem in
                allItem.id == prefixItem.id
            }) {
                let showWhenV1 = allItem.showWhenV1
                if showWhenV1.relation == "or" {
                    if showWhenV1.orArray.contains(where: { item in
                        item == currentSelction || (item.optionIds.count == 0 && currentSelction.questionsId == item.questionsId)
                    }) {
                        retItem = allItem
                        break
                    }
                } else if showWhenV1.relation == "and" {
                    if showWhenV1.andArray.count == 0 {
                        continue
                    } else if showWhenV1.andArray.count == 1 {
                        if showWhenV1.andArray.contains(where: { item in
                            item == currentSelction || (item.optionIds.count == 0 && currentSelction.questionsId == item.questionsId)
                        }) {
                            retItem = allItem
                            break
                        }
                    } else {
                        let prefixItems = prefixQuestions.compactMap { prefixItem in
                            let options = answerDic[prefixItem.id] ?? []
                            let optionIds = options.compactMap { $0.optionId }
                            return YHSurveyQuestionAndOptions(questionsId: prefixItem.id, optionIds: Set(optionIds))
                        }
                        let isAllSubset = showWhenV1.andArray.allSatisfy { outterItem in
                            prefixItems.contains { innerItem in
                                outterItem == innerItem || (outterItem.optionIds.count == 0 && innerItem.questionsId == outterItem.questionsId)
                            }
                        }
                        if isAllSubset {
                            retItem = allItem
                            break
                        }
                    }
                }
            }
        }

        return retItem
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == sections.count - 1 {
            return 0.01
        }
        return 16
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetY = scrollView.contentOffset.y + scrollView.contentInset.top
        topImageView.frame.origin.y = -offsetY
        if offsetY > 0 {
            var alpha = offsetY / k_Height_NavigationtBarAndStatuBar
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            gk_navBackgroundColor = .white
            gk_navTitle = "香港身份方案评估"
            gk_backImage = UIImage(named: "nav_black_24")
            gk_navRightBarButtonItem?.image = UIImage(named: "share_item")
            updateRightBarButtonItem(false)
        } else {
            gk_navBarAlpha = 0.0
            gk_navBackgroundColor = .clear
            gk_navTitle = nil
            updateRightBarButtonItem(true)
            gk_backImage = UIImage(named: "back_icon_white")
        }
    }
}
