import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/controller/profile/profile_controller.dart';
import 'package:Intaleq/main.dart';
import 'package:Intaleq/views/home/profile/complaint_page.dart';

import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/audio_record1.dart';
import '../../../controller/functions/launch.dart';
import '../../../controller/functions/toast.dart';
import '../../../controller/home/map_passenger_controller.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());

    return GetBuilder<MapPassengerController>(builder: (controller) {
      // --- نفس شرط الإظهار الخاص بك ---
      if (controller.statusRide != 'Begin') {
        return const SizedBox.shrink();
      }

      return Positioned(
        left: 0,
        right: 0,
        bottom: 0,
        child: Container(
          decoration: BoxDecoration(
            color: AppColor.secondaryColor,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(24),
              topRight: Radius.circular(24),
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 20,
                offset: const Offset(0, -5),
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // مقبض السحب (Handle)
                Container(
                  width: 40,
                  height: 5,
                  decoration: BoxDecoration(
                    color: AppColor.writeColor.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                const SizedBox(height: 12),

                // --- 1. قسم معلومات السائق ---
                _buildDriverInfo(controller),
                const Divider(height: 24, thickness: 0.5),

                // --- 2. قسم تقدم الرحلة ---
                _buildTripProgress(controller),
                const SizedBox(height: 16),

                // --- 3. قسم الإجراءات والأمان ---
                _buildActionButtons(
                    context, controller, profileController, audioController),
              ],
            ),
          ),
        ),
      );
    });
  }

  // --- ويدجت مساعدة لعرض معلومات السائق بشكل منظم ---
  Widget _buildDriverInfo(MapPassengerController controller) {
    return Row(
      children: [
        CircleAvatar(
          radius: 28,
          backgroundImage: NetworkImage(
              '${AppLink.server}/portrate_captain_image/${controller.driverId}.jpg'),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(controller.driverName,
                  style: AppStyle.title.copyWith(fontWeight: FontWeight.bold)),
              const SizedBox(height: 2),
              Text(
                '${controller.make} ${controller.model} • ${box.read(BoxName.carType)}',
                style: AppStyle.subtitle
                    .copyWith(color: AppColor.writeColor.withOpacity(0.7)),
              ),
            ],
          ),
        ),
        const SizedBox(width: 12),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: AppColor.writeColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(6),
              ),
              child: Text(
                controller.licensePlate,
                style: AppStyle.subtitle
                    .copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.5),
              ),
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                Text(controller.driverRate,
                    style: AppStyle.subtitle
                        .copyWith(fontWeight: FontWeight.bold)),
                const SizedBox(width: 2),
                const Icon(Icons.star_rounded,
                    color: AppColor.yellowColor, size: 16),
              ],
            ),
          ],
        )
      ],
    );
  }

  // --- ويدجت مساعدة لعرض شريط التقدم ---
  Widget _buildTripProgress(MapPassengerController controller) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('Time to Destination'.tr, style: AppStyle.subtitle),
            Text(controller.stringRemainingTimeRideBegin,
                style: AppStyle.subtitle.copyWith(
                    fontWeight: FontWeight.bold, color: AppColor.primaryColor)),
          ],
        ),
        const SizedBox(height: 8),
        ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: LinearProgressIndicator(
            backgroundColor: AppColor.primaryColor.withOpacity(0.2),
            color: controller.remainingTimeTimerRideBegin < 60
                ? AppColor.redColor
                : AppColor.greenColor,
            minHeight: 10,
            value: controller.progressTimerRideBegin.toDouble(),
          ),
        ),
      ],
    );
  }

  // --- ويدجت مساعدة لعرض أزرار الإجراءات ---
  Widget _buildActionButtons(
      BuildContext context,
      MapPassengerController controller,
      ProfileController profileController,
      AudioRecorderController audioController) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        _buildActionButton(
            icon: Icons.sos_rounded,
            label: 'SOS'.tr,
            color: AppColor.redColor,
            onTap: () async {
              // --- نفس منطقك القديم ---
              if (box.read(BoxName.sosPhonePassenger) == null) {
                await profileController.updatField(
                    'sosPhone', TextInputType.phone);
                box.write(BoxName.sosPhonePassenger,
                    profileController.prfoileData['sosPhone']);
              } else {
                makePhoneCall('112');
              }
            }),
        _buildActionButton(
            icon: FontAwesome.whatsapp,
            label: 'WhatsApp'.tr,
            color: AppColor.greenColor,
            onTap: () async {
              // --- نفس منطقك القديم ---
              if (box.read(BoxName.sosPhonePassenger) == null ||
                  box.read(BoxName.sosPhonePassenger) == 'sos') {
                await profileController.updatField(
                    'sosPhone', TextInputType.phone);
                box.write(BoxName.sosPhonePassenger,
                    profileController.prfoileData['sosPhone']);
              } else {
                final phoneNumber =
                    box.read(BoxName.sosPhonePassenger).toString();

                final phone = controller.formatSyrianPhoneNumber(phoneNumber);
                controller.sendWhatsapp(phone); //
              }
            }),
        _buildActionButton(
            icon: Icons.share_location_outlined, // أيقونة جديدة ومناسبة
            label: 'Share'.tr, // اسم جديد وواضح
            color: AppColor.blueColor,
            onTap: () async {
              // نفس الوظيفة السابقة التي كانت تحت اسم "Video Call"
              await controller.getTokenForParent();
            }),
        _buildActionButton(
          icon: audioController.isRecording
              ? Icons.mic_off_rounded
              : Icons.mic_none_rounded,
          label: audioController.isRecording ? 'Stop'.tr : 'Record'.tr,
          color: AppColor.primaryColor,
          onTap: () async {
            // --- نفس منطقك القديم ---
            if (audioController.isRecording == false) {
              await audioController.startRecording();
              Toast.show(context, 'Start Record'.tr, AppColor.greenColor);
            } else {
              await audioController.stopRecording();
              Toast.show(context, 'Record saved'.tr, AppColor.greenColor);
            }
          },
        ),
        _buildActionButton(
            icon: Icons.note_add_outlined,
            label: 'Complaint'.tr,
            color: AppColor.yellowColor,
            onTap: () {
              // --- نفس منطقك القديم ---
              Get.to(() => ComplaintPage(), transition: Transition.downToUp);
            }),
      ],
    );
  }

  // --- ويدجت مساعدة لبناء زر إجراء فردي ---
  Widget _buildActionButton(
      {required IconData icon,
      required String label,
      required Color color,
      required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Padding(
        padding: const EdgeInsets.all(4.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: color.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(icon, color: color, size: 26),
            ),
            const SizedBox(height: 6),
            Text(label, style: AppStyle.subtitle.copyWith(fontSize: 12)),
          ],
        ),
      ),
    );
  }
}
