//
//  OrderSourceLeadContentView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 带客单摘要内容，对齐 Android `SourceLeadContent`。
final class OrderSourceLeadContentView: UIView {

    var onCallPhone: ((String) -> Void)?
    var onImageTap: (([String], Int) -> Void)?

    private let phoneRow = UIStackView()
    private let phoneTitleLabel = UILabel()
    private let phoneValueLabel = UILabel()
    private let phoneSpacerView = UIView()
    private let remarkLabel = UILabel()
    private let imageRow = UIStackView()
    private let emptyImageLabel = UILabel()

    private var currentImages: [String] = []

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

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

    /// 应用带客单展示内容。
    func apply(lead: OrderSourceLead, compact: Bool, enablePhoneCall: Bool = true) {
        let phone = lead.userPhone.trimmingCharacters(in: .whitespacesAndNewlines)
        phoneRow.isHidden = phone.isEmpty
        phoneValueLabel.text = phone
        phoneValueLabel.textColor = enablePhoneCall ? AppColor.primary : AppColor.text333
        phoneValueLabel.isUserInteractionEnabled = enablePhoneCall && !phone.isEmpty

        let remark = lead.remark.trimmingCharacters(in: .whitespacesAndNewlines)
        remarkLabel.isHidden = remark.isEmpty
        remarkLabel.text = remark
        remarkLabel.font = compact ? .systemFont(ofSize: 12) : .systemFont(ofSize: 13)
        remarkLabel.numberOfLines = compact ? 2 : 4

        imageRow.arrangedSubviews.forEach { $0.removeFromSuperview() }
        emptyImageLabel.isHidden = true
        if lead.images.isEmpty {
            if !compact {
                emptyImageLabel.isHidden = false
            }
        } else {
            currentImages = lead.images
            lead.images.prefix(3).enumerated().forEach { index, url in
                let imageView = UIImageView()
                imageView.contentMode = .scaleAspectFill
                imageView.clipsToBounds = true
                imageView.layer.cornerRadius = 6
                imageView.backgroundColor = OrderTokens.sourceLeadPlaceholder
                imageView.loadRemoteImage(urlString: url, placeholderColor: OrderTokens.sourceLeadPlaceholder)
                imageView.isUserInteractionEnabled = true
                imageView.tag = index
                imageView.addGestureRecognizer(
                    UITapGestureRecognizer(target: self, action: #selector(imageTapped(_:)))
                )
                imageRow.addArrangedSubview(imageView)
                imageView.snp.makeConstraints { make in
                    make.height.equalTo(imageView.snp.width)
                }
            }
            let placeholders = max(0, 3 - min(lead.images.count, 3))
            if placeholders > 0 {
                (0..<placeholders).forEach { _ in
                    let spacer = UIView()
                    imageRow.addArrangedSubview(spacer)
                    spacer.snp.makeConstraints { make in
                        make.height.equalTo(spacer.snp.width)
                    }
                }
            }
        }
        imageRow.isHidden = compact && lead.images.isEmpty
    }

    private func setupUI() {
        phoneRow.axis = .horizontal
        phoneRow.alignment = .center
        phoneRow.spacing = 10
        phoneTitleLabel.text = "客户手机号"
        phoneTitleLabel.font = .systemFont(ofSize: 12)
        phoneTitleLabel.textColor = AppColor.text666
        phoneTitleLabel.setContentHuggingPriority(.required, for: .horizontal)
        phoneTitleLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        phoneValueLabel.font = .systemFont(ofSize: 13, weight: .medium)
        phoneValueLabel.lineBreakMode = .byTruncatingTail
        phoneValueLabel.setContentHuggingPriority(.required, for: .horizontal)
        phoneValueLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        phoneValueLabel.addGestureRecognizer(
            UITapGestureRecognizer(target: self, action: #selector(phoneTapped))
        )
        phoneSpacerView.setContentHuggingPriority(.defaultLow, for: .horizontal)
        phoneSpacerView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        phoneRow.addArrangedSubview(phoneTitleLabel)
        phoneRow.addArrangedSubview(phoneValueLabel)
        phoneRow.addArrangedSubview(phoneSpacerView)

        remarkLabel.textColor = AppColor.text333
        remarkLabel.lineBreakMode = .byTruncatingTail

        imageRow.axis = .horizontal
        imageRow.spacing = 8
        imageRow.distribution = .fillEqually

        emptyImageLabel.text = "暂无图片"
        emptyImageLabel.font = .systemFont(ofSize: 12)
        emptyImageLabel.textColor = AppColor.text666
        emptyImageLabel.textAlignment = .center
        emptyImageLabel.backgroundColor = OrderTokens.sourceLeadPlaceholder
        emptyImageLabel.layer.cornerRadius = 6
        emptyImageLabel.clipsToBounds = true

        let stack = UIStackView(arrangedSubviews: [phoneRow, remarkLabel, imageRow, emptyImageLabel])
        stack.axis = .vertical
        stack.spacing = 10
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        emptyImageLabel.snp.makeConstraints { make in
            make.height.equalTo(72)
        }
    }

    @objc private func phoneTapped() {
        let phone = phoneValueLabel.text?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
        guard !phone.isEmpty else { return }
        onCallPhone?(phone)
    }

    @objc private func imageTapped(_ gesture: UITapGestureRecognizer) {
        guard let imageView = gesture.view as? UIImageView else { return }
        onImageTap?(currentImages, imageView.tag)
    }
}
