import 'dart:ui'; // مهم لإضافة تأثير الضبابية

import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/main.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/views/home/my_wallet/passenger_wallet.dart';
import 'package:Intaleq/views/home/profile/complaint_page.dart';
import 'package:Intaleq/views/home/profile/order_history.dart';
import 'package:Intaleq/views/home/profile/promos_passenger_page.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../constant/colors.dart';
import '../../../constant/links.dart';
import '../../../controller/home/map_passenger_controller.dart';
import '../../notification/notification_page.dart';
import '../HomePage/contact_us.dart';
import '../HomePage/share_app_page.dart';
import '../setting_page.dart';
import '../profile/passenger_profile_page.dart';

// --- الويدجت الرئيسية بالتصميم الجديد ---
class MapMenuWidget extends StatelessWidget {
  const MapMenuWidget({super.key});

  @override
  Widget build(BuildContext context) {
    Get.lazyPut(() => MapPassengerController());

    return GetBuilder<MapPassengerController>(
      builder: (controller) => Stack(
        children: [
          // --- خلفية معتمة عند فتح القائمة ---
          if (controller.widthMenu > 0)
            GestureDetector(
              onTap: controller.getDrawerMenu,
              child: Container(
                color: Colors.black.withOpacity(0.4),
              ),
            ),

          // --- القائمة الجانبية المنزلقة ---
          _buildSideMenu(controller),

          // --- زر القائمة العائم ---
          _buildMenuButton(controller),
        ],
      ),
    );
  }

  // --- ويدجت لبناء زر القائمة ---
  Widget _buildMenuButton(MapPassengerController controller) {
    return Positioned(
      top: 45,
      left: 16,
      child: SafeArea(
        child: InkWell(
          onTap: controller.getDrawerMenu,
          borderRadius: BorderRadius.circular(50),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(50),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: AppColor.secondaryColor.withOpacity(0.8),
                  shape: BoxShape.circle,
                  border:
                      Border.all(color: AppColor.writeColor.withOpacity(0.2)),
                ),
                child: Icon(
                  controller.widthMenu > 0 ? Icons.close : Icons.menu,
                  color: AppColor.writeColor,
                  size: 26,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // --- ويدجت لبناء القائمة الجانبية ---
  Widget _buildSideMenu(MapPassengerController controller) {
    return AnimatedPositioned(
      duration: const Duration(milliseconds: 400),
      curve: Curves.fastOutSlowIn,
      top: 0,
      bottom: 0,
      left: controller.widthMenu > 0 ? 0 : -Get.width,
      child: ClipRRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
          child: Container(
            width: Get.width * 0.8,
            constraints: const BoxConstraints(maxWidth: 320),
            decoration: BoxDecoration(
              color: AppColor.secondaryColor.withOpacity(0.95),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2),
                  blurRadius: 20,
                )
              ],
            ),
            child: SafeArea(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildMenuHeader(),
                  _buildQuickActionButtons(),
                  const Divider(
                      color: Colors.white24,
                      indent: 16,
                      endIndent: 16,
                      height: 24),
                  Expanded(
                    child: ListView(
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      children: [
                        MenuListItem(
                            title: 'My Balance'.tr,
                            icon: Icons.account_balance_wallet_outlined,
                            onTap: () => Get.to(() => const PassengerWallet())),
                        MenuListItem(
                            title: 'Order History'.tr,
                            icon: Icons.history_rounded,
                            onTap: () => Get.to(() => const OrderHistory())),
                        MenuListItem(
                            title: 'Promos'.tr,
                            icon: Icons.local_offer_outlined,
                            onTap: () =>
                                Get.to(() => const PromosPassengerPage())),
                        MenuListItem(
                            title: 'Contact Us'.tr,
                            icon: Icons.contact_support_outlined,
                            onTap: () => Get.to(() => ContactUsPage())),
                        MenuListItem(
                            title: 'Complaint'.tr,
                            icon: Icons.flag_outlined,
                            onTap: () => Get.to(() => ComplaintPage())),
                        MenuListItem(
                            title: 'Driver'.tr,
                            icon: Ionicons.car_sport_outline,
                            onTap: () => _launchDriverAppUrl()),
                        MenuListItem(
                            title: 'Share App'.tr,
                            icon: Icons.share_outlined,
                            onTap: () => Get.to(() => ShareAppPage())),
                        MenuListItem(
                          title: 'Privacy Policy'.tr,
                          icon: Icons.shield_outlined,
                          onTap: () => launchUrl(Uri.parse(
                              '${AppLink.server}/privacy_policy.php')),
                        ),
                      ],
                    ),
                  ),
                  const Divider(
                      color: Colors.white24,
                      indent: 16,
                      endIndent: 16,
                      height: 1),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: MenuListItem(
                      title: 'Logout'.tr,
                      icon: Icons.logout_rounded,
                      onTap: () {
                        Get.defaultDialog(
                          title: "Logout".tr,
                          middleText: "Are you sure you want to logout?".tr,
                          textConfirm: "Logout".tr,
                          textCancel: "Cancel".tr,
                          onConfirm: () {
                            // controller.logout();
                            Get.back();
                          },
                        );
                      },
                      color: Colors.red.shade300,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // --- ويدجت رأس القائمة ---
  Widget _buildMenuHeader() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 30, 20, 16),
      child: Row(
        children: [
          const CircleAvatar(
            radius: 30,
            backgroundColor: AppColor.primaryColor,
            child: Icon(Icons.person, color: AppColor.writeColor, size: 35),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  box.read(BoxName.name) ?? 'Guest',
                  style: AppStyle.headTitle.copyWith(fontSize: 20),
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  "Intaleq Passenger".tr,
                  style: AppStyle.title.copyWith(
                      color: AppColor.writeColor.withOpacity(0.7),
                      fontSize: 14),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // --- ويدجت الأزرار السريعة ---
  Widget _buildQuickActionButtons() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildSmallActionButton(
              icon: Icons.person_outline_rounded,
              label: 'Profile'.tr,
              onTap: () => Get.to(() => PassengerProfilePage())),
          _buildSmallActionButton(
              icon: Icons.notifications_none_rounded,
              label: 'Alerts'.tr,
              onTap: () => Get.to(() => const NotificationPage())),
          _buildSmallActionButton(
              icon: Icons.settings_outlined,
              label: 'Settings'.tr,
              onTap: () => Get.to(() => const SettingPage())),
        ],
      ),
    );
  }

  Widget _buildSmallActionButton(
      {required IconData icon,
      required String label,
      required VoidCallback onTap}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, color: AppColor.writeColor.withOpacity(0.9), size: 24),
            const SizedBox(height: 6),
            Text(label,
                style: AppStyle.subtitle.copyWith(
                    fontSize: 12, color: AppColor.writeColor.withOpacity(0.9))),
          ],
        ),
      ),
    );
  }

  void _launchDriverAppUrl() async {
    final String driverAppUrl;
    if (defaultTargetPlatform == TargetPlatform.android) {
      driverAppUrl =
          'https://play.google.com/store/apps/details?id=com.intaleq_driver';
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      driverAppUrl =
          'https://apps.apple.com/st/app/intaleq-driver/id6482995159';
    } else {
      return;
    }
    try {
      final Uri url = Uri.parse(driverAppUrl);
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        Get.snackbar('Error', 'Could not launch driver app store.');
      }
    } catch (e) {
      Get.snackbar('Error', 'Could not open the link.');
    }
  }
}

// --- ويدجت عناصر القائمة بتصميم محسن ---
class MenuListItem extends StatelessWidget {
  const MenuListItem({
    super.key,
    required this.title,
    required this.onTap,
    required this.icon,
    this.color,
  });

  final String title;
  final IconData icon;
  final VoidCallback onTap;
  final Color? color;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: onTap,
      leading: Icon(
        icon,
        size: 26,
        color: color ?? AppColor.writeColor.withOpacity(0.8),
      ),
      title: Text(
        title.tr,
        style: AppStyle.title.copyWith(
          fontSize: 16,
          color: color ?? AppColor.writeColor,
        ),
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      splashColor: AppColor.primaryColor.withOpacity(0.2),
    );
  }
}
