import 'package:siro_rider/constant/currency.dart';
import 'package:siro_rider/controller/functions/launch.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import '../../../controller/functions/country_logic.dart';

// ... استيراد ملفاتك الأخرى ...
import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import '../../../constant/style.dart';
import '../../../controller/home/map/ride_lifecycle_controller.dart';
import '../../../controller/home/map/ui_interactions_controller.dart';
import '../../../controller/home/map/ride_state.dart';
import '../../../controller/profile/profile_controller.dart';
import '../../../main.dart';

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

  @override
  Widget build(BuildContext context) {
    final profileController = Get.put(ProfileController());
    final RideLifecycleController controller =
        Get.find<RideLifecycleController>();
    final UiInteractionsController uiController =
        Get.find<UiInteractionsController>();

    return Obx(() {
      final bool isRideActive =
          controller.currentRideState.value == RideState.inProgress &&
              controller.isStartAppHasRide == true;

      if (!isRideActive) return const SizedBox();

      // قراءة البيانات
      final rideData = controller.rideStatusFromStartApp['data'] ?? {};
      final driverId = rideData['driver_id'];
      final driverName = rideData['driverName'] ?? 'Captain'.tr;
      final driverRate = controller.driverRate;
      final carType = rideData['carType'] ?? 'Car'.tr;
      final carModel = controller.model;
      final arrivalTime = box.read(BoxName.arrivalTime) ?? '--:--';

      // تحديد البيانات للعرض
      final displayTime = controller.stringRemainingTimeRideBegin.isNotEmpty
          ? controller.stringRemainingTimeRideBegin
          : arrivalTime;
      final displayDistance = rideData['distance']?.toStringAsFixed(1) ?? 'N/A';
      final displayPrice = rideData['price']?.toString() ?? 'N/A';

      return Positioned(
        left: 0,
        right: 0,
        bottom: 0, // ملتصق بالأسفل تماماً
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
          decoration: BoxDecoration(
            color: AppColor.secondaryColor, // خلفية متفاعلة
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(25),
              topRight: Radius.circular(25),
            ),
            boxShadow: [
              BoxShadow(
                color: Get.isDarkMode
                    ? Colors.black.withValues(alpha: 0.4)
                    : Colors.black12,
                blurRadius: 15.0,
                spreadRadius: 5.0,
                offset: const Offset(0, -5),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 1. مقبض صغير للدلالة على السحب (تصميم جمالي)
              Center(
                child: Container(
                  width: 40,
                  height: 4,
                  margin: const EdgeInsets.only(bottom: 15),
                  decoration: BoxDecoration(
                    color: AppColor.grayColor.withValues(alpha: 0.3),
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ),

              // 2. حالة الرحلة + معلومات السائق
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // صورة السائق
                  Container(
                    padding: const EdgeInsets.all(2),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border:
                          Border.all(color: AppColor.primaryColor, width: 2),
                    ),
                    child: CircleAvatar(
                      radius: 28,
                      backgroundImage: NetworkImage(
                          '${AppLink.server}/portrate_captain_image/$driverId.jpg'),
                    ),
                  ),
                  const SizedBox(width: 12),

                  // الاسم والسيارة
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          driverName,
                          style: AppStyle.title.copyWith(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: AppColor.writeColor,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Icon(Icons.star,
                                color: AppColor.yellowColor, size: 16),
                            const SizedBox(width: 4),
                            Text(
                              driverRate,
                              style: AppStyle.title.copyWith(
                                  fontSize: 13, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(width: 8),
                            Container(
                                width: 1,
                                height: 12,
                                color: AppColor.grayColor.withValues(alpha: 0.3)),
                            const SizedBox(width: 8),
                            Text(
                              "$carType - $carModel",
                              style: AppStyle.title.copyWith(
                                  fontSize: 13, color: AppColor.grayColor),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),

                  // حالة الرحلة (نص ملون)
                  _buildStatusBadge(controller.currentRideState.value),
                ],
              ),

              const SizedBox(height: 20),

              // 3. شريط المعلومات (وقت، مسافة، سعر)
              Container(
                padding:
                    const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
                decoration: BoxDecoration(
                  color: AppColor.grayColor
                      .withValues(alpha: 0.1), // خلفية رمادية خفيفة جداً
                  borderRadius: BorderRadius.circular(15),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildInfoColumn(
                        Icons.access_time_filled, displayTime, "Time".tr),
                    _buildVerticalDivider(),
                    _buildInfoColumn(Icons.location_on, "$displayDistance KM",
                        "Distance".tr),
                    _buildVerticalDivider(),
                    _buildInfoColumn(
                        Icons.attach_money, "$displayPrice ${CurrencyHelper.currency}", "Price".tr),
                  ],
                ),
              ),

              const SizedBox(height: 20),

              // 4. أزرار التحكم (SOS & Share)
              Row(
                children: [
                  // زر المشاركة (يأخذ مساحة أكبر)
                  Expanded(
                    flex: 2,
                    child: ElevatedButton.icon(
                      onPressed: () => _checkAndCall(
                          uiController.sendWhatsapp, profileController),
                      icon:
                          const Icon(FontAwesome.whatsapp, color: Colors.white),
                      label: Text("Share Trip".tr,
                          style: const TextStyle(color: Colors.white)),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.greenColor,
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 0,
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  // زر الاستغاثة SOS
                  Expanded(
                    flex: 1,
                    child: ElevatedButton.icon(
                      onPressed: () =>
                          makePhoneCall(CountryLogic.getEmergencyNumber(box.read(BoxName.countryCode) ?? 'Syria')),
                      icon: const Icon(Icons.sos, color: Colors.white),
                      label: Text("SOS".tr,
                          style: const TextStyle(color: Colors.white)),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColor.redColor,
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 0,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      );
    });
  }

  // ------------------------- Widgets Helper Methods -------------------------

  Widget _buildStatusBadge(RideState status) {
    String text;
    Color color;

    if (status == RideState.inProgress) {
      text = 'On Trip'.tr;
      color = AppColor.primaryColor;
    } else if (status == RideState.driverArrived) {
      text = 'Arrived'.tr;
      color = AppColor.greenColor;
    } else {
      text = 'Coming'.tr;
      color = AppColor.yellowColor;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withValues(alpha: 0.5)),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: color,
          fontWeight: FontWeight.bold,
          fontSize: 12,
        ),
      ),
    );
  }

  Widget _buildInfoColumn(IconData icon, String value, String label) {
    return Column(
      children: [
        Icon(icon,
            color: AppColor.primaryColor,
            size: 22), // افترضت أن السكندري لون داكن، أو استخدم Primary
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            fontWeight: FontWeight.w800,
            fontSize: 15,
            color: AppColor.writeColor,
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 11,
            color: AppColor.grayColor,
          ),
        ),
      ],
    );
  }

  Widget _buildVerticalDivider() {
    return Container(
      height: 30,
      width: 1,
      color: AppColor.grayColor.withValues(alpha: 0.2),
    );
  }

  // دالة المساعدة للمنطق (بقيت كما هي ولكن تم تمرير البروفايل كونترولر)
  Future<void> _checkAndCall(
      Function(String) action, ProfileController profileController) async {
    String? sosPhone = box.read(BoxName.sosPhonePassenger);
    if (sosPhone == null || sosPhone == 'sos') {
      await profileController.updatField('sosPhone', TextInputType.phone);
      sosPhone = profileController.prfoileData['sosPhone'];
    }

    if (sosPhone != null && sosPhone != 'sos') {
      action(sosPhone);
    } else {
      Get.snackbar('Warning'.tr, 'Please set a valid SOS phone number.'.tr,
          backgroundColor: AppColor.redColor, colorText: Colors.white);
    }
  }
}
