import 'package:siro_driver/constant/currency.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import '../../../../constant/finance_design_system.dart';
import '../../../../controller/auth/captin/history_captain.dart';
import 'package:siro_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.white,
      body: GetBuilder<HistoryCaptainController>(
        builder: (controller) {
          if (controller.isloading) {
            return Center(
              child: CircularProgressIndicator(
                  color: FinanceDesignSystem.primaryDark),
            );
          }

          final List trips = controller.historyData['message'] ?? [];

          return CustomScrollView(
            physics: const BouncingScrollPhysics(),
            slivers: [
              // 1. Custom App Bar
              SliverAppBar(
                expandedHeight: 180,
                pinned: true,
                stretch: true,
                backgroundColor: FinanceDesignSystem.primaryDark,
                flexibleSpace: FlexibleSpaceBar(
                  centerTitle: true,
                  title: Text(
                    'Ride History'.tr,
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 18,
                    ),
                  ),
                  background: Stack(
                    fit: StackFit.expand,
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          gradient: FinanceDesignSystem.balanceGradient,
                        ),
                      ),
                      Positioned(
                        right: -50,
                        top: -20,
                        child: Icon(
                          Icons.history_rounded,
                          size: 200,
                          color: Colors.white.withValues(alpha: 0.05),
                        ),
                      ),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const SizedBox(height: 40),
                          Text(
                            trips.length.toString(),
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 40,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                          Text(
                            'Total Rides'.tr,
                            style: TextStyle(
                              color: Colors.white.withValues(alpha: 0.7),
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),

              // 2. Trips List
              if (trips.isEmpty)
                SliverFillRemaining(
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          padding: const EdgeInsets.all(32),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade50,
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.history_toggle_off_rounded,
                            size: 64,
                            color: Colors.grey.shade300,
                          ),
                        ),
                        const SizedBox(height: 24),
                        Text(
                          'No Rides Yet'.tr,
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey.shade600,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          'Your completed trips will appear here'.tr,
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.grey.shade400,
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              else
                SliverPadding(
                  padding: const EdgeInsets.fromLTRB(16, 24, 16, 40),
                  sliver: SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        final trip = trips[index];
                        return AnimationConfiguration.staggeredList(
                          position: index,
                          duration: const Duration(milliseconds: 375),
                          child: SlideAnimation(
                            verticalOffset: 50.0,
                            child: FadeInAnimation(
                              child: _TripHistoryCard(
                                trip: trip,
                                onTap: () {
                                  if (trip['status'] != 'Cancel' &&
                                      trip['status'] != 'CancelByPassenger') {
                                    controller
                                        .getHistoryDetails(trip['order_id']);
                                  } else {
                                    MyDialog().getDialog(
                                      'This Trip Was Cancelled'.tr,
                                      'This Trip Was Cancelled'.tr,
                                      () => Get.back(),
                                    );
                                  }
                                },
                              ),
                            ),
                          ),
                        );
                      },
                      childCount: trips.length,
                    ),
                  ),
                ),
            ],
          );
        },
      ),
    );
  }
}

class _TripHistoryCard extends StatelessWidget {
  final Map trip;
  final VoidCallback onTap;

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

  String _formatDateToSyria(String? dateStr) {
    if (dateStr == null) return '';
    try {
      // Parse GMT date
      DateTime date = DateTime.parse(dateStr);
      // Add 3 hours for Syria (GMT+3)
      DateTime syriaDate = date.add(const Duration(hours: 3));
      // Format to readable string
      return DateFormat('yyyy-MM-dd HH:mm').format(syriaDate);
    } catch (e) {
      return dateStr;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(FinanceDesignSystem.cardRadius),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.04),
            blurRadius: 15,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          borderRadius: BorderRadius.circular(FinanceDesignSystem.cardRadius),
          child: Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: FinanceDesignSystem.primaryDark
                                .withValues(alpha: 0.05),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Icon(
                            Icons.receipt_long_rounded,
                            color: FinanceDesignSystem.primaryDark,
                            size: 20,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '${'OrderId'.tr} #${trip['order_id']}',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 15,
                                color: FinanceDesignSystem.primaryDark,
                              ),
                            ),
                            Text(
                              _formatDateToSyria(trip['created_at']),
                              style: TextStyle(
                                fontSize: 11,
                                color: Colors.grey.shade500,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                    _buildStatusChip(trip['status']),
                  ],
                ),
                const SizedBox(height: 20),
                const Divider(height: 1),
                const SizedBox(height: 20),
                Row(
                  children: [
                    Column(
                      children: [
                        Icon(Icons.circle,
                            size: 12, color: FinanceDesignSystem.accentBlue),
                        Container(
                          width: 2,
                          height: 20,
                          color: Colors.grey.shade200,
                        ),
                        Icon(Icons.location_on_rounded,
                            size: 14, color: FinanceDesignSystem.dangerRed),
                      ],
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            trip['start_name'] ?? 'Pickup Location'.tr,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey.shade700,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(height: 12),
                          Text(
                            trip['end_name'] ?? 'Destination Location'.tr,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.grey.shade700,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                    if (trip['price'] != null)
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Text(
                            '${trip['price']} ${CurrencyHelper.currency}',
                            style: TextStyle(
                              fontWeight: FontWeight.w900,
                              fontSize: 16,
                              color: FinanceDesignSystem.primaryDark,
                            ),
                          ),
                          const Icon(Icons.arrow_forward_ios_rounded,
                              size: 12, color: Colors.grey),
                        ],
                      ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildStatusChip(String? status) {
    Color color;
    IconData icon;
    String label = status ?? 'Unknown';
    List<Color> gradientColors;

    switch (status) {
      case 'Apply':
        color = FinanceDesignSystem.successGreen;
        icon = Icons.check_circle_rounded;
        label = 'Completed'.tr;
        gradientColors = [color.withOpacity(0.2), color.withOpacity(0.05)];
        break;
      case 'Refused':
        color = FinanceDesignSystem.dangerRed;
        icon = Icons.cancel_rounded;
        label = 'Refused'.tr;
        gradientColors = [color.withOpacity(0.2), color.withOpacity(0.05)];
        break;
      case 'Cancel':
        color = Colors.orange;
        icon = Icons.info_rounded;
        label = 'Cancelled'.tr;
        gradientColors = [color.withOpacity(0.2), color.withOpacity(0.05)];
        break;
      case 'CancelByPassenger':
        color = const Color(0xFF6B4EFF);
        icon = Icons.person_off_rounded;
        label = 'Cancelled by Passenger'.tr;
        gradientColors = [color.withOpacity(0.2), color.withOpacity(0.05)];
        break;
      default:
        color = Colors.grey;
        icon = Icons.help_rounded;
        gradientColors = [color.withOpacity(0.2), color.withOpacity(0.05)];
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: gradientColors,
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: color.withValues(alpha: 0.3), width: 1),
        boxShadow: [
          BoxShadow(
            color: color.withValues(alpha: 0.1),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: color),
          const SizedBox(width: 6),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 11,
              fontWeight: FontWeight.w800,
              letterSpacing: 0.3,
            ),
          ),
        ],
      ),
    );
  }
}
