import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';

import '../../../../controller/auth/captin/history_captain.dart';
import 'package:sefer_driver/views/widgets/mydialoug.dart';

class HistoryCaptain extends StatelessWidget {
  const HistoryCaptain({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(HistoryCaptainController());

    return Scaffold(
      backgroundColor: Colors.grey[100], // A softer background color
      appBar: AppBar(
        title: Text('Ride History'.tr),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 1,
      ),
      body: GetBuilder<HistoryCaptainController>(
        builder: (controller) {
          if (controller.isloading) {
            return const Center(child: CircularProgressIndicator());
          }

          if (controller.historyData['message'].isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.history_toggle_off,
                      size: 80, color: Colors.grey[400]),
                  const SizedBox(height: 16),
                  Text(
                    'No Rides Yet'.tr,
                    style: Theme.of(context)
                        .textTheme
                        .headlineSmall
                        ?.copyWith(color: Colors.grey[600]),
                  ),
                ],
              ),
            );
          }

          // 动画: Wrap ListView with AnimationLimiter for staggered animations
          return AnimationLimiter(
            child: ListView.builder(
              padding: const EdgeInsets.all(16.0),
              itemCount: controller.historyData['message'].length,
              itemBuilder: (BuildContext context, int index) {
                var trip = controller.historyData['message'][index];

                // 动画: Apply animation to each list item
                return AnimationConfiguration.staggeredList(
                  position: index,
                  duration: const Duration(milliseconds: 375),
                  child: SlideAnimation(
                    verticalOffset: 50.0,
                    child: FadeInAnimation(
                      child: _AnimatedHistoryCard(
                        trip: trip,
                        onTap: () {
                          // Your original logic is preserved here
                          if (trip['status'] != 'Cancel') {
                            controller.getHistoryDetails(trip['order_id']);
                          } else {
                            MyDialog().getDialog(
                              'This Trip Was Cancelled'.tr,
                              'This Trip Was Cancelled'.tr,
                              () => Get.back(),
                            );
                          }
                        },
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

// 动画: A new stateful widget to handle the tap animation
class _AnimatedHistoryCard extends StatefulWidget {
  final Map<String, dynamic> trip;
  final VoidCallback onTap;

  const _AnimatedHistoryCard({required this.trip, required this.onTap});

  @override
  __AnimatedHistoryCardState createState() => __AnimatedHistoryCardState();
}

class __AnimatedHistoryCardState extends State<_AnimatedHistoryCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 150),
    );
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.95).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );
  }

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

  void _onTapDown(TapDownDetails details) {
    _controller.forward();
  }

  void _onTapUp(TapUpDetails details) {
    _controller.reverse();
    widget.onTap();
  }

  void _onTapCancel() {
    _controller.reverse();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: _onTapDown,
      onTapUp: _onTapUp,
      onTapCancel: _onTapCancel,
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Card(
          elevation: 4,
          shadowColor: Colors.black.withOpacity(0.1),
          margin: const EdgeInsets.only(bottom: 16.0),
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Icon(Icons.receipt_long,
                    color: Theme.of(context).primaryColor, size: 40),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${'OrderId'.tr}: ${widget.trip['order_id']}',
                        style:
                            Theme.of(context).textTheme.titleMedium?.copyWith(
                                  fontWeight: FontWeight.bold,
                                ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        widget.trip['created_at'],
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              color: Colors.grey[600],
                            ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 16),
                _buildStatusChip(widget.trip['status']),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 🎨 A separate function for the status chip, slightly restyled for Material
Widget _buildStatusChip(String status) {
  Color chipColor;
  Color textColor;
  String statusText = status;
  IconData iconData;

  switch (status) {
    case 'Apply':
      chipColor = Colors.green.shade50;
      textColor = Colors.green.shade800;
      iconData = Icons.check_circle;
      break;
    case 'Refused':
      chipColor = Colors.red.shade50;
      textColor = Colors.red.shade800;
      iconData = Icons.cancel;
      break;
    case 'Cancel':
      chipColor = Colors.orange.shade50;
      textColor = Colors.orange.shade800;
      iconData = Icons.info;
      statusText = 'Cancelled';
      break;
    default:
      chipColor = Colors.grey.shade200;
      textColor = Colors.grey.shade800;
      iconData = Icons.hourglass_empty;
  }

  return Chip(
    avatar: Icon(iconData, color: textColor, size: 16),
    label: Text(
      statusText.tr,
      style: TextStyle(color: textColor, fontWeight: FontWeight.w600),
    ),
    backgroundColor: chipColor,
    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
    side: BorderSide.none,
  );
}
