import 'package:siro_rider/print.dart';
import 'package:siro_rider/views/widgets/mydialoug.dart';
import 'dart:async';

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

import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/functions/toast.dart';
import '../../../controller/home/map/location_search_controller.dart';
import '../../../controller/home/map/map_engine_controller.dart';
import '../../../controller/home/map/ride_lifecycle_controller.dart';
import '../../../controller/home/map/ride_state.dart';
import '../../../main.dart';

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

GetBuilder<LocationSearchController> formSearchPlacesDestenation() {
  final String addWorkValue =
      box.read(BoxName.addWork)?.toString() ?? 'addWork';
  final String addHomeValue =
      box.read(BoxName.addHome)?.toString() ?? 'addHome';

  if (addWorkValue.isEmpty || addHomeValue.isEmpty) {
    box.write(BoxName.addWork, 'addWork');
    box.write(BoxName.addHome, 'addHome');
  }

  return GetBuilder<LocationSearchController>(
    id: 'destination_form',
    builder: (controller) {
      final mapEngine = Get.find<MapEngineController>();
      final rideLifecycle = Get.find<RideLifecycleController>();
      return Column(
        children: [
          _SearchField(
            controller: controller,
            mapEngine: mapEngine,
            rideLifecycle: rideLifecycle,
          ),
          _QuickActions(
            controller: controller,
            mapEngine: mapEngine,
            rideLifecycle: rideLifecycle,
            addWorkValue: addWorkValue,
            addHomeValue: addHomeValue,
          ),
          _SearchResults(
            controller: controller,
            mapEngine: mapEngine,
            rideLifecycle: rideLifecycle,
          ),
        ],
      );
    },
  );
}

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

class _SearchField extends StatefulWidget {
  final LocationSearchController controller;
  final MapEngineController mapEngine;
  final RideLifecycleController rideLifecycle;

  const _SearchField({
    required this.controller,
    required this.mapEngine,
    required this.rideLifecycle,
  });

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

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

  void _onTextChanged() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    widget.controller.placeDestinationController.addListener(_onTextChanged);
  }

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 500), () {
      if (query.length > 2) {
        widget.controller.getPlaces();
        widget.mapEngine.changeHeightPlaces();
      } else if (query.isEmpty) {
        widget.controller.clearPlacesDestination();
        widget.mapEngine.changeHeightPlaces();
      }
    });
  }

  @override
  void dispose() {
    _debounce?.cancel();
    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: Icon(Icons.search, color: AppColor.primaryColor),
                suffixIcon: widget
                        .controller.placeDestinationController.text.isNotEmpty
                    ? IconButton(
                        icon: Icon(Icons.clear, color: Colors.grey[400]),
                        onPressed: () {
                          widget.controller.placeDestinationController.clear();
                        },
                      )
                    : null,
                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.mapEngine.changeMainBottomMenuMap();
              widget.mapEngine.changePickerShown();
            },
            icon: Icon(Icons.location_on_outlined,
                color: AppColor.accentColor, size: 30),
            tooltip: widget.rideLifecycle.isAnotherOreder
                ? 'Pick destination on map'.tr
                : 'Pick on map'.tr,
          ),
        ],
      ),
    );
  }
}

class _QuickActions extends StatelessWidget {
  final LocationSearchController controller;
  final MapEngineController mapEngine;
  final RideLifecycleController rideLifecycle;
  final String addWorkValue;
  final String addHomeValue;

  const _QuickActions({
    required this.controller,
    required this.mapEngine,
    required this.rideLifecycle,
    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;
                mapEngine.changeMainBottomMenuMap();
                mapEngine.changePickerShown();
              } else {
                _handleQuickAction(
                  controller,
                  mapEngine,
                  rideLifecycle,
                  BoxName.addWork,
                  'To Work',
                );
              }
            },
            onLongPress: () =>
                _showChangeLocationDialog(controller, mapEngine, 'Work'),
          ),
          _buildQuickActionButton(
            icon: Icons.home_outlined,
            text: addHomeValue == 'addHome' ? 'Add Home'.tr : 'To Home'.tr,
            onTap: () {
              if (addHomeValue == 'addHome') {
                controller.homeLocationFromMap = true;
                mapEngine.changeMainBottomMenuMap();
                mapEngine.changePickerShown();
              } else {
                _handleQuickAction(
                  controller,
                  mapEngine,
                  rideLifecycle,
                  BoxName.addHome,
                  'To Home',
                );
              }
            },
            onLongPress: () =>
                _showChangeLocationDialog(controller, mapEngine, 'Home'),
          ),
        ],
      ),
    );
  }
}

class _SearchResults extends StatelessWidget {
  final LocationSearchController controller;
  final MapEngineController mapEngine;
  final RideLifecycleController rideLifecycle;

  const _SearchResults({
    required this.controller,
    required this.mapEngine,
    required this.rideLifecycle,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LocationSearchController>(
      id: 'places_list',
      builder: (locCtrl) {
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          height: locCtrl.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: locCtrl.placesDestination.length,
            separatorBuilder: (context, index) =>
                const Divider(height: 1, color: Colors.grey),
            itemBuilder: (BuildContext context, int index) {
              final res = locCtrl.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,
                  mapEngine,
                  rideLifecycle,
                  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(
      LocationSearchController controller,
      MapEngineController mapEngine,
      RideLifecycleController rideLifecycle,
      dynamic latitude,
      dynamic longitude,
      String title,
      int index) async {
    if (latitude == null || longitude == null) {
      Toast.show(Get.context!, 'Invalid location data', AppColor.redColor);
      return;
    }

    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 (rideLifecycle.isAnotherOreder) {
      await _handleAnotherOrderSelection(
          controller, mapEngine, rideLifecycle, destLatLng);
    } else {
      _handleRegularOrderSelection(
          controller, mapEngine, rideLifecycle, destLatLng, index);
    }
  }

  Future<void> _handleAnotherOrderSelection(
      LocationSearchController controller,
      MapEngineController mapEngine,
      RideLifecycleController rideLifecycle,
      LatLng destination) async {
    controller.myDestination = destination;
    controller.clearPlacesDestination();

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

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

  void _handleRegularOrderSelection(
      LocationSearchController controller,
      MapEngineController mapEngine,
      RideLifecycleController rideLifecycle,
      LatLng destination,
      int index) {
    controller.passengerLocation = controller.newMyLocation;
    controller.myDestination = destination;
    controller.convertHintTextDestinationNewPlaces(index);

    controller.clearPlacesDestination();

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

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

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.cyanBlue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: AppColor.cyanBlue.withOpacity(0.3)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: AppColor.cyanBlue),
          const SizedBox(height: 4.0),
          Text(
            text,
            textAlign: TextAlign.center,
            style: AppStyle.title.copyWith(
                color: AppColor.cyanBlue, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    ),
  );
}

void _showChangeLocationDialog(LocationSearchController controller,
    MapEngineController mapEngine, String locationType) {
  MyDialog().getDialog(
    locationType == 'Work'
        ? 'Change Work location ?'.tr
        : 'Change Home location ?'.tr,
    '',
    () {
      if (locationType == 'Work') {
        controller.workLocationFromMap = true;
      } else {
        controller.homeLocationFromMap = true;
      }
      mapEngine.changeMainBottomMenuMap();
      mapEngine.changePickerShown();
    },
  );
}

void _handleQuickAction(
    LocationSearchController controller,
    MapEngineController mapEngine,
    RideLifecycleController rideLifecycle,
    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;
    mapEngine.changeMainBottomMenuMap();

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

    controller.currentLocationToFormPlaces = false;
    controller.clearPlacesDestination();
    controller.passengerStartLocationFromMap = false;
    mapEngine.isPickerShown = false;
    rideLifecycle.showBottomSheet1();
  } catch (e) {
    Log.print("Error handling quick action: $e");
    Toast.show(Get.context!, "Failed to get location".tr, AppColor.redColor);
  }
}
