//
//  LNAutoReplyEditViewController.swift
//  Gami
//
//  Created by OneeChan on 2026/3/10.
//

import Foundation
import UIKit
import SnapKit


extension UIView {
    func pushToAutoRelyEdit(num: Int, item: LNAutoReplyVO) {
        let vc = LNAutoReplyEditViewController()
        vc.update(num: num, item: item)
        navigationController?.pushViewController(vc, animated: true)
    }
}


class LNAutoReplyEditViewController: LNViewController {
    private let editView = UIView()
    private let titleLabel = UILabel()
    
    private let textEdit = LNCommonTextView()
    private let voiceEdit = LNVoiceEditView()
    
    private let rejectView = UIView()
    private let rejectLabel = UILabel()
    
    private let commitButton = UIButton()
    
    private var curItem: LNAutoReplyVO?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
    }
    
    func update(num: Int, item: LNAutoReplyVO) {
        textEdit.isHidden = true
        voiceEdit.isHidden = true
        rejectView.isHidden = true
        
        titleLabel.text = .init(key: "B00114", num + 1)
        
        switch item.type {
        case .text:
            textEdit.isHidden = false
            textEdit.textView.text = item.textContent
        case .voice:
            voiceEdit.isHidden = false
            voiceEdit.update(item.voiceUrl, duration: item.voiceDuration)
        }
        
        commitButton.isEnabled = false
        commitButton.setBackgroundImage(nil, for: .normal)
        switch item.status {
        case .pass:
            commitButton.setTitle(.init(key: "A00240"), for: .normal)
        case .reject:
            commitButton.setTitle(.init(key: "B00121"), for: .normal)
            
            rejectLabel.text = item.reviewReason
            rejectView.isHidden = false
        case .reviewing:
            break
        }
        
        curItem = item
    }
}

extension LNAutoReplyEditViewController {
    private func commitItem(_ item: LNAutoReplyVO) {
        if item.id.isEmpty {
            LNGameMateManager.shared.createAutoReplay(item: item) { [weak self] success in
                guard let self else { return }
                guard success else { return }
                view.pushToSkillReview(cls: LNAutoReplyEditViewController.self)
            }
        } else {
            LNGameMateManager.shared.updateAutoReplay(item: item) { [weak self] success in
                guard let self else { return }
                guard success else { return }
                navigationController?.popViewController(animated: true)
            }
        }
    }
}

extension LNAutoReplyEditViewController: UITextViewDelegate, LNVoiceEditViewDelegate {
    func onVoiceChanged() {
        checkSubmit()
    }
    
    func textViewDidChange(_ textView: UITextView) {
        checkSubmit()
    }
}

extension LNAutoReplyEditViewController {
    private func checkSubmit() {
        let enable = switch curItem?.type {
        case .text:
            textEdit.text.isEmpty == false && textEdit.text != curItem?.textContent
        case .voice:
            voiceEdit.voiceInfo.0 != nil && voiceEdit.voiceInfo.1 > 0 && voiceEdit.voiceInfo.0 != curItem?.voiceUrl
        case nil:
            false
        }
        
        if commitButton.isEnabled != enable {
            commitButton.isEnabled = enable
            if enable {
                commitButton.setBackgroundImage(.primary_8, for: .normal)
            } else {
                commitButton.setBackgroundImage(nil, for: .normal)
            }
        }
    }
    
    private func setupViews() {
        title = .init(key: "B00112")
        view.backgroundColor = .primary_1
        view.onTap { [weak self] in
            guard let self else { return }
            view.endEditing(true)
        }
        
        if curItem?.id.isEmpty == false {
            let delete = UIButton()
            delete.setImage(.icDelete.withTintColor(.text_5, renderingMode: .alwaysOriginal), for: .normal)
            delete.addAction(UIAction(handler: { [weak self] _ in
                guard let self else { return }
                LNCommonAlertView.showCommonDeleteAlert { [weak self] in
                    guard let self else { return }
                    guard let curItem else { return }
                    LNGameMateManager.shared.deleteAutoReplay(id: curItem.id) { [weak self] success in
                        guard let self else { return }
                        guard success else { return }
                        navigationController?.popViewController(animated: true)
                    }
                }
            }), for: .touchUpInside)
            setRightButton(delete)
        }
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 10
        view.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(12)
        }
        
        stackView.addArrangedSubview(buildWelcomeDetailView())
        stackView.addArrangedSubview(buildReject())
        
        commitButton.layer.cornerRadius = 23.5
        commitButton.clipsToBounds = true
        commitButton.backgroundColor = .fill_4
        commitButton.setTitleColor(.text_1, for: .normal)
        commitButton.titleLabel?.font = .heading_h3
        commitButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            guard let curItem else { return }
            
            switch curItem.type {
            case .text:
                curItem.textContent = textEdit.text
                commitItem(curItem)
            case .voice:
                let (url, duration) = voiceEdit.voiceInfo
                guard let url else { return }
                showLoading()
                LNFileUploader.shared.startUpload(type: .voice, fileURL: URL(fileURLWithPath: url), progressHandler: nil)
                { [weak self] url, err in
                    dismissLoading()
                    guard let self else { return }
                    if let url, err == nil {
                        curItem.voiceUrl = url
                        curItem.voiceDuration = duration
                        commitItem(curItem)
                    } else {
                        showToast(err)
                    }
                }
            }
        }), for: .touchUpInside)
        view.addSubview(commitButton)
        commitButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(view.commonBottomInset)
            make.height.equalTo(47)
        }
    }
    
    private func buildWelcomeDetailView() -> UIView {
        editView.layer.cornerRadius = 12
        editView.backgroundColor = .fill
        
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        editView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(16)
        }
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 10
        editView.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        textEdit.delegate = self
        textEdit.maxInput = LNGameMateManager.AutoReplayMaxInput
        textEdit.placeholderLabel.text = .init(key: "B00126")
        textEdit.snp.makeConstraints { make in
            make.height.equalTo(150)
        }
        stackView.addArrangedSubview(textEdit)
        
        voiceEdit.delegate = self
        stackView.addArrangedSubview(voiceEdit)
        
        return editView
    }
    
    private func buildReject() -> UIView {
        rejectView.layer.cornerRadius = 12
        rejectView.backgroundColor = .fill
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "B00127")
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        rejectView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(16)
        }
        
        rejectLabel.font = .body_s
        rejectLabel.textColor = .text_4
        rejectView.addSubview(rejectLabel)
        rejectLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        return rejectView
    }
}

#if DEBUG

import SwiftUI

struct LNAutoReplyEditViewControllerPreview: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        LNAutoReplyEditViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
}

#Preview(body: {
    LNAutoReplyEditViewControllerPreview()
})
#endif
