import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/table_names.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart';

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/toast.dart';
import '../../../controller/home/map_passenger_controller.dart';
import '../../../main.dart';

// ---------------------------------------------------
// -- Widget for Destination Point Search (Optimized) --
// ---------------------------------------------------

/// A more optimized and cleaner implementation of the destination search form.
///
/// Improvements:
/// 1.  **Widget Refactoring**: The UI is broken down into smaller, focused widgets
///     (_SearchField, _QuickActions, _SearchResults) to prevent unnecessary rebuilds.
/// 2.  **State Management Scoping**: `GetBuilder` is used only on widgets that
///     actually need to update, not the entire form.
/// 3.  **Reduced Build Logic**: Logic like reading from `box` is done once.
/// 4.  **Readability**: Code is cleaner and easier to follow.
GetBuilder<MapPassengerController> formSearchPlacesDestenation() {
  // --- [تحسين] قراءة القيم مرة واحدة في بداية البناء ---
  // Store box values in local variables to avoid repeated calls inside the build method.
  final String addWorkValue =
      box.read(BoxName.addWork)?.toString() ?? 'addWork';
  final String addHomeValue =
      box.read(BoxName.addHome)?.toString() ?? 'addHome';

  // --- [ملاحظة] تأكد من أن القيم الأولية موجودة ---
  // This initialization can be moved to your app's startup logic or a splash screen controller.
  if (addWorkValue.isEmpty || addHomeValue.isEmpty) {
    box.write(BoxName.addWork, 'addWork');
    box.write(BoxName.addHome, 'addHome');
  }

  return GetBuilder<MapPassengerController>(
    id: 'destination_form', // Use an ID to allow targeted updates
    builder: (controller) {
      return Column(
        children: [
          // --- Widget for the search text field ---
          _SearchField(controller: controller),

          // --- Widget for "Add Work" and "Add Home" buttons ---
          _QuickActions(
            controller: controller,
            addWorkValue: addWorkValue,
            addHomeValue: addHomeValue,
          ),

          // --- Widget for displaying search results, wrapped in its own GetBuilder ---
          _SearchResults(),
        ],
      );
    },
  );
}

// ---------------------------------------------------
// -- Private Helper Widgets for Cleaner Code --
// ---------------------------------------------------

/// A dedicated widget for the search input field.
class _SearchField extends StatefulWidget {
  final MapPassengerController controller;

  const _SearchField({required this.controller});

  @override
  State<_SearchField> createState() => _SearchFieldState();
}

class _SearchFieldState extends State<_SearchField> {
  Timer? _debounce;

  // --- [إصلاح] Listener لتحديث الواجهة عند تغيير النص لإظهار/إخفاء زر المسح ---
  void _onTextChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    // Add listener to update the suffix icon when text changes
    widget.controller.placeDestinationController.addListener(_onTextChanged);
  }

  // --- [تحسين] إضافة Debouncer لتأخير البحث أثناء الكتابة ---
  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      if (query.length > 2) {
        widget.controller.getPlaces();
        widget.controller.changeHeightPlaces();
      } else if (query.isEmpty) {
        widget.controller.clearPlacesDestination();
        widget.controller.changeHeightPlaces();
      }
    });
  }

  @override
  void dispose() {
    _debounce?.cancel();
    // Remove the listener to prevent memory leaks
    widget.controller.placeDestinationController.removeListener(_onTextChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: widget.controller.placeDestinationController,
              onChanged: _onSearchChanged,
              decoration: InputDecoration(
                hintText: widget.controller.hintTextDestinationPoint,
                hintStyle: AppStyle.subtitle.copyWith(color: Colors.grey[600]),
                prefixIcon:
                    const Icon(Icons.search, color: AppColor.primaryColor),
                // --- [إصلاح] تم استبدال Obx بشرط بسيط لأن `setState` يعيد بناء الواجهة الآن ---
                suffixIcon: widget
                        .controller.placeDestinationController.text.isNotEmpty
                    ? IconButton(
                        icon: Icon(Icons.clear, color: Colors.grey[400]),
                        onPressed: () {
                          widget.controller.placeDestinationController.clear();
                          // The listener will automatically handle the UI update
                          // And _onSearchChanged will handle clearing the results
                        },
                      )
                    : null, // Use null instead of SizedBox for better practice
                contentPadding: const EdgeInsets.symmetric(
                    horizontal: 16.0, vertical: 10.0),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0),
                  borderSide: BorderSide.none,
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8.0),
                  borderSide: BorderSide(color: AppColor.primaryColor),
                ),
                filled: true,
                fillColor: Colors.grey[50],
              ),
            ),
          ),
          const SizedBox(width: 8.0),
          IconButton(
            onPressed: () {
              widget.controller.changeMainBottomMenuMap();
              widget.controller.changePickerShown();
            },
            icon: Icon(Icons.location_on_outlined,
                color: AppColor.accentColor, size: 30),
            tooltip: widget.controller.isAnotherOreder
                ? 'Pick destination on map'.tr
                : 'Pick on map'.tr,
          ),
        ],
      ),
    );
  }
}

/// A dedicated widget for the quick action buttons (Work/Home).
class _QuickActions extends StatelessWidget {
  final MapPassengerController controller;
  final String addWorkValue;
  final String addHomeValue;

  const _QuickActions({
    required this.controller,
    required this.addWorkValue,
    required this.addHomeValue,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          _buildQuickActionButton(
            icon: Icons.work_outline,
            text: addWorkValue == 'addWork' ? 'Add Work'.tr : 'To Work'.tr,
            onTap: () {
              if (addWorkValue == 'addWork') {
                controller.workLocationFromMap = true;
                controller.changeMainBottomMenuMap();
                controller.changePickerShown();
              } else {
                _handleQuickAction(controller, BoxName.addWork, 'To Work');
              }
            },
            onLongPress: () => _showChangeLocationDialog(controller, 'Work'),
          ),
          _buildQuickActionButton(
            icon: Icons.home_outlined,
            text: addHomeValue == 'addHome' ? 'Add Home'.tr : 'To Home'.tr,
            onTap: () {
              if (addHomeValue == 'addHome') {
                controller.homeLocationFromMap = true;
                controller.changeMainBottomMenuMap();
                controller.changePickerShown();
              } else {
                _handleQuickAction(controller, BoxName.addHome, 'To Home');
              }
            },
            onLongPress: () => _showChangeLocationDialog(controller, 'Home'),
          ),
        ],
      ),
    );
  }
}

/// A dedicated widget for the search results list.
/// It uses its own `GetBuilder` to only rebuild when the list of places changes.
class _SearchResults extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetBuilder<MapPassengerController>(
      id: 'places_list', // Use a specific ID for targeted updates
      builder: (controller) {
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          height: controller.placesDestination.isNotEmpty ? 300 : 0,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.0),
          ),
          margin: const EdgeInsets.symmetric(horizontal: 16.0),
          child: ListView.separated(
            shrinkWrap: true,
            physics: const ClampingScrollPhysics(),
            itemCount: controller.placesDestination.length,
            separatorBuilder: (context, index) =>
                const Divider(height: 1, color: Colors.grey),
            itemBuilder: (BuildContext context, int index) {
              final res = controller.placesDestination[index];
              final title = res['name_ar'] ?? res['name'] ?? 'Unknown Place';
              final address = res['address'] ?? 'Details not available';
              final latitude = res['latitude'];
              final longitude = res['longitude'];

              return ListTile(
                leading: const Icon(Icons.place, size: 30, color: Colors.grey),
                title: Text(
                  title,
                  style:
                      AppStyle.subtitle.copyWith(fontWeight: FontWeight.w500),
                ),
                subtitle: Text(
                  address,
                  style: TextStyle(color: Colors.grey[600], fontSize: 12),
                ),
                trailing: IconButton(
                  icon: const Icon(Icons.favorite_border, color: Colors.grey),
                  onPressed: () => _handleAddToFavorites(
                      context, latitude, longitude, title),
                ),
                onTap: () => _handlePlaceSelection(
                    controller, latitude, longitude, title, index),
              );
            },
          ),
        );
      },
    );
  }

  // --- [تحسين] استخراج المنطق المعقد إلى دوال مساعدة ---
  Future<void> _handleAddToFavorites(BuildContext context, dynamic latitude,
      dynamic longitude, String title) async {
    if (latitude != null && longitude != null) {
      await sql.insertMapLocation({
        'latitude': latitude,
        'longitude': longitude,
        'name': title,
        'rate': 'N/A',
      }, TableName.placesFavorite);

      Toast.show(
        context,
        '$title ${'Saved Successfully'.tr}',
        AppColor.primaryColor,
      );
    } else {
      Toast.show(
        context,
        'Invalid location data',
        AppColor.redColor,
      );
    }
  }

  Future<void> _handlePlaceSelection(MapPassengerController controller,
      dynamic latitude, dynamic longitude, String title, int index) async {
    if (latitude == null || longitude == null) {
      Toast.show(Get.context!, 'Invalid location data', AppColor.redColor);
      return;
    }

    // Save to recent locations
    await sql.insertMapLocation({
      'latitude': latitude,
      'longitude': longitude,
      'name': title,
      'rate': 'N/A',
      'createdAt': DateTime.now().toIso8601String(),
    }, TableName.recentLocations);

    final destLatLng = LatLng(
        double.parse(latitude.toString()), double.parse(longitude.toString()));

    if (controller.isAnotherOreder) {
      // **Another Order Flow**
      await _handleAnotherOrderSelection(controller, destLatLng);
    } else {
      // **Regular Order Flow**
      _handleRegularOrderSelection(controller, destLatLng, index);
    }
  }

  Future<void> _handleAnotherOrderSelection(
      MapPassengerController controller, LatLng destination) async {
    controller.myDestination = destination;
    controller.clearPlacesDestination(); // Helper method in controller

    await controller.getDirectionMap(
        '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
        '${controller.myDestination.latitude},${controller.myDestination.longitude}');

    controller.isPickerShown = false;
    controller.passengerStartLocationFromMap = false;
    controller.changeMainBottomMenuMap();
    controller.showBottomSheet1();
  }

  void _handleRegularOrderSelection(
      MapPassengerController controller, LatLng destination, int index) {
    controller.passengerLocation = controller.newMyLocation;
    controller.myDestination = destination;
    controller.convertHintTextDestinationNewPlaces(index);

    controller.clearPlacesDestination(); // Helper method in controller

    controller.changeMainBottomMenuMap();
    controller.passengerStartLocationFromMap = true;
    controller.isPickerShown = true;
  }
}

// ---------------------------------------------------
// -- Helper Functions (kept from original code) --
// ---------------------------------------------------

Widget _buildQuickActionButton({
  required IconData icon,
  required String text,
  VoidCallback? onTap,
  VoidCallback? onLongPress,
}) {
  return InkWell(
    onTap: onTap,
    onLongPress: onLongPress,
    child: Container(
      padding: const EdgeInsets.all(8.0),
      decoration: BoxDecoration(
        color: AppColor.blueColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: AppColor.blueColor.withOpacity(0.3)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: AppColor.blueColor),
          const SizedBox(height: 4.0),
          Text(
            text,
            textAlign: TextAlign.center,
            style: AppStyle.title.copyWith(
                color: AppColor.blueColor, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    ),
  );
}

void _showChangeLocationDialog(
    MapPassengerController controller, String locationType) {
  Get.defaultDialog(
    title: 'Change $locationType location?'.tr,
    middleText: '',
    confirm: MyElevatedButton(
      title: 'Yes'.tr,
      onPressed: () {
        Get.back();
        if (locationType == 'Work') {
          controller.workLocationFromMap = true;
        } else {
          controller.homeLocationFromMap = true;
        }
        controller.changeMainBottomMenuMap();
        controller.changePickerShown();
      },
    ),
  );
}

void _handleQuickAction(
    MapPassengerController controller, String boxName, String hintText) async {
  // --- [تحسين] قراءة وتحويل الإحداثيات بأمان أكبر ---
  try {
    final locationString = box.read(boxName).toString();
    final parts = locationString.split(',');
    final latLng = LatLng(
      double.parse(parts[0]),
      double.parse(parts[1]),
    );

    controller.hintTextDestinationPoint = hintText;
    controller.changeMainBottomMenuMap();

    await controller.getDirectionMap(
      '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
      '${latLng.latitude},${latLng.longitude}',
    );

    controller.currentLocationToFormPlaces = false;
    controller.clearPlacesDestination(); // Helper method in controller
    controller.passengerStartLocationFromMap = false;
    controller.isPickerShown = false;
    controller.showBottomSheet1();
  } catch (e) {
    // Handle error if parsing fails
    print("Error handling quick action: $e");
    Toast.show(Get.context!, "Failed to get location".tr, AppColor.redColor);
  }
}
