//
//  LNIMChatOrderMessageCell.swift
//  Lanu
//
//  Created by OneeChan on 2025/12/26.
//

import Foundation
import UIKit
import SnapKit


class LNIMChatOrderMessageCell: UITableViewCell {
    private let statusIc = UIImageView()
    private let statusLabel = UILabel()
    
    private let tipsLabel = UILabel()
    
    private let gameIc = UIImageView()
    private let billInfoLabel = UILabel()
    
    private let menuButton = UIButton()
    
    private var curItem: LNIMMessageData?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        setupViews()
    }
    
    func update(_ data: LNIMMessageData, viewModel: LNIMChatViewModel) {
        guard let order: LNIMOrderMessage = data.decodeCustomMessage() else { return }
        
        let isCreator = order.buyerUserNo.isMyUid
        
        tipsLabel.isHidden = false
        menuButton.isHidden = true
        
        gameIc.sd_setImage(with: URL(string: order.categoryIcon))
        billInfoLabel.text = "\(order.bizCategoryName)/\(order.unit) x \(order.purchaseQty)"
        
        curItem = data
        
        let ui = order.statusUI
        statusLabel.text = ui.title
        statusIc.image = ui.icon
        
        if order.refundApply {
            if isCreator {
                tipsLabel.text = .init(key: "A00050")
            } else {
                tipsLabel.text = .init(key: "A00052")
            }
            return
        }
        
        switch order.status {
        case .created, .waitingForAccept:
            if isCreator {
                tipsLabel.text = .init(key: "A00054")
            } else {
                tipsLabel.text = .init(key: "A00056", order.customerRemark)
            }
        case .completed:
            if isCreator {
                tipsLabel.text = .init(key: "A00058")
            } else {
                tipsLabel.text = .init(key: "A00059")
            }
        case .refunded:
            tipsLabel.text = .init(key: "A00061")
        case .accepted:
            if isCreator {
                tipsLabel.text = .init(key: "A00063")
            } else {
                tipsLabel.isHidden = true
                menuButton.isHidden = false
                menuButton.setTitle(.init(key: "A00064"), for: .normal)
            }
        case .rejected:
            if isCreator {
                tipsLabel.text = .init(key: "A00066")
            } else {
                tipsLabel.text = .init(key: "A00067")
            }
        case .servicing:
            tipsLabel.text = .init(key: "A00075")
            
            if !isCreator {
                menuButton.isHidden = false
                menuButton.setTitle(.init(key: "A00069"), for: .normal)
            }
        case .serviceDone:
            if isCreator {
                tipsLabel.text = .init(key: "A00058")
                menuButton.isHidden = false
                menuButton.setTitle(.init(key: "A00069"), for: .normal)
            } else {
                tipsLabel.text = .init(key: "A00074")
            }
        case .cancelled:
            if isCreator {
                tipsLabel.text = .init(key: "A00072")
            } else {
                tipsLabel.text = .init(key: "A00073")
            }
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNIMChatOrderMessageCell {
    private func setupViews() {
        backgroundColor = .clear
        
        let container = UIView()
        container.backgroundColor = .fill
        container.layer.cornerRadius = 12
        contentView.addSubview(container)
        container.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-8)
        }
        
        let mainStackView = UIStackView()
        mainStackView.axis = .vertical
        mainStackView.spacing = 12
        container.addSubview(mainStackView)
        mainStackView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(12)
            make.verticalEdges.equalToSuperview().inset(12)
        }
        
        let infoStackView = UIStackView()
        infoStackView.axis = .vertical
        infoStackView.spacing = 6
        infoStackView.onTap { [weak self] in
            guard let self else { return }
            guard let order: LNIMOrderMessage = curItem?.decodeCustomMessage() else { return }
            if order.buyerUserNo.isMyUid {
                pushToOrderList()
            } else {
                pushToOrderRecord()
            }
        }
        mainStackView.addArrangedSubview(infoStackView)
        
        infoStackView.addArrangedSubview(buildStatusView())
        infoStackView.addArrangedSubview(buildTipsView())
        infoStackView.addArrangedSubview(buildLine())
        infoStackView.addArrangedSubview(buildBillInfoView())
        
        mainStackView.addArrangedSubview(buildMenu())
    }
    
    private func buildStatusView() -> UIView {
        let container = UIView()
        container.snp.makeConstraints { make in
            make.height.equalTo(24)
        }
        
        container.addSubview(statusIc)
        statusIc.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview()
            make.width.height.equalTo(24)
        }
        
        statusLabel.font = .heading_h4
        statusLabel.textColor = .text_5
        container.addSubview(statusLabel)
        statusLabel.snp.makeConstraints { make in
            make.leading.equalTo(statusIc.snp.trailing).offset(6)
            make.centerY.equalToSuperview()
        }
        
        let arrow = UIImageView.arrowImageView(size: 16)
        arrow.tintColor = .text_4
        container.addSubview(arrow)
        arrow.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview()
        }
        
        return container
    }
    
    private func buildTipsView() -> UIView {
        tipsLabel.font = .body_xs
        tipsLabel.textColor = .text_3
        tipsLabel.numberOfLines = 0
        
        return tipsLabel
    }
    
    private func buildLine() -> UIView {
        let line = UIView()
        line.backgroundColor = .fill_2
        line.snp.makeConstraints { make in
            make.height.equalTo(1)
        }
        
        return line
    }
    
    private func buildBillInfoView() -> UIView {
        let container = UIView()
        container.snp.makeConstraints { make in
            make.height.equalTo(20)
        }
        
        let backgroundIc = UIImageView()
        backgroundIc.layer.cornerRadius = 10
        backgroundIc.image = .primary_7
        backgroundIc.clipsToBounds = true
        container.addSubview(backgroundIc)
        backgroundIc.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        gameIc.backgroundColor = .fill
        gameIc.layer.cornerRadius = 9
        gameIc.clipsToBounds = true
        backgroundIc.addSubview(gameIc)
        gameIc.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(18)
        }
        
        billInfoLabel.font = .body_s
        billInfoLabel.textColor = .text_4
        container.addSubview(billInfoLabel)
        billInfoLabel.snp.makeConstraints { make in
            make.leading.equalTo(backgroundIc.snp.trailing).offset(6)
            make.centerY.equalToSuperview()
        }
        
        return container
    }
    
    private func buildMenu() -> UIView {
        menuButton.layer.cornerRadius = 20
        menuButton.setBackgroundImage(.primary_8, for: .normal)
        menuButton.clipsToBounds = true
        menuButton.setTitleColor(.text_1, for: .normal)
        menuButton.titleLabel?.font = .heading_h3
        menuButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            guard let order: LNIMOrderMessage = curItem?.decodeCustomMessage() else { return }
            
            let isCreator = order.buyerUserNo.isMyUid
            
            switch order.status {
            case .accepted:
                if !isCreator {
                    LNOrderManager.shared.startOrderService(orderId: order.orderId) { success in }
                }
            case .servicing:
                if !isCreator {
                    LNOrderManager.shared.finishOrderService(orderId: order.orderId) { success in }
                }
            case .serviceDone:
                if isCreator {
                    LNCommonAlertView.showFinishOrderAlert(orderId: order.orderId)
                }
            default: break
            }
        }), for: .touchUpInside)
        menuButton.snp.makeConstraints { make in
            make.height.equalTo(40)
        }
        
        return menuButton
    }
}

