//
//  StoreAdminOrderListView.swift
//  suixinkan
//
//  Created by Codex on 2026/6/29.
//

import SwiftUI

/// 店长角色订单 Tab 列表，对齐 Android DepositOrderListScreen。
struct StoreAdminOrderListView: View {
    @EnvironmentObject private var accountContext: AccountContext
    @EnvironmentObject private var router: RouterPath
    @Environment(\.ordersAPI) private var ordersAPI
    @EnvironmentObject private var toastCenter: ToastCenter
    @Environment(\.globalLoading) private var globalLoading
    @Environment(\.openURL) private var openURL

    @StateObject private var viewModel = StoreAdminOrderListViewModel()

    @State private var showDateFilterSheet = false
    @State private var refundOrder: StoreOrderListItem?
    @State private var refundMode: OrderRefundMode = .full
    @State private var showScanner = false
    @State private var appliedSearchQuery = ""

    private var currentStoreId: Int? { accountContext.currentStore?.id }

    var body: some View {
        Group {
            if currentStoreId == nil {
                AppContentUnavailableView(
                    "缺少门店上下文",
                    systemImage: "storefront",
                    description: Text("请先选择门店后查看订单。")
                )
            } else {
                listContent
            }
        }
        .background(AppDesign.orderPageBackground.ignoresSafeArea())
        .navigationTitle("订单")
        .navigationBarTitleDisplayMode(.inline)
        .searchable(text: $viewModel.searchPhone, prompt: "输入游客手机号")
        .onSubmit(of: .search) {
            appliedSearchQuery = OrderListSearchBehavior.normalized(viewModel.searchPhone)
            Task { await reload() }
        }
        .onChange(of: viewModel.searchPhone) { newValue in
            guard OrderListSearchBehavior.shouldReloadAfterClear(newText: newValue, appliedQuery: appliedSearchQuery) else { return }
            appliedSearchQuery = ""
            Task { await reload() }
        }
        .task { await reload() }
        .onChange(of: accountContext.currentStore?.id) { _ in
            Task { await reload() }
        }
        .sheet(isPresented: $showDateFilterSheet) {
            DateRangePickerSheet(
                initialStartDate: viewModel.filterStartDate,
                initialEndDate: viewModel.filterEndDate
            ) { start, end in
                viewModel.filterStartDate = start
                viewModel.filterEndDate = end
                Task { await reload() }
            }
        }
        .sheet(item: $refundOrder) { order in
            StoreOrderRefundDialogView(
                orderNumber: order.orderNumber,
                actualPayAmount: order.actualPayAmount,
                initialMode: refundMode,
                onDismiss: { refundOrder = nil },
                onConfirm: { mode, amount, reason in
                    Task {
                        do {
                            try await viewModel.refund(
                                api: ordersAPI,
                                storeId: currentStoreId,
                                orderNumber: order.orderNumber,
                                mode: mode,
                                amount: amount,
                                reason: reason
                            )
                            refundOrder = nil
                            toastCenter.show("退款申请已提交")
                            await reload(showLoading: false)
                        } catch {
                            toastCenter.show(error.localizedDescription)
                        }
                    }
                }
            )
        }
        .fullScreenCover(isPresented: $showScanner) {
            OrderScannerPage(
                onClose: { showScanner = false },
                onSuccess: { _ in
                    showScanner = false
                    toastCenter.show("核销成功")
                    Task { await reload(showLoading: false) }
                },
                onFailure: { error in
                    showScanner = false
                    toastCenter.show(error.localizedDescription)
                }
            )
        }
    }

    private var listContent: some View {
        ScrollView {
            LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
                Section {
                    LazyVStack(spacing: 12) {
                        if viewModel.loading && viewModel.orders.isEmpty {
                            ProgressView().frame(maxWidth: .infinity).padding(.vertical, 40)
                        } else if viewModel.orders.isEmpty {
                            AppContentUnavailableView("暂无订单", systemImage: "tray")
                                .frame(minHeight: 260)
                        } else {
                            ForEach(viewModel.orders) { item in
                                StoreAdminOrderCardView(
                                    item: item,
                                    onTap: { handleOrderTap(item) },
                                    onRefund: {
                                        refundMode = .full
                                        refundOrder = item
                                    },
                                    onPartialRefund: {
                                        refundMode = .partial
                                        refundOrder = item
                                    },
                                    onVerify: { showScanner = true },
                                    onCallPhone: { dialPhone(item.phone) }
                                )
                                .onAppear {
                                    guard item.id == viewModel.orders.last?.id else { return }
                                    Task { await loadMore() }
                                }
                            }
                            if viewModel.loadingMore {
                                ProgressView().frame(maxWidth: .infinity).padding(.vertical, 8)
                            }
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.bottom, 16)
                } header: {
                    OrderListHeaderView(
                        filterTitle: viewModel.currentFilterTitle,
                        timeFilterTitle: OrderDateRangeFormatter.displayText(
                            start: viewModel.filterStartDate,
                            end: viewModel.filterEndDate
                        ),
                        statusFilters: OrderFilters.storeAdminStatusFilters,
                        selectedStatus: viewModel.selectedStatus,
                        onStatusSelected: { status in
                            viewModel.selectedStatus = status
                            Task { await reload() }
                        },
                        onTimeFilterTap: { showDateFilterSheet = true }
                    )
                }
            }
        }
        .refreshable { await reload(showLoading: false) }
    }

    private func handleOrderTap(_ item: StoreOrderListItem) {
        if item.orderType == StoreOrderType.multiTravelShoot {
            router.navigate(to: .orders(.depositDetail(orderNumber: item.orderNumber)))
        } else {
            toastCenter.show("该订单不可查看详情")
        }
    }

    private func reload(showLoading: Bool = true) async {
        do {
            try await globalLoading.withOptionalLoading(showLoading && viewModel.orders.isEmpty, message: "加载中...") {
                try await viewModel.reload(api: ordersAPI, storeId: currentStoreId, showLoading: showLoading)
            }
        } catch {
            toastCenter.show(error.localizedDescription)
        }
    }

    private func loadMore() async {
        do {
            try await viewModel.loadMore(api: ordersAPI, storeId: currentStoreId)
        } catch {
            toastCenter.show(error.localizedDescription)
        }
    }

    private func dialPhone(_ phone: String) {
        let trimmed = phone.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let url = URL(string: "tel:\(trimmed)") else { return }
        openURL(url)
    }
}

/// 店长订单卡片，对齐 Android DepositOrderCard。
private struct StoreAdminOrderCardView: View {
    let item: StoreOrderListItem
    let onTap: () -> Void
    let onRefund: () -> Void
    let onPartialRefund: () -> Void
    let onVerify: () -> Void
    let onCallPhone: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Button(action: onTap) {
                VStack(alignment: .leading, spacing: 8) {
                    HStack {
                        Text("订单号：\(item.orderNumber)")
                            .font(.system(size: 14))
                            .foregroundStyle(.black)
                        Spacer()
                        OrderStatusChip(text: item.orderStatusName, status: item.orderStatus)
                    }
                    OrderInfoRow(title: "项目名称", value: item.projectName.isEmpty ? "--" : item.projectName)
                    OrderInfoRow(title: "订单金额", value: "¥\(item.actualPayAmount)", valueColor: AppDesign.primary)
                    OrderInfoRow(title: "付款时间", value: item.payTime.isEmpty ? "--" : item.payTime)
                    OrderInfoRow(title: "完成时间", value: item.completeTime.isEmpty ? "--" : item.completeTime)
                    OrderInfoRow(title: "用户 UID", value: "\(item.userId)")
                    OrderInfoRow(title: "手机号", value: OrderListUI.maskPhone(item.phone)) {
                        HStack(spacing: 7) {
                            Text(OrderListUI.maskPhone(item.phone))
                                .font(.system(size: 14, weight: .medium))
                            OrderPhoneCallButton(action: onCallPhone)
                        }
                    }
                }
            }
            .buttonStyle(.plain)

            HStack(spacing: 12) {
                OrderActionButton(
                    title: "退款",
                    textColor: AppDesign.orderRefundText,
                    backgroundColor: AppDesign.orderRefundBackground,
                    action: onRefund
                )
                OrderActionButton(
                    title: "部分退款",
                    textColor: AppDesign.orderLabelColor,
                    backgroundColor: .white,
                    action: onPartialRefund
                )
                .overlay(RoundedRectangle(cornerRadius: 8).stroke(AppDesign.orderBorderLight, lineWidth: 1))
            }

            if item.orderType == StoreOrderType.offlineProduct {
                OrderActionButton(title: "核销", action: onVerify)
            }
        }
        .padding(16)
        .background(.white, in: RoundedRectangle(cornerRadius: 12))
    }
}
