//
//  OrderFilterBarView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 订单筛选栏：搜索 + 状态下拉 + 日期筛选，对齐 Android Header。
final class OrderFilterBarView: UIView {

    var onSearchChanged: ((String) -> Void)?
    var onSearchSubmitted: (() -> Void)?
    var onFilterSelected: ((Int, Int) -> Void)?
    var onDateRangeTap: (() -> Void)?

    private let searchContainer = UIView()
    private let searchIconView = UIImageView(image: UIImage(systemName: "magnifyingglass"))
    private let searchField = UITextField()
    private let divider = UIView()
    private let filterPill = OrderFilterPillControl()
    private let datePill = OrderFilterPillControl()

    private var isStoreMode = false

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = AppColor.cardBackground
        setupUI()
    }

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

    func configure(isStoreMode: Bool, filterLabel: String, dateRangeText: String, searchText: String) {
        self.isStoreMode = isStoreMode
        searchField.placeholder = isStoreMode ? "输入游客手机号" : "输入手机号搜索"
        searchField.attributedPlaceholder = NSAttributedString(
            string: searchField.placeholder ?? "",
            attributes: [.foregroundColor: OrderTokens.searchPlaceholder]
        )
        searchField.text = searchText
        filterPill.pillTitle = filterLabel
        datePill.pillTitle = dateRangeText
        rebuildFilterMenu(selectedLabel: filterLabel)
    }

    private func setupUI() {
        searchContainer.backgroundColor = OrderTokens.filterBackground
        searchContainer.layer.cornerRadius = OrderTokens.pillRadius
        searchContainer.clipsToBounds = true

        searchIconView.tintColor = .gray
        searchIconView.contentMode = .scaleAspectFit

        searchField.font = .app(.body)
        searchField.textColor = AppColor.textPrimary
        searchField.keyboardType = .phonePad
        searchField.returnKeyType = .search
        searchField.borderStyle = .none
        searchField.backgroundColor = .clear
        searchField.delegate = self
        searchField.addTarget(self, action: #selector(searchChanged), for: .editingChanged)

        divider.backgroundColor = AppColor.border

        filterPill.showsMenuAsPrimaryAction = true

        datePill.setTrailingSystemImage("calendar")
        datePill.addTarget(self, action: #selector(dateTapped), for: .touchUpInside)

        addSubview(searchContainer)
        searchContainer.addSubview(searchIconView)
        searchContainer.addSubview(searchField)
        addSubview(divider)
        addSubview(filterPill)
        addSubview(datePill)

        searchContainer.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview().inset(AppSpacing.md)
            make.height.equalTo(OrderTokens.searchHeight)
        }
        searchIconView.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(AppSpacing.sm)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(18)
        }
        searchField.snp.makeConstraints { make in
            make.leading.equalTo(searchIconView.snp.trailing).offset(10)
            make.trailing.equalToSuperview().inset(AppSpacing.sm)
            make.centerY.equalToSuperview()
        }
        divider.snp.makeConstraints { make in
            make.top.equalTo(searchContainer.snp.bottom).offset(AppSpacing.md)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(OrderTokens.dividerHeight)
        }
        filterPill.snp.makeConstraints { make in
            make.top.equalTo(divider.snp.bottom).offset(AppSpacing.md)
            make.leading.equalToSuperview().inset(AppSpacing.md)
            make.bottom.equalToSuperview().inset(AppSpacing.md)
        }
        datePill.snp.makeConstraints { make in
            make.top.bottom.width.equalTo(filterPill)
            make.leading.equalTo(filterPill.snp.trailing).offset(OrderTokens.filterGap)
            make.trailing.equalToSuperview().inset(AppSpacing.md)
        }
    }

    private func rebuildFilterMenu(selectedLabel: String) {
        let items: [(String, Int, Int)] = isStoreMode
            ? StoreOrderFilter.allCases.map { ($0.label, $0.tabIndex, 0) }
            : PhotographerOrderFilter.allCases.map { ($0.label, $0.tabIndex, $0.rTabIndex) }

        let actions = items.map { title, tab, rTab in
            UIAction(title: title, state: title == selectedLabel ? .on : .off) { [weak self] _ in
                guard let self else { return }
                self.filterPill.pillTitle = title
                self.rebuildFilterMenu(selectedLabel: title)
                self.onFilterSelected?(tab, rTab)
            }
        }
        filterPill.menu = UIMenu(title: "", options: .displayInline, children: actions)
    }

    @objc private func searchChanged() {
        onSearchChanged?(searchField.text ?? "")
    }

    @objc private func dateTapped() {
        onDateRangeTap?()
    }
}

extension OrderFilterBarView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        onSearchSubmitted?()
        return true
    }
}
