//
//  StatisticsSummaryCardView.swift
//  suixinkan
//

import SnapKit
import UIKit

/// 数据统计汇总卡片，包含日期行、周期 chip 与 5 张指标卡。
final class StatisticsSummaryCardView: UIView {

    var onPeriodSelected: ((String) -> Void)?

    private let datePrefixLabel = UILabel()
    private let dateValueLabel = UILabel()
    private let periodStack = UIStackView()
    private var periodButtons: [StatisticsPeriodButton] = []

    private let totalAmountCard = StatisticsStatCardView(
        title: "订单总金额",
        valueColor: AppColor.online,
        backgroundColor: AppColor.successBackground,
        iconName: "icon_data_statistics_total_amount"
    )
    private let totalOrderCard = StatisticsStatCardView(
        title: "订单总数",
        valueColor: UIColor(hex: 0x7F00FF),
        backgroundColor: UIColor(hex: 0xEBD8FF),
        iconName: "icon_data_statistics_total_order"
    )
    private let receivedCard = StatisticsStatCardView(
        title: "实收金额",
        valueColor: AppColor.online,
        backgroundColor: AppColor.warningBackground,
        iconName: "icon_data_statistics_get_amount"
    )
    private let averageCard = StatisticsStatCardView(
        title: "客单价",
        valueColor: AppColor.primary,
        backgroundColor: AppColor.primaryLight,
        iconName: "icon_data_statistics_average_amount"
    )
    private let refundCard = StatisticsStatCardView(
        title: "退款金额",
        valueColor: AppColor.danger,
        backgroundColor: AppColor.dangerBackground,
        iconName: "icon_data_statistics_refund_amount"
    )

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

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

    func apply(selectedPeriod: String, selectedPeriodTime: String, summary: StatisticsSummaryResponse?) {
        dateValueLabel.text = selectedPeriodTime
        periodButtons.forEach { $0.isSelected = $0.periodTitle == selectedPeriod }

        totalAmountCard.configure(value: "¥\(summary?.orderAmountSum ?? "0")")
        totalOrderCard.configure(value: "\(summary?.orderCount ?? 0)单")
        receivedCard.configure(value: "¥\(summary?.receivedAmountSum ?? "0")")
        averageCard.configure(value: "¥\(summary?.orderPriceAvg ?? "0")")
        refundCard.configure(value: "¥\(summary?.refundAmountSum ?? "0")")
    }

    private func setupUI() {
        backgroundColor = AppColor.cardBackground
        layer.cornerRadius = AppRadius.lg
        clipsToBounds = true

        datePrefixLabel.text = "已选日期："
        datePrefixLabel.font = .app(.body)
        datePrefixLabel.textColor = AppColor.textPrimary

        dateValueLabel.font = .app(.body)
        dateValueLabel.textColor = AppColor.primary
        dateValueLabel.numberOfLines = 1

        periodStack.axis = .horizontal
        periodStack.distribution = .equalSpacing
        periodStack.alignment = .fill

        StatisticsSummaryPeriod.allCases.forEach { period in
            let button = StatisticsPeriodButton()
            button.periodTitle = period.rawValue
            button.addTarget(self, action: #selector(periodTapped(_:)), for: .touchUpInside)
            periodButtons.append(button)
            periodStack.addArrangedSubview(button)
        }

        let row1 = UIStackView(arrangedSubviews: [totalOrderCard, receivedCard])
        row1.axis = .horizontal
        row1.spacing = AppSpacing.sm
        row1.distribution = .fillEqually

        let row2 = UIStackView(arrangedSubviews: [averageCard, refundCard])
        row2.axis = .horizontal
        row2.spacing = AppSpacing.sm
        row2.distribution = .fillEqually

        let cardStack = UIStackView(arrangedSubviews: [totalAmountCard, row1, row2])
        cardStack.axis = .vertical
        cardStack.spacing = AppSpacing.sm

        let dateRow = UIStackView(arrangedSubviews: [datePrefixLabel, dateValueLabel, UIView()])
        dateRow.axis = .horizontal
        dateRow.alignment = .center
        dateRow.spacing = 0

        let contentStack = UIStackView(arrangedSubviews: [dateRow, periodStack, cardStack])
        contentStack.axis = .vertical
        contentStack.spacing = AppSpacing.sm

        addSubview(contentStack)
        contentStack.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(AppSpacing.md)
        }
    }

    @objc private func periodTapped(_ sender: StatisticsPeriodButton) {
        onPeriodSelected?(sender.periodTitle)
    }
}
