import 'package:autosos_flutter/model/order.dart';
import 'package:autosos_flutter/provider/providers.dart';
import 'package:autosos_flutter/router/app_router.dart';
import 'package:autosos_flutter/util/toast.dart';
import 'package:autosos_flutter/widget/multi_state_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';

/// 历史订单记录页（对应 Android RecordOrderActivity）
class OrderRecordPage extends ConsumerStatefulWidget {
  const OrderRecordPage({super.key});

  @override
  ConsumerState<OrderRecordPage> createState() => _OrderRecordPageState();
}

class _OrderRecordPageState extends ConsumerState<OrderRecordPage> {
  MultiState _state = MultiState.loading;
  List<Order> _items = [];
  String? _status;
  int _page = 1;
  bool _hasMore = true;
  bool _loadingMore = false;
  final _scroll = ScrollController();

  final _tabs = const [
    ('全部', null),
    ('已完成', 'completed'),
    ('已取消', 'cancelled'),
  ];

  @override
  void initState() {
    super.initState();
    _load(reset: true);
    _scroll.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scroll.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scroll.position.pixels >=
        _scroll.position.maxScrollExtent - 200) {
      _load();
    }
  }

  Future<void> _load({bool reset = false}) async {
    if (reset) {
      _page = 1;
      _hasMore = true;
      _items = [];
      setState(() => _state = MultiState.loading);
    }
    if (!_hasMore || _loadingMore) return;
    _loadingMore = true;
    try {
      final resp = await ref.read(orderApiProvider).historyOrders(
        page: _page,
        size: 20,
        status: _status,
      );
      if (!mounted) return;
      if (!resp.isSuccess) {
        if (reset) setState(() => _state = MultiState.error);
        Toast.error(resp.message ?? '加载失败');
        return;
      }
      final list = resp.data?.list ?? [];
      _items.addAll(list);
      _hasMore = (resp.data?.hasMore ?? false) && list.length >= 20;
      _page++;
      setState(() {
        _state = _items.isEmpty ? MultiState.empty : MultiState.success;
      });
    } catch (e) {
      if (mounted && reset) setState(() => _state = MultiState.error);
    } finally {
      _loadingMore = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('历史订单'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(44),
          child: Container(
            color: Colors.white,
            child: Row(
              children: _tabs
                  .map(
                    (t) => Expanded(
                      child: InkWell(
                        onTap: () {
                          if (_status == t.$2) return;
                          setState(() => _status = t.$2);
                          _load(reset: true);
                        },
                        child: Container(
                          height: 44,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            border: Border(
                              bottom: BorderSide(
                                color: _status == t.$2
                                    ? Theme.of(context).primaryColor
                                    : Colors.transparent,
                                width: 2,
                              ),
                            ),
                          ),
                          child: Text(
                            t.$1,
                            style: TextStyle(
                              color: _status == t.$2
                                  ? Theme.of(context).primaryColor
                                  : Colors.black87,
                              fontWeight: _status == t.$2
                                  ? FontWeight.bold
                                  : FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ),
          ),
        ),
      ),
      body: RefreshIndicator(
        onRefresh: () => _load(reset: true),
        child: MultiStateView(
          state: _state,
          emptyText: '暂无历史订单',
          onRetry: () => _load(reset: true),
          child: ListView.separated(
            controller: _scroll,
            padding: const EdgeInsets.all(12),
            itemCount: _items.length + (_hasMore ? 1 : 0),
            separatorBuilder: (_, __) => const SizedBox(height: 8),
            itemBuilder: (ctx, i) {
              if (i >= _items.length) {
                return const Padding(
                  padding: EdgeInsets.all(16),
                  child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
                );
              }
              return _RecordCard(
                order: _items[i],
                onTap: () => context.push(
                  '${Routes.orderComplete}/${_items[i].id}',
                ),
              );
            },
          ),
        ),
      ),
    );
  }
}

class _RecordCard extends StatelessWidget {
  final Order order;
  final VoidCallback onTap;
  const _RecordCard({required this.order, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final fmt = DateFormat('yyyy-MM-dd HH:mm');
    final isCompleted = order.status == OrderStatus.completed;
    return Material(
      color: Colors.white,
      borderRadius: BorderRadius.circular(8),
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 2,
                    ),
                    decoration: BoxDecoration(
                      color: isCompleted
                          ? Colors.green.shade50
                          : Colors.grey.shade200,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      order.status.label,
                      style: TextStyle(
                        color: isCompleted
                            ? Colors.green.shade700
                            : Colors.grey.shade600,
                        fontSize: 12,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(order.serviceType,
                      style: const TextStyle(
                          fontSize: 14, fontWeight: FontWeight.w600)),
                  const Spacer(),
                  Text(
                    '¥${order.amount.toStringAsFixed(2)}',
                    style: const TextStyle(
                      color: Colors.red,
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text('订单号：${order.orderNo}',
                  style: const TextStyle(fontSize: 13)),
              if (order.address != null && order.address!.isNotEmpty) ...[
                const SizedBox(height: 4),
                Text('地点：${order.address}',
                    style: TextStyle(
                        fontSize: 13, color: Colors.grey.shade700)),
              ],
              const SizedBox(height: 4),
              Text('时间：${fmt.format(order.createdAt)}',
                  style: TextStyle(fontSize: 12, color: Colors.grey.shade500)),
            ],
          ),
        ),
      ),
    );
  }
}
