import 'dart:ui';

import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/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:siro_rider/constant/style.dart';
import 'package:siro_rider/views/home/my_wallet/passenger_wallet.dart';
import 'package:siro_rider/views/home/profile/complaint_page.dart';
import 'package:siro_rider/views/home/profile/order_history.dart';
import 'package:siro_rider/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/map_engine_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';

// ─── ألوان النظام (Integrated with AppColor) ──────────────────────────────────
Color get _kCyan => AppColor.cyanBlue;
Color get _kBg =>
    Get.isDarkMode ? const Color(0xFF060B18) : AppColor.secondaryColor;
Color get _kBgSurface => Get.isDarkMode
    ? const Color(0xFF0D1525)
    : AppColor.secondaryColor.withValues(alpha: 0.9);
const _kAmber = Color(0xFFFFB700);
Color get _kText => AppColor.writeColor;
Color get _kTextMuted => AppColor.grayColor;

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

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapEngineController>(
      builder: (controller) => Stack(
        children: [
          // ── تعتيم الخلفية ───────────────────────────────────────────────
          if (controller.widthMenu > 0)
            GestureDetector(
              onTap: controller.getDrawerMenu,
              child: Container(color: Colors.black.withValues(alpha: 0.55)),
            ),

          _buildSideMenu(controller),
          _buildMenuButton(controller),
        ],
      ),
    );
  }

  // ── زر القائمة العائم ────────────────────────────────────────────────────
  Widget _buildMenuButton(MapEngineController controller) {
    return Positioned(
      top: 45,
      left: 16,
      child: SafeArea(
        child: GestureDetector(
          onTap: controller.getDrawerMenu,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 12, sigmaY: 12),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeOut,
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: _kBg.withValues(alpha: 0.88),
                  borderRadius: BorderRadius.circular(16),
                  border: Border.all(color: _kCyan.withValues(alpha: 0.25), width: 1),
                  boxShadow: [
                    BoxShadow(
                      color: _kCyan.withValues(alpha: 0.12),
                      blurRadius: 16,
                    ),
                  ],
                ),
                child: AnimatedSwitcher(
                  duration: const Duration(milliseconds: 200),
                  child: Icon(
                    controller.widthMenu > 0
                        ? Icons.close_rounded
                        : Icons.menu_rounded,
                    key: ValueKey(controller.widthMenu > 0),
                    color: _kCyan,
                    size: 22,
                  ),
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  // ── القائمة الجانبية ─────────────────────────────────────────────────────
  Widget _buildSideMenu(MapEngineController controller) {
    return AnimatedPositioned(
      duration: const Duration(milliseconds: 420),
      curve: Curves.fastOutSlowIn,
      top: 0,
      bottom: 0,
      left: controller.widthMenu > 0 ? 0 : -Get.width,
      child: ClipRect(
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
          child: Container(
            width: Get.width * 0.8,
            constraints: const BoxConstraints(maxWidth: 320),
            decoration: BoxDecoration(
              color: _kBg.withValues(alpha: 0.97),
              border: Border(
                right: BorderSide(color: _kCyan.withValues(alpha: 0.12), width: 1),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.5),
                  blurRadius: 32,
                ),
              ],
            ),
            child: Stack(
              children: [
                // شبكة خلفية
                Positioned.fill(
                    child: CustomPaint(painter: _MenuGridPainter())),

                // المحتوى
                SafeArea(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildMenuHeader(),
                      _buildQuickActionButtons(),
                      _buildDivider(),
                      Expanded(
                        child: ListView(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 12, vertical: 4),
                          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'),
                              ),
                            ),
                          ],
                        ),
                      ),
                      _buildDivider(),
                      // زر الخروج
                      Padding(
                        padding: const EdgeInsets.fromLTRB(12, 4, 12, 12),
                        child: MenuListItem(
                          title: 'Logout'.tr,
                          icon: Icons.logout_rounded,
                          isDestructive: true,
                          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();
                              },
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // ── رأس القائمة ──────────────────────────────────────────────────────────
  Widget _buildMenuHeader() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 24, 16, 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _kBgSurface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _kCyan.withValues(alpha: 0.15), width: 1),
      ),
      child: Row(
        children: [
          // أفاتار المستخدم
          Stack(
            children: [
              Container(
                width: 56,
                height: 56,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      _kCyan.withValues(alpha: 0.2),
                      _kAmber.withValues(alpha: 0.12),
                    ],
                  ),
                  border:
                      Border.all(color: _kCyan.withValues(alpha: 0.35), width: 1.5),
                ),
                child: Icon(Icons.person_rounded, color: _kCyan, size: 28),
              ),
              // نقطة الحضور
              Positioned(
                bottom: 1,
                right: 1,
                child: Container(
                  width: 12,
                  height: 12,
                  decoration: BoxDecoration(
                    color: const Color(0xFF00E676),
                    shape: BoxShape.circle,
                    border: Border.all(color: _kBg, width: 2),
                    boxShadow: [
                      BoxShadow(
                    color: const Color(0xFF00E676).withValues(alpha: 0.5),
                        blurRadius: 6,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  box.read(BoxName.name) ?? 'Guest',
                  style: TextStyle(
                    color: _kText,
                    fontSize: 17,
                    fontWeight: FontWeight.w700,
                    letterSpacing: 0.3,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 5),
                Row(
                  children: [
                    Container(
                      width: 5,
                      height: 5,
                      decoration:
                          BoxDecoration(color: _kCyan, shape: BoxShape.circle),
                    ),
                    const SizedBox(width: 6),
                    Text(
                      "Siro Passenger".tr,
                      style: TextStyle(
                        color: _kTextMuted,
                        fontSize: 12,
                        letterSpacing: 0.4,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ── أزرار الإجراءات السريعة ───────────────────────────────────────────────
  Widget _buildQuickActionButtons() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Row(
        children: [
          _QuickBtn(
            icon: Icons.person_outline_rounded,
            label: 'Profile'.tr,
            onTap: () => Get.to(() => PassengerProfilePage()),
          ),
          const SizedBox(width: 8),
          _QuickBtn(
            icon: Icons.notifications_none_rounded,
            label: 'Alerts'.tr,
            onTap: () => Get.to(() => const NotificationPage()),
          ),
          const SizedBox(width: 8),
          _QuickBtn(
            icon: Icons.settings_outlined,
            label: 'Settings'.tr,
            onTap: () => Get.to(() => const SettingPage()),
          ),
        ],
      ),
    );
  }

  Widget _buildDivider() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      height: 1,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.transparent,
            _kCyan.withValues(alpha: 0.15),
            Colors.transparent,
          ],
        ),
      ),
    );
  }

  void _launchDriverAppUrl() async {
    final String driverAppUrl;
    if (defaultTargetPlatform == TargetPlatform.android) {
      driverAppUrl =
          'https://play.google.com/store/apps/details?id=com.siro_driver';
    } else if (defaultTargetPlatform == TargetPlatform.iOS) {
      driverAppUrl =
          'https://apps.apple.com/st/app/siro-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 _QuickBtn extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;

  const _QuickBtn({
    required this.icon,
    required this.label,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 12),
          decoration: BoxDecoration(
            color: _kBgSurface,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: _kCyan.withValues(alpha: 0.12), width: 1),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, color: _kCyan, size: 22),
              const SizedBox(height: 6),
              Text(
                label,
                style: TextStyle(
                  color: _kTextMuted,
                  fontSize: 11,
                  letterSpacing: 0.4,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── عنصر القائمة ─────────────────────────────────────────────────────────────
class MenuListItem extends StatelessWidget {
  const MenuListItem({
    super.key,
    required this.title,
    required this.onTap,
    required this.icon,
    this.color,
    this.isDestructive = false,
  });

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

  @override
  Widget build(BuildContext context) {
    final iconColor = isDestructive
        ? const Color(0xFFFF5252)
        : (color ?? _kCyan.withValues(alpha: 0.80));
    final textColor =
        isDestructive ? const Color(0xFFFF5252) : (color ?? _kText);

    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        splashColor: _kCyan.withValues(alpha: 0.07),
        highlightColor: _kCyan.withValues(alpha: 0.04),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          child: Row(
            children: [
              // أيقونة بخلفية دقيقة
              Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  color: isDestructive
                      ? const Color(0xFFFF5252).withValues(alpha: 0.08)
                      : _kCyan.withValues(alpha: 0.07),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(icon, size: 19, color: iconColor),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Text(
                  title.tr,
                  style: TextStyle(
                    color: textColor,
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    letterSpacing: 0.2,
                  ),
                ),
              ),
              Icon(
                Icons.chevron_right_rounded,
                color: _kTextMuted.withValues(alpha: 0.4),
                size: 18,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── رسّام الشبكة ──────────────────────────────────────────────────────────────
class _MenuGridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = AppColor.cyanBlue.withValues(alpha: 0.04)
      ..strokeWidth = 0.5;
    const spacing = 36.0;
    for (double y = 0; y < size.height; y += spacing) {
      canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
    }
    for (double x = 0; x < size.width; x += spacing) {
      canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
    }
  }

  @override
  bool shouldRepaint(_MenuGridPainter old) => false;
}
