import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:slide_to_act/slide_to_act.dart';
import 'package:vibration/vibration.dart';
import 'dart:io';

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

// Changed: إعادة تصميم كاملة للشريط ليصبح شريطًا علويًا عند بدء الرحلة
GetBuilder<MapDriverController> driverEndRideBar() {
  return GetBuilder<MapDriverController>(
    builder: (controller) => AnimatedPositioned(
      duration: const Duration(milliseconds: 300),
      // New: يظهر الشريط من الأعلى عندما تبدأ الرحلة
      top: controller.isRideStarted ? 0 : -200,
      left: 0,
      right: 0,
      child: Card(
        margin: EdgeInsets.zero,
        elevation: 10,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(24)),
        ),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
          child: Column(
            children: [
              // -- معلومات الرحلة --
              if (controller.carType != 'Mishwar Vip')
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildInfoColumn(
                      icon: Icons.social_distance,
                      text: '${controller.distance} ${'KM'.tr}',
                      label: 'Distance'.tr,
                    ),
                    _buildInfoColumn(
                      icon: Icons.timelapse,
                      text: controller.hours > 1
                          ? '${controller.hours}h ${controller.minutes}m'
                          : '${controller.minutes}m',
                      label: 'Time'.tr,
                    ),
                    _buildInfoColumn(
                      icon: Icons.money_sharp,
                      text: '${controller.paymentAmount} ${'SYP'.tr}',
                      label: 'Price'.tr,
                    ),
                  ],
                ),
              if (controller.carType != 'Mishwar Vip')
                const Divider(height: 20),

              // -- مؤقت الرحلة المتبقي (إن وجد) --
              _builtTimerAndCarType(),

              const SizedBox(height: 12),

              // -- زر إنهاء الرحلة المنزلق --
              SlideAction(
                height: 55,
                borderRadius: 15,
                elevation: 4,
                text: 'Slide to End Trip'.tr,
                textStyle: AppStyle.title.copyWith(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
                outerColor: AppColor.redColor,
                innerColor: Colors.white,
                sliderButtonIcon: const Icon(
                  Icons.arrow_forward_ios,
                  color: AppColor.redColor,
                  size: 24,
                ),
                sliderRotate: false,
                onSubmit: () {
                  HapticFeedback.mediumImpact();
                  controller.finishRideFromDriver();
                  return null; // New: onSubmit now returns null
                },
              ),
            ],
          ),
        ),
      ),
    ),
  );
}

// New: ودجت لعرض معلومات الرحلة في الشريط العلوي
Widget _buildInfoColumn(
    {required IconData icon, required String text, required String label}) {
  return Column(
    mainAxisSize: MainAxisSize.min,
    children: [
      Icon(icon, color: AppColor.primaryColor),
      const SizedBox(height: 4),
      Text(text, style: AppStyle.title.copyWith(fontWeight: FontWeight.bold)),
      Text(label,
          style:
              AppStyle.title.copyWith(color: Colors.grey[600], fontSize: 12)),
    ],
  );
}

// Changed: تم تعديل تصميم ودجت عرض المؤقت ونوع السيارة
class _builtTimerAndCarType extends StatelessWidget {
  const _builtTimerAndCarType();

  @override
  Widget build(BuildContext context) {
    final controller = Get.find<MapDriverController>();
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // -- نوع السيارة --
        Container(
          decoration: AppStyle.boxDecoration1.copyWith(color: Colors.grey[200]),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Text(
            controller.carType,
            style: AppStyle.title.copyWith(fontWeight: FontWeight.bold),
          ),
        ),
        // -- مؤقت الرحلة --
        if (controller.carType != 'Comfort' &&
            controller.carType != 'Mishwar Vip' &&
            controller.carType != 'Lady') ...[
          const SizedBox(width: 10),
          Expanded(
            child: Container(
              height: 40,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                gradient: LinearGradient(
                  colors: [
                    controller.remainingTimeTimerRideBegin < 60
                        ? AppColor.redColor.withOpacity(0.8)
                        : AppColor.greenColor.withOpacity(0.8),
                    controller.remainingTimeTimerRideBegin < 60
                        ? AppColor.redColor
                        : AppColor.greenColor,
                  ],
                ),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    LinearProgressIndicator(
                      backgroundColor: Colors.transparent,
                      valueColor: AlwaysStoppedAnimation<Color>(
                          Colors.white.withOpacity(0.2)),
                      minHeight: 40,
                      value: controller.progressTimerRideBegin.toDouble(),
                    ),
                    Text(
                      controller.stringRemainingTimeRideBegin,
                      style: AppStyle.title.copyWith(
                          color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ],
    );
  }
}

// Changed: تم تعديل مكان ومظهر دائرة السرعة
GetBuilder<MapDriverController> speedCircle() {
  if (Get.find<MapDriverController>().speed > 100) {
    if (Platform.isIOS) {
      HapticFeedback.selectionClick();
    } else {
      Vibration.vibrate(duration: 1000);
    }
    Get.defaultDialog(
      barrierDismissible: false,
      titleStyle: AppStyle.title,
      title: 'Speed Over'.tr,
      middleText: 'Please slow down'.tr,
      middleTextStyle: AppStyle.title,
      confirm: MyElevatedButton(
        title: 'I will slow down'.tr,
        onPressed: () => Get.back(),
      ),
    );
  }
  return GetBuilder<MapDriverController>(
    builder: (controller) {
      return controller.isRideStarted
          ? Positioned(
              // New: تم وضع دائرة السرعة في الأسفل يمينًا
              bottom: 25,
              left: 3,
              child: Container(
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  boxShadow: [BoxShadow(blurRadius: 5, color: Colors.black26)],
                  border: Border.all(
                    width: 4,
                    color: controller.speed > 100
                        ? Colors.red
                        : AppColor.greenColor,
                  ),
                ),
                height: 70,
                width: 70,
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        controller.speed.toStringAsFixed(0),
                        style: AppStyle.number.copyWith(fontSize: 24),
                      ),
                      Text("km/h", style: TextStyle(fontSize: 10)),
                    ],
                  ),
                ),
              ),
            )
          : const SizedBox();
    },
  );
}
