import 'package:siro_rider/constant/currency.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// تأكد من المسارات
import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import 'package:siro_rider/controller/functions/country_logic.dart';
import '../../../controller/functions/audio_record1.dart';
import '../../../controller/functions/launch.dart';
import '../../../controller/functions/toast.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';
import '../../../views/home/profile/complaint_page.dart';
import '../../../controller/functions/country_logic.dart';

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

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

    return Obx(() {
      final controller = Get.find<RideLifecycleController>();

      // شرط الإظهار
      final bool isVisible =
          controller.currentRideState.value == RideState.inProgress &&
              controller.isStartAppHasRide == false;

      return AnimatedPositioned(
        duration: const Duration(milliseconds: 500),
        curve: Curves.easeInOutCubic,
        // تم تقليل قيمة الإخفاء لأن الارتفاع الكلي للنافذة أصبح أصغر
        bottom: isVisible ? 0 : -300,
        left: 0,
        right: 0,
        child: Container(
          decoration: BoxDecoration(
            color: AppColor.secondaryColor,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(25),
              topRight: Radius.circular(25),
            ),
            boxShadow: [
              BoxShadow(
                color: Get.isDarkMode
                    ? Colors.black.withValues(alpha: 0.4)
                    : Colors.black.withValues(alpha: 0.1),
                blurRadius: 20,
                spreadRadius: 2,
                offset: const Offset(0, -3),
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 1. مقبض السحب
                Center(
                  child: Container(
                    width: 40,
                    height: 4,
                    decoration: BoxDecoration(
                      color: AppColor.grayColor.withValues(alpha: 0.3),
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                ),
                const SizedBox(height: 12),

                // 2. هيدر المعلومات (سائق + سيارة + سعر)
                _buildCompactHeader(controller),

                const SizedBox(height: 12),

                // خط فاصل خفيف
                Divider(
                    height: 1,
                    thickness: 0.5,
                    color: AppColor.grayColor.withValues(alpha: 0.2)),

                const SizedBox(height: 12),

                // 3. الأزرار (إجراءات)
                _buildCompactActionButtons(
                    context, controller, profileController, audioController),

                // إضافة هامش سفلي بسيط لرفع الأزرار عن حافة الشاشة
                const SizedBox(height: 5),
              ],
            ),
          ),
        ),
      );
    });
  }

  // --- الهيدر (بدون تغيير، ممتاز) ---
  Widget _buildCompactHeader(RideLifecycleController controller) {
    return Row(
      children: [
        // صورة السائق
        Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(
                color: AppColor.primaryColor.withValues(alpha: 0.5),
                width: 1.5),
          ),
          child: CircleAvatar(
            radius: 24,
            backgroundImage: NetworkImage(
                '${AppLink.server}/portrate_captain_image/${controller.driverId}.jpg'),
            onBackgroundImageError: (_, __) => const Icon(Icons.person),
          ),
        ),
        const SizedBox(width: 10),

        // الاسم ومعلومات السيارة
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Flexible(
                    child: Text(
                      controller.driverName,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 15,
                        color: AppColor.writeColor,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  const SizedBox(width: 4),
                  const Icon(Icons.star, color: Colors.amber, size: 14),
                  Text(
                    controller.driverRate,
                    style: const TextStyle(
                        fontSize: 12, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              const SizedBox(height: 2),
              Row(
                children: [
                  Flexible(
                    child: Text(
                      '${controller.model}${controller.carColor.isNotEmpty ? " • ${controller.carColor.tr}" : ""} • ',
                      style: TextStyle(fontSize: 12, color: AppColor.grayColor),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                    decoration: BoxDecoration(
                      color: AppColor.writeColor.withValues(alpha: 0.05),
                      border: Border.all(
                          color: AppColor.grayColor.withValues(alpha: 0.2)),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      controller.licensePlate,
                      style: const TextStyle(
                        fontFamily: 'monospace',
                        fontSize: 11,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),

        // السعر
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
          decoration: BoxDecoration(
            color: AppColor.primaryColor.withValues(alpha: 0.08),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                NumberFormat('#,###').format(controller.totalPassenger),
                style: const TextStyle(
                  fontWeight: FontWeight.w900,
                  fontSize: 16,
                  color: AppColor.primaryColor,
                ),
              ),
              Text(CurrencyHelper.currency,
                  style: TextStyle(fontSize: 9, color: AppColor.grayColor)),
            ],
          ),
        ),
      ],
    );
  }

  // --- الأزرار (بدون تغيير) ---
  Widget _buildCompactActionButtons(
      BuildContext context,
      RideLifecycleController controller,
      ProfileController profileController,
      AudioRecorderController audioController) {
    final uiController = Get.find<UiInteractionsController>();
    return SizedBox(
      height: 60,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _compactBtn(
            icon: Icons.sos_rounded,
            label: 'SOS'.tr,
            color: AppColor.redColor,
            bgColor: AppColor.redColor.withValues(alpha: 0.1),
            onTap: () async {
              if (box.read(BoxName.sosPhonePassenger) == null) {
                await profileController.updatField(
                    'sosPhone', TextInputType.phone);
                box.write(BoxName.sosPhonePassenger,
                    profileController.prfoileData['sosPhone']);
              } else {
                makePhoneCall(CountryLogic.getEmergencyNumber(
                    box.read(BoxName.countryCode) ?? 'Syria'));
              }
            },
          ),
          _compactBtn(
            icon: FontAwesome.whatsapp,
            label: 'WhatsApp'.tr,
            color: const Color(0xFF25D366),
            bgColor: const Color(0xFF25D366).withValues(alpha: 0.1),
            onTap: () async {
              final phone = box.read(BoxName.sosPhonePassenger);
              if (phone == null || phone.toString().isEmpty) {
                // لا يوجد رقم طوارئ — نعرض الديالوج لإدخاله
                await uiController.shareTripWithFamily();
              } else {
                final formattedPhone =
                    CountryLogic.formatCurrentCountryPhone(phone.toString());
                uiController.sendWhatsapp(formattedPhone);
              }
            },
          ),
          _compactBtn(
            icon: Icons.share,
            label: 'Share'.tr,
            color: AppColor.primaryColor,
            bgColor: AppColor.primaryColor.withValues(alpha: 0.1),
            onTap: () async => await uiController.shareTripWithFamily(),
          ),
          GetBuilder<AudioRecorderController>(
            init: audioController,
            builder: (audioCtx) {
              return _compactBtn(
                icon: audioCtx.isRecording
                    ? Icons.stop_circle_outlined
                    : Icons.mic_none_outlined,
                label: audioCtx.isRecording ? 'Stop'.tr : 'Record'.tr,
                color: audioCtx.isRecording
                    ? AppColor.redColor
                    : AppColor.primaryColor,
                bgColor: audioCtx.isRecording
                    ? AppColor.redColor.withValues(alpha: 0.1)
                    : AppColor.primaryColor.withValues(alpha: 0.1),
                onTap: () async {
                  if (!audioCtx.isRecording) {
                    await audioCtx.startRecording(rideId: controller.rideId);
                    if (context.mounted) {
                      Toast.show(
                          context, 'Start Record'.tr, AppColor.greenColor);
                    }
                  } else {
                    await audioCtx.stopRecording();
                    if (context.mounted) {
                      Toast.show(
                          context, 'Record saved'.tr, AppColor.greenColor);
                    }
                  }
                },
              );
            },
          ),
          _compactBtn(
            icon: Icons.info_outline_rounded,
            label: 'Report'.tr,
            color: AppColor.grayColor,
            bgColor: AppColor.writeColor.withValues(alpha: 0.1),
            onTap: () => Get.to(() => ComplaintPage()),
          ),
        ],
      ),
    );
  }

  Widget _compactBtn({
    required IconData icon,
    required String label,
    required Color color,
    required Color bgColor,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: bgColor,
              shape: BoxShape.circle,
            ),
            child: Icon(icon, size: 20, color: color),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
                fontSize: 10,
                color: AppColor.grayColor,
                fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }
}
