import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:just_audio/just_audio.dart';
import 'package:sefer_driver/constant/api_key.dart';
import 'package:sefer_driver/models/overlay_service.dart';
import '../../../../constant/box_name.dart';
import '../../../../constant/links.dart';
import '../../../../controller/firebase/firbase_messge.dart';
import '../../../../controller/firebase/local_notification.dart';
import '../../../../controller/firebase/notification_service.dart';
import '../../../../controller/functions/crud.dart';
import '../../../../main.dart';
import '../../../../models/model/order_data.dart';
import '../../../../print.dart';

// === Enhanced Colors for Better Readability ===
class AppColors {
  static const primary = Color(0xFF1A252F);
  static const card = Color(0xFF2C3E50);
  static const white = Colors.white;
  static const gray = Color(0xFFBDC3C7);
  static const lightGray = Color(0xFFECF0F1);
  static const accent = Color(0xFF00BCD4);
  static const accept = Color(0xFF4CAF50);
  static const reject = Color(0xFFFF5722);
  static const highlight = Color(0xFFFFC107);
  static const priceHighlight = Color(0xFF00E676);
  static const urgentRed = Color(0xFFD32F2F);
}

class OrderOverlay extends StatefulWidget {
  const OrderOverlay({Key? key}) : super(key: key);

  @override
  State<OrderOverlay> createState() => _OrderOverlayState();
}

class _OrderOverlayState extends State<OrderOverlay>
    with WidgetsBindingObserver {
  // === State Variables ===
  OrderData? orderData;
  Timer? timer;
  int remainingSeconds = 10;
  final AudioPlayer audioPlayer = AudioPlayer();
  bool buttonsEnabled = true;
  final String mapApiKey = AK.mapAPIKEY;
  final CRUD _crud = CRUD();

  final NotificationController notificationController =
      Get.put(NotificationController());
  // === Getters ===
  bool get canShowMap {
    if (orderData == null || mapApiKey.isEmpty) return false;
    final start = orderData!.startCoordinates;
    final end = orderData!.endCoordinates;
    return start?['lat'] != null &&
        start?['lng'] != null &&
        end?['lat'] != null &&
        end?['lng'] != null;
  }

  String get staticMapUrl {
    if (!canShowMap) return "";
    final start = orderData!.startCoordinates!;
    final end = orderData!.endCoordinates!;
    final startMarker = Uri.encodeComponent("${start['lat']},${start['lng']}");
    final endMarker = Uri.encodeComponent("${end['lat']},${end['lng']}");

    return "https://maps.googleapis.com/maps/api/staticmap?"
        "size=600x150&maptype=roadmap"
        "&markers=color:green%7Clabel:S%7C$startMarker"
        "&markers=color:red%7Clabel:D%7C$endMarker"
        "&path=color:0x007bff%7Cweight:5%7C$startMarker%7C$endMarker"
        "&key=$mapApiKey";
  }

  // === Lifecycle ===
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    FlutterOverlayWindow.overlayListener.listen((event) {
      if (mounted) _processEventData(event);
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    _stopAudio();
    audioPlayer.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _checkOverlayStatus();
    }
  }

  List myList = [];
  // === Setup & Listeners ===
  void _setupOverlayListener() {
    FlutterOverlayWindow.overlayListener.listen((event) {
      if (mounted) _processEventData(event);
    });
  }

  void _processEventData(dynamic event) {
    _log("Received event: $event");
    if (event is List<dynamic>) {
      try {
        myList = event;
        final newOrder = OrderData.fromList(event);
        _log("Parsed OrderData: ${newOrder.toMap()}");
        setState(() {
          orderData = newOrder;
        });
        _resetAndStartTimer();
      } catch (e, s) {
        _log("Error parsing OrderData: $e\nStackTrace: $s");
      }
    } else {
      _log("Unexpected data format: $event");
    }
  }

  void _checkOverlayStatus() async {
    bool isActive = await FlutterOverlayWindow.isActive();
    if (isActive && mounted && orderData != null) {
      if (remainingSeconds > 0 && (timer == null || !timer!.isActive)) {
        _resetAndStartTimer();
      }
    }
  }

  // === Timer Management ===
  void _resetAndStartTimer() {
    timer?.cancel();
    audioPlayer.stop();
    setState(() {
      buttonsEnabled = true;
      remainingSeconds = _calculateTimerDuration();
    });
    _playAudio();
    _startTimer();
  }

  int _calculateTimerDuration() {
    if (orderData?.durationToPassengerMinutes != null &&
        orderData!.durationToPassengerMinutes > 0) {
      int duration = orderData!.durationToPassengerMinutes * 60;
      return duration > 10 ? 10 : duration;
    }
    return 10;
  }

  void _startTimer() {
    if (orderData == null) return;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        _stopAudio();
        return;
      }
      setState(() {
        if (remainingSeconds > 0) {
          remainingSeconds--;
        } else {
          timer.cancel();
          _stopAudio();
          if (buttonsEnabled) _handleOrderTimeout();
        }
      });
    });
  }

  // === Audio Management ===
  void _playAudio() async {
    try {
      await audioPlayer.setAsset('assets/order.mp3', preload: true);
      await audioPlayer.setLoopMode(LoopMode.one);
      await audioPlayer.play();
    } catch (e) {
      _log('Error playing audio: $e');
    }
  }

  void _stopAudio() {
    audioPlayer.stop();
  }

  String _getData(int index, {String defaultValue = ''}) {
    if (myList.length > index && myList[index] != null) {
      return myList[index].toString();
    }
    return defaultValue;
  }

  // === Order Actions ===
  Future<void> _acceptOrder() async {
    if (!buttonsEnabled || orderData == null) return;
    _disableButtonsAndProcess();
    _log("Order ACCEPTED: ${orderData!.orderId}");

    try {
      final driverId = box.read(BoxName.driverID)?.toString();
      if (driverId == null) {
        _log("Error: Driver ID is null. Closing overlay.");
        await _closeOverlay();
        return;
      }
      var res = await CRUD()
          .post(link: "${AppLink.ride}/rides/acceptRide.php", payload: {
        'id': orderData!.orderId,
        'rideTimeStart': DateTime.now().toString(),
        'status': 'Apply',
        'driver_id': box.read(BoxName.driverID),
        'passengerToken': _getData(9),
      });

      final payload = {
        // بيانات أساسية
        'driver_id': driverId,
        'status': 'Apply',
        'passengerLocation': _getData(0),
        'passengerDestination': _getData(1),
        'Duration': _getData(4),
        'totalCost': _getData(26),
        'Distance': _getData(5),
        'name': _getData(8),
        'phone': _getData(10),
        'email': _getData(28),
        'WalletChecked': _getData(13),
        'tokenPassenger': _getData(9),
        'direction': staticMapUrl.toString(),
        'DurationToPassenger': _getData(15),
        'rideId': orderData!.orderId,
        'passengerId': _getData(7),
        'durationOfRideValue': _getData(19),
        'paymentAmount': _getData(2),
        'paymentMethod': _getData(13) == 'true' ? 'visa' : 'cash',
        'isHaveSteps': _getData(20),
        'step0': myList[21].toString(),
        'step1': myList[22].toString(),
        'step2': myList[23].toString(),
        'step3': myList[24].toString(),
        'step4': myList[25].toString(),
        'passengerWalletBurc': myList[26].toString(),
        'carType': myList[31].toString(),
        'kazan': myList[32].toString(),
        'startNameLocation': myList[29].toString(),
        'endNameLocation': myList[30].toString(),
        // الحقول الإضافية التي يجب تضمينها
        'timeOfOrder': DateTime.now().toIso8601String(),
        'totalPassenger': _getData(2),
      };
      Log.print('payload: ${payload}');
      CRUD().post(
        link: AppLink.addOverLayStatus,
        payload: payload,
      );
      if (res != "failure") {
        // Using rideId (_getData(16)) for order_id consistently

        _log("Server update successful. Writing to storage.");
        notificationController.showNotification(
          "Order Accepted".tr,
          "Open app and go to passenger".tr,
          'ding',
          '',
        );

        // 3. الخطوة الأهم: فتح التطبيق وإغلاق النافذة
        try {
          // استدعاء الميثود التي تم تحديثها في الخطوة 1
          await OverlayMethodChannel.bringToForeground();
        } catch (e) {
          _log("Failed to bring app to foreground: $e");
        }
        await _closeOverlay();
      } else {
        _log("Failed to update order status on server: $res");
        notificationController.showNotification(
          "Order Accepted by another driver".tr,
          "Open app and go to passenger".tr,
          'ding',
          '',
        );
        await _closeOverlay();
      }
    } catch (e, s) {
      _log(
          "A critical error occurred during server update: $e\nStackTrace: $s");
      if (mounted) setState(() => buttonsEnabled = true);

      _log("Error in accept order: $e");
      await _closeOverlay();
      // حتى في حال الخطأ، نحاول فتح التطبيق ليرى السائق ما حدث
      await OverlayMethodChannel.bringToForeground();

      return;
    }
  }

  // Your list parsing for 'customerToken' should be something like:
  // customerToken: list.length > a_certain_index ? list[a_certain_index].toString() : null,
  Future<void> _rejectOrder() async {
    if (!buttonsEnabled || orderData == null) return;
    _disableButtonsAndProcess();
    _log("Order REJECTED: ${orderData!.orderId}");
    box.write(BoxName.rideStatus, 'reject');
    Log.print('rideStatus from overlay 303  : ${box.read(BoxName.rideStatus)}');
    await _apiRefuseOrder(orderData!.orderId);
    await _closeOverlay();
  }

  void _handleOrderTimeout() {
    if (orderData == null) return;
    _log("Order TIMED OUT: ${orderData!.orderId}");
    _rejectOrder();
  }

  Future<void> _apiRefuseOrder(String orderID) async {
    if (orderID == "N/A") {
      _log("Cannot refuse order with N/A ID");
      return;
    }
    try {
      final driverId = box.read(BoxName.driverID)?.toString();
      if (driverId == null) {
        _log("Driver ID is null, cannot refuse order");
        return;
      }
      CRUD().post(link: AppLink.addDriverOrder, payload: {
        'driver_id': driverId,
        'order_id': orderID,
        'status': 'Refused'
      });

      _log("Order $orderID refused successfully");
    } catch (e) {
      _log("Error in _apiRefuseOrder for $orderID: $e");
    }
  }

  // === Helper Methods ===
  void _disableButtonsAndProcess() {
    setState(() => buttonsEnabled = false);
    timer?.cancel();
    _stopAudio();
  }

  Future<void> _closeOverlay() async {
    _stopAudio();
    timer?.cancel();
    if (await FlutterOverlayWindow.isActive()) {
      await FlutterOverlayWindow.closeOverlay();
    }
  }

  void _log(String message) {
    // A simple logger to distinguish overlay logs
    print("OVERLAY_LOG: $message");
  }

  // === UI Build Methods ===
  @override
  Widget build(BuildContext context) {
    // ... (Your entire UI build method remains unchanged) ...
    // The UI code is excellent and doesn't need modification.
    if (orderData == null) {
      return const Material(
          color: Colors.transparent,
          child: Center(
              child: CircularProgressIndicator(color: AppColors.accent)));
    }

    return Material(
      color: Colors.black.withOpacity(0.4),
      child: Center(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
          padding: const EdgeInsets.all(16.0),
          decoration: BoxDecoration(
            color: AppColors.card,
            borderRadius: BorderRadius.circular(20.0),
            border: Border.all(
                color: AppColors.accent.withOpacity(0.3), width: 1.5),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.6),
                blurRadius: 15,
                spreadRadius: 2,
              )
            ],
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                _buildQuickHeader(),
                const SizedBox(height: 12),
                _buildPrimaryInfo(),
                const SizedBox(height: 12),
                if (canShowMap) _buildCompactMap(),
                if (canShowMap) const SizedBox(height: 12),
                _buildSecondaryInfo(),
                const SizedBox(height: 16),
                _buildEnhancedActionButtons(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // All your _build... widget methods (_buildQuickHeader, _buildPrimaryInfo, etc.)
  // are perfectly fine and do not need to be changed.
  // ... Paste all your existing _build... methods here ...
  Widget _buildQuickHeader() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            remainingSeconds <= 3
                ? AppColors.urgentRed
                : remainingSeconds <= 5
                    ? AppColors.highlight
                    : AppColors.accent,
            remainingSeconds <= 3
                ? AppColors.urgentRed.withOpacity(0.7)
                : remainingSeconds <= 5
                    ? AppColors.highlight.withOpacity(0.7)
                    : AppColors.accent.withOpacity(0.7),
          ],
        ),
        borderRadius: BorderRadius.circular(15),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Icon(Icons.drive_eta_rounded, color: AppColors.white, size: 24),
              const SizedBox(width: 8),
              Text(
                "طلب جديد".tr,
                style: const TextStyle(
                    color: AppColors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w600),
              ),
            ],
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
            decoration: BoxDecoration(
              color: AppColors.white.withOpacity(0.9),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              "$remainingSeconds ث",
              style: TextStyle(
                color: remainingSeconds <= 3
                    ? AppColors.urgentRed
                    : remainingSeconds <= 5
                        ? AppColors.highlight
                        : AppColors.accent,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPrimaryInfo() {
    final order = orderData!;

    // FIX: Parse the price to a number safely before formatting
    // This handles cases where order.price is a String like "173"
    final num priceValue = num.tryParse(order.price.toString()) ?? 0;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.primary.withOpacity(0.6),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
            color: AppColors.priceHighlight.withOpacity(0.3), width: 1),
      ),
      child: Column(
        children: [
          // Price and Distance - Most Important Info
          Row(
            children: [
              Expanded(
                flex: 3,
                child: _buildHighlightInfo(
                  // FIX: Use the parsed priceValue here
                  "${NumberFormat('#,##0').format(priceValue)} ل.س",
                  "السعر".tr,
                  Icons.monetization_on_rounded,
                  AppColors.priceHighlight,
                  isLarge: true,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                flex: 2,
                child: _buildHighlightInfo(
                  // Ensure tripDistanceKm is treated safely too
                  "${(num.tryParse(order.tripDistanceKm.toString()) ?? 0).toStringAsFixed(1)} كم",
                  "المسافة".tr,
                  Icons.straighten_rounded,
                  AppColors.accent,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Divider(color: AppColors.gray.withOpacity(0.2), thickness: 1),
          const SizedBox(height: 12),
          // Passenger Info and ETA
          Row(
            children: [
              Expanded(
                flex: 2,
                child: _buildPassengerQuickInfo(),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildHighlightInfo(
                  "${order.durationToPassengerMinutes} د",
                  "للوصول".tr,
                  Icons.access_time_filled_rounded,
                  order.durationToPassengerMinutes <= 3
                      ? AppColors.priceHighlight
                      : AppColors.gray,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildHighlightInfo(
      String value, String label, IconData icon, Color color,
      {bool isLarge = false}) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: color.withOpacity(0.3), width: 1),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: isLarge ? 24 : 20),
          const SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              color: AppColors.white,
              fontSize: isLarge ? 20 : 16,
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
          Text(
            label,
            style: TextStyle(
              color: AppColors.lightGray.withOpacity(0.7),
              fontSize: 11,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildPassengerQuickInfo() {
    final order = orderData!;
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
      decoration: BoxDecoration(
        color: AppColors.highlight.withOpacity(0.1),
        borderRadius: BorderRadius.circular(10),
        border:
            Border.all(color: AppColors.highlight.withOpacity(0.3), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.person_rounded, color: AppColors.highlight, size: 18),
              const SizedBox(width: 4),
              Expanded(
                child: Text(
                  order.customerName,
                  style: const TextStyle(
                    color: AppColors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 2),
          Text(
            order.rideType,
            style: TextStyle(
              color: AppColors.lightGray.withOpacity(0.7),
              fontSize: 11,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCompactMap() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(12.0),
      child: Image.network(
        staticMapUrl,
        height: 100, // Reduced from 110
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            height: 100,
            decoration: BoxDecoration(
              color: AppColors.primary.withOpacity(0.3),
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Center(
                child:
                    Icon(Icons.map_outlined, color: AppColors.gray, size: 32)),
          );
        },
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return SizedBox(
            height: 100,
            child: Center(
              child: CircularProgressIndicator(
                value: loadingProgress.expectedTotalBytes != null
                    ? loadingProgress.cumulativeBytesLoaded /
                        loadingProgress.expectedTotalBytes!
                    : null,
                color: AppColors.accent,
                strokeWidth: 2.0,
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSecondaryInfo() {
    final order = orderData!;
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.primary.withOpacity(0.4),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          _buildLocationRow(
            Icons.trip_origin_rounded,
            "من".tr,
            order.startLocationAddress,
            Colors.green.shade300,
          ),
          const SizedBox(height: 8),
          _buildLocationRow(
            Icons.flag_rounded,
            "إلى".tr,
            order.endLocationAddress,
            Colors.red.shade300,
          ),
          if (order.tripDurationMinutes > 0) ...[
            const SizedBox(height: 8),
            Divider(color: AppColors.gray.withOpacity(0.2), thickness: 0.5),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.timer_outlined, color: AppColors.accent, size: 16),
                const SizedBox(width: 4),
                Text(
                  "مدة الرحلة: ${order.tripDurationMinutes} دقيقة".tr,
                  style: const TextStyle(
                    color: AppColors.lightGray,
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ]
        ],
      ),
    );
  }

  Widget _buildLocationRow(
      IconData icon, String label, String address, Color iconColor) {
    return Row(
      children: [
        Icon(icon, color: iconColor, size: 16),
        const SizedBox(width: 8),
        Text(
          "$label: ",
          style: TextStyle(
            color: AppColors.lightGray.withOpacity(0.8),
            fontSize: 12,
            fontWeight: FontWeight.w500,
          ),
        ),
        Expanded(
          child: Text(
            address,
            style: const TextStyle(
              color: AppColors.white,
              fontSize: 12,
            ),
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
          ),
        ),
      ],
    );
  }

  Widget _buildEnhancedActionButtons() {
    return Row(
      children: [
        Expanded(
          child: ElevatedButton(
            onPressed: buttonsEnabled ? _rejectOrder : null,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.reject,
              foregroundColor: AppColors.white,
              padding: const EdgeInsets.symmetric(vertical: 14),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
              disabledBackgroundColor: AppColors.reject.withOpacity(0.3),
              elevation: 3,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.close_rounded, size: 20),
                const SizedBox(width: 6),
                Text(
                  "رفض".tr,
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: ElevatedButton(
            onPressed: buttonsEnabled ? _acceptOrder : null,
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.accept,
              foregroundColor: AppColors.white,
              padding: const EdgeInsets.symmetric(vertical: 14),
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12)),
              disabledBackgroundColor: AppColors.accept.withOpacity(0.3),
              elevation: 3,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Icon(Icons.check_circle_rounded, size: 20),
                const SizedBox(width: 6),
                Text(
                  "قبول".tr,
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
