//
//  DepositOrderCardCell.swift
//  suixinkan
//

import SnapKit
import UIKit

struct DepositOrderCardActions {
    var onRefund: (() -> Void)?
    var onPartialRefund: (() -> Void)?
    var onVerify: (() -> Void)?
    var onCallPhone: (() -> Void)?
    var onTap: (() -> Void)?
}

/// 店铺订单卡片，严格对齐 Android `DepositOrderCard`。
final class DepositOrderCardCell: UITableViewCell {
    static let reuseIdentifier = "DepositOrderCardCell"

    private let cardView = UIView()
    private let contentStack = UIStackView()
    private let headerRow = UIStackView()
    private let orderNumberLabel = UILabel()
    private let statusBadge = DepositOrderStatusBadgeView()
    private let createdAtLabel = UILabel()
    private let typeChip = OrderTypeChipView()
    private let infoStack = UIStackView()
    private let phoneRow = OrderPhoneRowView(style: .deposit)
    private let actionRow = UIStackView()
    private let refundButton = OrderActionButton(title: "退款", style: .destructiveLight)
    private let partialRefundButton = OrderActionButton(title: "部分退款", style: .dangerFilled)
    private let verifyButton = OrderActionButton(title: "核销", style: .primaryFilled)

    private var actions = DepositOrderCardActions()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        setupUI()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure(item: StoreOrderItem, actions: DepositOrderCardActions) {
        self.actions = actions
        orderNumberLabel.text = "订单号: \(item.orderNumber)"
        statusBadge.apply(status: item.orderStatus, text: item.orderStatusName)
        createdAtLabel.text = item.createdAt
        typeChip.apply(text: item.orderTypeLabel)

        infoStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
        addInfoRow(title: "项目名称", value: item.projectName)
        addInfoRow(title: "订单金额", value: "¥ \(item.actualPayAmount)", primary: true)
        addInfoRow(title: "付款时间", value: item.payTime.isEmpty ? "--" : item.payTime)
        addInfoRow(title: "完成时间", value: item.completeTime.isEmpty ? "--" : item.completeTime)
        addInfoRow(title: "用户 UID", value: String(item.userId))
        infoStack.addArrangedSubview(phoneRow)
        phoneRow.apply(phone: item.phone)
        phoneRow.onTap = { [weak self] in self?.actions.onCallPhone?() }

        let showVerify = item.orderType == StoreOrderType.offlineProduct && item.orderStatus == 20
        verifyButton.isHidden = !showVerify
    }

    private func setupUI() {
        cardView.backgroundColor = AppColor.cardBackground
        cardView.layer.cornerRadius = OrderTokens.cardRadius
        let tap = UITapGestureRecognizer(target: self, action: #selector(cardTapped))
        cardView.addGestureRecognizer(tap)

        orderNumberLabel.font = .app(.body)
        orderNumberLabel.textColor = OrderTokens.orderNumber
        createdAtLabel.font = .app(.caption)
        createdAtLabel.textColor = OrderTokens.timestamp

        headerRow.axis = .horizontal
        headerRow.alignment = .center
        headerRow.distribution = .equalSpacing
        headerRow.addArrangedSubview(orderNumberLabel)
        headerRow.addArrangedSubview(statusBadge)

        infoStack.axis = .vertical
        infoStack.spacing = AppSpacing.xxs

        actionRow.axis = .horizontal
        actionRow.spacing = OrderTokens.cardGap
        actionRow.distribution = .fillEqually
        actionRow.addArrangedSubview(refundButton)
        actionRow.addArrangedSubview(partialRefundButton)
        refundButton.addTarget(self, action: #selector(refundTapped), for: .touchUpInside)
        partialRefundButton.addTarget(self, action: #selector(partialRefundTapped), for: .touchUpInside)
        verifyButton.addTarget(self, action: #selector(verifyTapped), for: .touchUpInside)

        contentStack.axis = .vertical
        contentStack.spacing = OrderTokens.cardGap
        [headerRow, createdAtLabel, typeChip, infoStack, actionRow, verifyButton].forEach {
            contentStack.addArrangedSubview($0)
        }

        contentView.addSubview(cardView)
        cardView.addSubview(contentStack)
        cardView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(
                UIEdgeInsets(top: 0, left: AppSpacing.md, bottom: OrderTokens.cardGap, right: AppSpacing.md)
            )
        }
        contentStack.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(OrderTokens.cardPadding)
        }
    }

    private func addInfoRow(title: String, value: String, primary: Bool = false) {
        let row = OrderInfoRowView()
        row.apply(title: title, value: value, usesPrimaryValue: primary)
        infoStack.addArrangedSubview(row)
    }

    @objc private func refundTapped() { actions.onRefund?() }
    @objc private func partialRefundTapped() { actions.onPartialRefund?() }
    @objc private func verifyTapped() { actions.onVerify?() }
    @objc private func cardTapped() { actions.onTap?() }
}
