import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:slide_to_act/slide_to_act.dart';

import '../../../../constant/colors.dart';
import '../../../../controller/home/captin/map_driver_controller.dart';

Widget driverEndRideBar() {
  return GetBuilder<MapDriverController>(
    builder: (controller) {
      // 🔥 فحص هل السعر ثابت للعرض
      final String carType = controller.carType;
      final bool isFixed = (carType == 'Speed' ||
          carType == 'Awfar' ||
          carType == 'Fixed Price');

      return AnimatedContainer(
        duration: const Duration(milliseconds: 400),
        curve: Curves.easeOutBack,
        transform: Matrix4.translationValues(
          0,
          controller.isRideStarted ? 0 : -300,
          0,
        ), // Matrix4.translationValues مستخدمة للإزاحة [web:28]
        margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
        padding: const EdgeInsets.all(15),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 20,
              offset: const Offset(0, 8),
            )
          ],
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // لوحة العدادات
            Container(
              padding: const EdgeInsets.symmetric(vertical: 15, horizontal: 10),
              decoration: BoxDecoration(
                color: const Color(0xFFF8F9FA),
                borderRadius: BorderRadius.circular(18),
                border: Border.all(color: Colors.grey.shade200),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  // 1) المسافة (تتغير دائماً)
                  _buildLiveMetric(
                    icon: Icons.alt_route_rounded,
                    iconColor: Colors.blueAccent,
                    value: controller.currentRideDistanceKm.toStringAsFixed(2),
                    unit: 'KM'.tr,
                    label: 'Traveled'.tr,
                  ),

                  _buildVerticalDivider(),

                  // 2) السعر (ثابت أو متغير)
                  _buildLiveMetric(
                    icon: isFixed
                        ? Icons.lock_outline_rounded
                        : Icons.attach_money_rounded,
                    iconColor: isFixed ? Colors.grey : AppColor.primaryColor,
                    value: NumberFormat('#,##0').format(
                      double.tryParse(controller.price.toString()) ?? 0,
                    ),
                    unit: 'SYP'.tr,
                    label: isFixed ? 'Fixed Price'.tr : 'Meter Fare'.tr,
                    isHighlight: true,
                    isFixedStyle: isFixed,
                  ),

                  _buildVerticalDivider(),

                  // 3) الوقت (تصغير الخط + إخفاء الساعات إذا 0)
                  _buildLiveMetric(
                    icon: Icons.timer_outlined,
                    iconColor: Colors.orange,
                    value: _formatDurationFromStart(controller),
                    unit: '',
                    label: 'Duration'.tr,
                    valueFontSize: 14, // ✅ تصغير خط “المدة”
                  ),
                ],
              ),
            ),

            const SizedBox(height: 20),

            // زر الإنهاء
            SlideAction(
              key: ValueKey(controller.isRideFinished),
              height: 60,
              borderRadius: 18,
              elevation: 0,
              text: 'Swipe to End Trip'.tr,
              textStyle: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
              outerColor: AppColor.redColor,
              innerColor: Colors.white,
              sliderButtonIcon: const Icon(
                Icons.stop_circle_outlined,
                color: AppColor.redColor,
                size: 32,
              ),
              onSubmit: () async {
                await controller.finishRideFromDriver(isFromSlider: true);
                return null;
              },
            ), // SlideAction مثال الاستخدام موجود في صفحة الحزمة [web:19]
          ],
        ),
      );
    },
  ); // GetBuilder يعيد البناء عند update() من الكنترولر [web:21]
}

/// دالة تنسيق المدة:
/// - أقل من ساعة: mm:ss
/// - ساعة فأكثر: h:mm:ss (خانة واحدة للساعات بدون leading zero)
String _formatDurationFromStart(MapDriverController controller) {
  if (controller.rideStartTime == null) return "00:00";

  final d = DateTime.now().difference(controller.rideStartTime!);

  String twoDigits(int n) => n.toString().padLeft(2, "0");

  final hours = d.inHours;
  final minutes = d.inMinutes.remainder(60);
  final seconds = d.inSeconds.remainder(60);

  if (hours == 0) {
    // mm:ss
    final totalMinutes = d.inMinutes;
    return "${twoDigits(totalMinutes)}:${twoDigits(seconds)}";
  }

  // h:mm:ss
  return "$hours:${twoDigits(minutes)}:${twoDigits(seconds)}";
} // Duration وتفكيكه (inHours/inMinutes/inSeconds) من أساسيات Dart [web:11]

Widget _buildLiveMetric({
  required IconData icon,
  required Color iconColor,
  required String value,
  required String unit,
  required String label,
  bool isHighlight = false,
  bool isFixedStyle = false,
  double? valueFontSize, // ✅ جديد: حجم خط القيمة فقط
}) {
  final effectiveFontSize = valueFontSize ?? (isHighlight ? 20 : 18);

  return Expanded(
    child: Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 14, color: iconColor),
            const SizedBox(width: 4),
            Text(
              label,
              style: TextStyle(
                fontSize: 10,
                color: Colors.grey[600],
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        const SizedBox(height: 6),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.baseline,
          textBaseline: TextBaseline.alphabetic,
          children: [
            Text(
              value,
              style: TextStyle(
                fontSize: effectiveFontSize, // ✅ هنا صار التحكم
                fontWeight: FontWeight.w900,
                color: isFixedStyle
                    ? Colors.grey[800]
                    : (isHighlight ? AppColor.primaryColor : Colors.black87),
                fontFamily: 'monospace',
              ),
            ),
            if (unit.isNotEmpty) ...[
              const SizedBox(width: 2),
              Text(
                unit,
                style: TextStyle(
                  fontSize: 10,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey[600],
                ),
              ),
            ]
          ],
        ),
      ],
    ),
  );
}

Widget _buildVerticalDivider() {
  return Container(height: 35, width: 1, color: Colors.grey.shade300);
}
