import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intaleq_maps/intaleq_maps.dart';
import 'package:siro_driver/constant/api_key.dart';
import 'package:siro_driver/constant/colors.dart';
import 'package:siro_driver/controller/home/captin/order_request_controller.dart';
import 'package:siro_driver/constant/currency.dart';

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

  @override
  Widget build(BuildContext context) {
    // حقن الكنترولر
    final OrderRequestController controller = Get.put(OrderRequestController());

    return Scaffold(
      body: Directionality(
        textDirection: TextDirection.rtl,
        child: GetBuilder<OrderRequestController>(
          builder: (controller) {
            // 🔥 التعديل الأهم: التحقق من وجود أي بيانات (List أو Map)
            if (controller.myList == null && controller.myMapData == null) {
              return const Center(
                  child:
                      CircularProgressIndicator()); // شاشة تحميل بدلاً من فراغ
            }

            // 🔥 استخدام دوال الكنترولر الآمنة لجلب البيانات بدلاً من الوصول المباشر
            // قمت بتحويل _safeGet إلى دالة عامة safeGet في الكنترولر (تأكد من جعلها public)
            // أو سأقوم بكتابة المنطق هنا مباشرة لضمان العمل:

            String getValue(int index) {
              if (controller.myList != null &&
                  index < controller.myList!.length) {
                return controller.myList![index].toString();
              }
              if (controller.myMapData != null &&
                  controller.myMapData!.containsKey(index.toString())) {
                return controller.myMapData![index.toString()].toString();
              }
              return "";
            }

            final String passengerName =
                getValue(8).isEmpty ? "عميل" : getValue(8);
            final String startAddr = controller.apiStartName.isNotEmpty
                ? controller.apiStartName
                : (getValue(29).isEmpty ? "موقع الانطلاق" : getValue(29));
            final String endAddr = controller.apiEndName.isNotEmpty
                ? controller.apiEndName
                : (getValue(30).isEmpty ? "الوجهة" : getValue(30));
            final bool isVisa = (getValue(13) == 'true');

            // منطق Speed = سعر ثابت
            final bool isSpeed =
                controller.tripType.toLowerCase().contains('speed');
            final String carTypeLabel =
                isSpeed ? "سعر ثابت" : controller.tripType;
            final Color carTypeColor =
                isSpeed ? Colors.red.shade700 : Colors.blue.shade700;
            final IconData carIcon =
                isSpeed ? Icons.local_offer : Icons.directions_car;

            return Stack(
              children: [
                // 1. الخارطة
                Positioned.fill(
                  bottom: 300,
                  child: IntaleqMap(
                    apiKey: AK.mapAPIKEY,
                    initialCameraPosition: CameraPosition(
                      target: LatLng(
                          controller.latPassenger, controller.lngPassenger),
                      zoom: 13.0,
                    ),
                    markers: controller.markers,
                    mapType: Get.isDarkMode
                        ? IntaleqMapType.normal
                        : IntaleqMapType.light,
                    polylines: controller.polylines,
                    zoomControlsEnabled: false,
                    myLocationButtonEnabled: false,
                    compassEnabled: false,
                    onMapCreated: (c) {
                      controller.onMapCreated(c);
                      controller.update();
                    },
                  ),
                ),

                // 2. كبسولة الوصول للراكب
                Positioned(
                  top: 50,
                  left: 0,
                  right: 0,
                  child: Center(
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15, vertical: 8),
                      decoration: BoxDecoration(
                        color: Colors.black87,
                        borderRadius: BorderRadius.circular(30),
                        boxShadow: [
                          BoxShadow(color: Colors.black26, blurRadius: 8)
                        ],
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          const Icon(Icons.near_me,
                              color: Colors.amber, size: 16),
                          const SizedBox(width: 8),
                          Text(
                            "الوصول للراكب: ${controller.timeToPassenger}",
                            style: const TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 13),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),

                // 3. البطاقة السفلية
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    height: 360,
                    decoration: BoxDecoration(
                      color: Theme.of(context).cardColor,
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(25),
                        topRight: Radius.circular(25),
                      ),
                      boxShadow: [
                        BoxShadow(
                            color:
                                Theme.of(context).shadowColor.withOpacity(0.1),
                            blurRadius: 20,
                            spreadRadius: 5)
                      ],
                    ),
                    padding: const EdgeInsets.fromLTRB(20, 10, 20, 20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Center(
                            child: Container(
                                width: 40,
                                height: 4,
                                decoration: BoxDecoration(
                                    color: Theme.of(context).dividerColor,
                                    borderRadius: BorderRadius.circular(2)))),

                        const SizedBox(height: 15),

                        // الصف الأول: الراكب والسعر
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                CircleAvatar(
                                  radius: 24,
                                  backgroundColor: Theme.of(context)
                                      .colorScheme
                                      .surfaceVariant,
                                  child: Icon(Icons.person,
                                      color: Theme.of(context).hintColor,
                                      size: 28),
                                ),
                                const SizedBox(width: 10),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(passengerName,
                                        style: const TextStyle(
                                            fontSize: 17,
                                            fontWeight: FontWeight.bold)),
                                    Row(
                                      children: [
                                        const Icon(Icons.star,
                                            color: Colors.amber, size: 14),
                                        Text(controller.passengerRating,
                                            style: const TextStyle(
                                                fontSize: 13,
                                                fontWeight: FontWeight.bold)),
                                      ],
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                Text("${controller.tripPrice} ${CurrencyHelper.currency}",
                                    style: const TextStyle(
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                        color: AppColor.primaryColor)),
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 8, vertical: 2),
                                  decoration: BoxDecoration(
                                      color: isVisa
                                          ? Colors.purple.withOpacity(0.1)
                                          : Colors.green.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(4)),
                                  child: Row(
                                    children: [
                                      Text(isVisa ? "فيزا" : "كاش",
                                          style: TextStyle(
                                              fontSize: 11,
                                              fontWeight: FontWeight.bold,
                                              color: isVisa
                                                  ? Colors.purple
                                                  : Colors.green)),
                                      const SizedBox(width: 4),
                                      Icon(
                                          isVisa
                                              ? Icons.credit_card
                                              : Icons.money,
                                          size: 14,
                                          color: isVisa
                                              ? Colors.purple
                                              : Colors.green),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),

                        const SizedBox(height: 15),

                        // الصف الثاني: شريط المعلومات
                        Container(
                          padding: const EdgeInsets.symmetric(
                              vertical: 10, horizontal: 10),
                          decoration: BoxDecoration(
                            color: Theme.of(context)
                                .colorScheme
                                .surfaceVariant
                                .withOpacity(0.5),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                                color: Theme.of(context).dividerColor),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              _buildInfoItem(
                                  context, carIcon, carTypeLabel, carTypeColor),
                              Container(
                                  height: 20,
                                  width: 1,
                                  color: Theme.of(context).dividerColor),
                              _buildInfoItem(
                                  context,
                                  Icons.route,
                                  controller.totalTripDistance,
                                  Theme.of(context)
                                          .textTheme
                                          .bodyLarge
                                          ?.color ??
                                      Colors.black87),
                              Container(
                                  height: 20,
                                  width: 1,
                                  color: Theme.of(context).dividerColor),
                              _buildInfoItem(
                                  context,
                                  Icons.access_time_filled,
                                  controller.totalTripDuration,
                                  Theme.of(context)
                                          .textTheme
                                          .bodyLarge
                                          ?.color ??
                                      Colors.black87),
                            ],
                          ),
                        ),

                        const SizedBox(height: 20),

                        // الصف الثالث: العناوين
                        Expanded(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Column(
                                children: [
                                  const Icon(Icons.my_location,
                                      size: 18, color: Colors.green),
                                  Container(
                                      width: 2,
                                      height: 38,
                                      color: Colors.grey.shade300,
                                      margin: const EdgeInsets.symmetric(
                                          vertical: 4)),
                                  const Icon(Icons.location_on,
                                      size: 18, color: Colors.red),
                                ],
                              ),
                              const SizedBox(width: 15),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const Text("موقع الانطلاق",
                                            style: TextStyle(
                                                fontSize: 11,
                                                color: Colors.grey)),
                                        const SizedBox(height: 2),
                                        Text(startAddr,
                                            style: const TextStyle(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600),
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis),
                                      ],
                                    ),
                                    const SizedBox(height: 14),
                                    Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        const Text("الوجهة",
                                            style: TextStyle(
                                                fontSize: 11,
                                                color: Colors.grey)),
                                        const SizedBox(height: 2),
                                        Text(endAddr,
                                            style: const TextStyle(
                                                fontSize: 13,
                                                fontWeight: FontWeight.w600),
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis),
                                      ],
                                    ),
                                  ],
                                ),
                              )
                            ],
                          ),
                        ),

                        const SizedBox(height: 15),

                        // الصف الرابع: الأزرار
                        Row(
                          children: [
                            InkWell(
                              onTap: () => Get.back(),
                              child: Container(
                                height: 50,
                                width: 50,
                                decoration: BoxDecoration(
                                    color: Colors.red.shade50,
                                    shape: BoxShape.circle,
                                    border:
                                        Border.all(color: Colors.red.shade100)),
                                child: const Icon(Icons.close,
                                    color: Colors.red, size: 24),
                              ),
                            ),
                            const SizedBox(width: 15),
                            Expanded(
                              child: ElevatedButton(
                                onPressed: controller.isAccepting
                                    ? null
                                    : () => controller.acceptOrder(),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: AppColor.primaryColor,
                                  foregroundColor: Colors.white,
                                  padding:
                                      const EdgeInsets.symmetric(vertical: 14),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(15)),
                                  elevation: 2,
                                ),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                        controller.isAccepting
                                            ? "جاري القبول...".tr
                                            : "قبول الرحلة".tr,
                                        style: const TextStyle(
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold)),
                                    const SizedBox(width: 15),
                                    SizedBox(
                                      width: 20,
                                      height: 20,
                                      child: controller.isAccepting
                                          ? const CircularProgressIndicator(
                                              color: Colors.white,
                                              strokeWidth: 2.5,
                                            )
                                          : CircularProgressIndicator(
                                              value: controller.progress,
                                              color: Colors.white,
                                              strokeWidth: 2.5,
                                              backgroundColor: Colors.white24),
                                    ),
                                    if (!controller.isAccepting) ...[
                                      const SizedBox(width: 8),
                                      Text("${controller.remainingTime}",
                                          style: const TextStyle(
                                              fontSize: 14,
                                              color: Colors.white)),
                                    ],
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildInfoItem(
      BuildContext context, IconData icon, String text, Color color) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(icon, size: 16, color: color),
        const SizedBox(width: 6),
        Text(text,
            style: TextStyle(
                fontSize: 13, fontWeight: FontWeight.bold, color: color)),
      ],
    );
  }
}
