//
//  LNOrderRefundViewController.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/23.
//

import Foundation
import UIKit
import SnapKit


extension UIView {
    func pushToOrderRefund(_ orderId: String) {
        let vc = LNOrderRefundViewController(orderId: orderId)
        navigationController?.pushViewController(vc, animated: true)
    }
}


class LNOrderRefundViewController: LNViewController {
    private let orderId: String
    private var curDetail: LNOrderDetailResponse?
    
    private let detailView = LNOrderDetailCardView(type: .small)
    
    private let maxUpload = 6
    private let messageInputView = LNCommonTextView()
    private let imageUploadView = LNMultiImagesUploadView()
    
    private let submitButton = UIButton()
    
    init(orderId: String) {
        self.orderId = orderId
        super.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        
        updateSubmitButton()
        reloadDetail()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNOrderRefundViewController: LNOrderManagerNotify {
    func onOrderInfoChanged(orderId: String) {
        guard orderId == self.orderId else { return }
        reloadDetail()
    }
}

extension LNOrderRefundViewController {
    private func reloadDetail() {
        LNOrderManager.shared.getOrderDetail(orderId: orderId) { [weak self] detail in
            guard let self else { return }
            guard let detail else { return }
            curDetail = detail
            update(detail)
        }
    }
    
    private func update(_ item: LNOrderDetailResponse) {
        detailView.update(item)
    }
}

extension LNOrderRefundViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        updateSubmitButton()
    }
}

extension LNOrderRefundViewController {
    private func updateSubmitButton() {
        if !messageInputView.text.isEmpty {
            submitButton.backgroundColor = .clear
            submitButton.setTitleColor(.text_5, for: .normal)
            submitButton.isEnabled = true
        } else {
            submitButton.backgroundColor = .fill_4
            submitButton.setTitleColor(.text_1, for: .normal)
            submitButton.isEnabled = false
        }
    }
}
extension LNOrderRefundViewController {
    private func setupViews() {
        view.backgroundColor = .primary_1
        title = .init(key: "A00284")
        
        let backgroundIc = UIImageView()
        backgroundIc.image = .icOrderCancelledBg
        view.addSubview(backgroundIc)
        backgroundIc.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        submitButton.setTitle(.init(key: "A00179"), for: .normal)
        submitButton.titleLabel?.font = .heading_h3
        submitButton.layer.cornerRadius = 23.5
        submitButton.layer.borderWidth = 1
        submitButton.layer.borderColor = UIColor.text_2.cgColor
        submitButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            let reason = messageInputView.text
            let attachments = imageUploadView.curFileUrls
            LNOrderManager.shared.refundOrder(orderId: orderId, reason: reason, attachments: attachments) { [weak self] success in
                guard let self else { return }
                guard success else { return }
                navigationController?.popViewController(animated: true)
            }
        }), for: .touchUpInside)
        view.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-view.safeBottomInset - 10)
            make.height.equalTo(47)
        }
        
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalTo(submitButton.snp.top)
        }
        
        let fakeView = UIView()
        scrollView.addSubview(fakeView)
        fakeView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(0)
        }
         
        scrollView.addSubview(detailView)
        detailView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalToSuperview().offset(10)
        }
        
        let container = UIView()
        container.backgroundColor = .fill
        container.layer.cornerRadius = 12
        scrollView.addSubview(container)
        container.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(detailView.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        let textView = buildTextView()
        container.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview().offset(16)
        }
        
        let photoView = buildPhotoView()
        container.addSubview(photoView)
        photoView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalTo(textView.snp.bottom).offset(16)
            make.bottom.equalToSuperview().offset(-16)
        }
        
        view.onTap { [weak self] in
            guard let self else { return }
            view.endEditing(true)
        }
    }
    
    private func buildTextView() -> UIView {
        let container = UIView()
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00180")
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        titleLabel.numberOfLines = 0
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(16)
        }
        
        let descLabel = UILabel()
        descLabel.text = .init(key: "A00181")
        descLabel.font = .body_s
        descLabel.textColor = .text_4
        descLabel.numberOfLines = 0
        container.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom).offset(2)
            make.horizontalEdges.equalToSuperview().inset(16)
        }
        
        messageInputView.delegate = self
        messageInputView.maxInput = LNOrderManager.orderRefundMaxLength
        container.addSubview(messageInputView)
        messageInputView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(descLabel.snp.bottom).offset(8)
            make.bottom.equalToSuperview()
            make.height.equalTo(150)
        }
        
        return container
    }
    
    private func buildPhotoView() -> UIView {
        let container = UIView()
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00177", maxUpload)
        titleLabel.font = .heading_h4
        titleLabel.textColor = .text_5
        container.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.horizontalEdges.equalToSuperview().inset(16)
        }
        
        let descLabel = UILabel()
        descLabel.text = .init(key: "A00178")
        descLabel.font = .body_s
        descLabel.textColor = .text_4
        container.addSubview(descLabel)
        descLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(titleLabel.snp.bottom).offset(2)
        }
        
        imageUploadView.maxPhoto = maxUpload
        container.addSubview(imageUploadView)
        imageUploadView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalTo(descLabel.snp.bottom).offset(16)
            make.bottom.equalToSuperview()
            make.height.equalTo(0).priority(.low)
        }
        
        return container
    }
}

#if DEBUG

import SwiftUI

struct LNOrderRefundViewControllerPreview: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> some UIViewController {
        LNOrderRefundViewController(orderId: "")
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { }
}

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