import 'package:siro_driver/constant/box_name.dart';
import 'package:siro_driver/controller/firebase/local_notification.dart';
import 'package:siro_driver/main.dart';
import 'package:siro_driver/views/home/Captin/driver_map_page.dart';
import 'package:siro_driver/views/home/Captin/orderCaptin/vip_order_page.dart';
import 'package:siro_driver/views/auth/syria/registration_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:siro_driver/controller/home/captin/home_captain_controller.dart';
import 'package:siro_driver/views/widgets/mydialoug.dart';

import '../../../../../constant/links.dart';
import '../../../../../controller/firebase/notification_service.dart';
import '../../../../../controller/functions/crud.dart';
import '../../../../../controller/home/captin/order_request_controller.dart';
import '../../../../../print.dart';
import '../../../../Rate/ride_calculate_driver.dart';
import 'package:siro_driver/views/home/statistics/statistics_dashboard.dart';

// ─────────────────────────────────────────────
//  Design Tokens (Responsive)
// ─────────────────────────────────────────────
class _T {
  static Color surface(BuildContext context) =>
      Theme.of(context).brightness == Brightness.dark
          ? const Color(0xFF16213E)
          : Colors.white;

  static const Color accent = Color(0xFFF0A500);
  static const Color blue = Color(0xFF3498DB);

  static Color border(BuildContext context) =>
      Theme.of(context).brightness == Brightness.dark
          ? const Color(0xFF2A2A4A)
          : Colors.grey.withOpacity(0.2);

  static const double radius = 14.0;
}

// ─────────────────────────────────────────────
//  Left Side Menu
// ─────────────────────────────────────────────

/// Returns the vertical icon column anchored to the left-center of the map.
GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
  return GetBuilder<HomeCaptainController>(
    builder: (ctrl) => Positioned(
      // Place just above the bottom status bar
      bottom: 100,
      left: 10,
      child: Builder(builder: (context) {
        return Container(
          decoration: BoxDecoration(
            color: _T.surface(context),
            borderRadius: BorderRadius.circular(_T.radius),
            border: Border.all(color: _T.border(context)),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 10,
                offset: const Offset(2, 4),
              ),
            ],
          ),
          padding: const EdgeInsets.symmetric(vertical: 6),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // ── 1. Active Ride shortcut ──────────
              _MenuIcon(
                icon: Icons.directions_car_rounded,
                color:
                    box.read(BoxName.rideArgumentsFromBackground) == 'failure'
                        ? Colors.red.shade400
                        : Colors.green.shade400,
                tooltip: 'Active Ride'.tr,
                onTap: () async {
                  await checkForPendingOrderFromServer();
                  if (box.read(BoxName.rideArgumentsFromBackground) !=
                      'failure') {
                    Get.to(
                      () => PassengerLocationMapPage(),
                      arguments: box.read(BoxName.rideArgumentsFromBackground),
                    );
                  } else {
                    MyDialog().getDialog(
                      'Ride info'.tr,
                      'you dont have accepted ride'.tr,
                      () => Get.back(),
                    );
                  }
                },
                onLongPress: () {
                  box.write(BoxName.rideArgumentsFromBackground, 'failure');
                  box.write(BoxName.statusDriverLocation, 'off');
                  box.write(BoxName.rideStatus, 'no_ride');
                  Log.print(box.read(BoxName.statusDriverLocation));
                  ctrl.update();
                },
              ),

              _Divider(context),

              // ── 2. Earnings Chart ────────────────
              _MenuIcon(
                icon: FontAwesome5.chart_bar,
                color: _T.blue,
                tooltip: 'Statistics'.tr,
                onTap: () {
                  Get.to(() => StatisticsDashboard());
                },
                onLongPress: () =>
                    box.write(BoxName.statusDriverLocation, 'off'),
              ),

              // ── 3. VIP Orders (2023+ cars only) ──
              if (int.tryParse(box.read(BoxName.carYear).toString()) != null &&
                  int.parse(box.read(BoxName.carYear).toString()) > 2023) ...[
                _Divider(context),
                _MenuIcon(
                  icon: Octicons.watch,
                  color: _T.accent,
                  tooltip: 'VIP Orders'.tr,
                  onTap: () => Get.to(() => const VipOrderPage()),
                ),
              ],

              // _Divider(context),

              // // ── 4. Driver Registration ──────────
              // _MenuIcon(
              //   icon: Icons.person_add_alt_1_rounded,
              //   color: Colors.purple.shade400,
              //   tooltip: 'Registration'.tr,
              //   onTap: () => Get.to(() => const RegistrationView()),
              // ),
            ],
          ),
        );
      }),
    ),
  );
}

// ─────────────────────────────────────────────
//  Reusable sub-widgets
// ─────────────────────────────────────────────

class _MenuIcon extends StatelessWidget {
  final IconData icon;
  final Color color;
  final String tooltip;
  final VoidCallback onTap;
  final VoidCallback? onLongPress;

  const _MenuIcon({
    required this.icon,
    required this.color,
    required this.tooltip,
    required this.onTap,
    this.onLongPress,
  });

  @override
  Widget build(BuildContext context) => Tooltip(
        message: tooltip,
        child: InkWell(
          onTap: onTap,
          onLongPress: onLongPress,
          borderRadius: BorderRadius.circular(10),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            child: Icon(icon, color: color, size: 26),
          ),
        ),
      );
}

/// Thin separator between icons
class _Divider extends StatelessWidget {
  final BuildContext context;
  const _Divider(this.context);

  @override
  Widget build(BuildContext context) => Container(
        height: 1,
        width: 32,
        margin: const EdgeInsets.symmetric(horizontal: 6),
        color: _T.border(this.context),
      );
}

// ─────────────────────────────────────────────
//  Server Helpers (unchanged logic)
// ─────────────────────────────────────────────

bool _isCheckingPendingOrder = false;

Future<void> checkForPendingOrderFromServer() async {
  if (_isCheckingPendingOrder) return;
  if (Get.currentRoute == '/passenger-location-map') return;

  final driverId = box.read(BoxName.driverID)?.toString();
  if (driverId == null) return;

  _isCheckingPendingOrder = true;

  try {
    var response = await CRUD().post(
      link: AppLink.getArgumentAfterAppliedFromBackground,
      payload: {'driver_id': driverId},
    );
    Log.print('response: $response');

    if (response['status'] == 'success') {
      final Map<String, dynamic> orderInfo = response['message'];
      final Map<String, dynamic> rideArgs =
          _transformServerDataToAppArguments(orderInfo);

      final customerToken = response['message']['token_passenger'];
      final orderId = response['message']['ride_id'].toString();

      box.write(BoxName.rideArgumentsFromBackground, rideArgs);
      box.write(BoxName.statusDriverLocation, 'on');
      box.write(BoxName.rideStatus, 'Apply');
      Get.put(OrderRequestController()).changeApplied();

      Get.to(
        () => PassengerLocationMapPage(),
        arguments: box.read(BoxName.rideArgumentsFromBackground),
      );
    } else {
      box.write(BoxName.rideArgumentsFromBackground, 'failure');
    }
  } catch (_) {
    // silent
  } finally {
    _isCheckingPendingOrder = false;
  }
}

Map<String, dynamic> _transformServerDataToAppArguments(
    Map<String, dynamic> d) {
  String s(String key, [String def = 'unknown']) => d[key]?.toString() ?? def;

  return {
    'passengerLocation': s('passenger_location'),
    'passengerDestination': s('passenger_destination'),
    'Duration': s('duration'),
    'totalCost': s('total_cost'),
    'Distance': s('distance'),
    'name': s('name'),
    'phone': s('phone'),
    'email': s('email'),
    'tokenPassenger': s('token_passenger'),
    'direction': s('direction_url'),
    'DurationToPassenger': s('duration_to_passenger'),
    'rideId': s('ride_id'),
    'passengerId': s('passenger_id'),
    'driverId': s('driver_id'),
    'durationOfRideValue': s('duration_of_ride'),
    'paymentAmount': s('payment_amount'),
    'paymentMethod': s('payment_method'),
    'passengerWalletBurc': s('passenger_wallet_burc'),
    'timeOfOrder': s('time_of_order'),
    'totalPassenger': s('total_passenger'),
    'carType': s('car_type'),
    'kazan': s('kazan'),
    'startNameLocation': s('start_name_location'),
    'endNameLocation': s('end_name_location'),
    'step0': s('step0'),
    'step1': s('step1'),
    'step2': s('step2'),
    'step3': s('step3'),
    'step4': s('step4'),
    'WalletChecked': (d['wallet_checked'] == 1).toString(),
    'isHaveSteps': (d['has_steps'] == 1) ? 'startEnd' : 'noSteps',
  };
}

void _sendAcceptanceNotification(String? customerToken, dynamic rideId) {
  if (customerToken == null || customerToken.isEmpty) return;

  List<String> body = [
    box.read(BoxName.driverID).toString(),
    box.read(BoxName.nameDriver).toString(),
    box.read(BoxName.tokenDriver).toString(),
    rideId.toString(),
  ];

  NotificationService.sendNotification(
    target: customerToken,
    title: 'Accepted Ride'.tr,
    body: 'your ride is Accepted'.tr,
    isTopic: false,
    tone: 'start',
    driverList: body,
    category: 'Accepted Ride',
  );
}
