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';

GetBuilder<MapPassengerController> formSearchPlacesDestenation() {
  if (box.read(BoxName.addWork).toString() == '' ||
      box.read(BoxName.addHome).toString() == '') {
    box.write(BoxName.addWork, 'addWork');
    box.write(BoxName.addHome, 'addHome');
  }

  return GetBuilder<MapPassengerController>(
    builder: (controller) => Column(
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          child: Row(
            children: [
              Expanded(
                child: TextFormField(
                  controller: controller.placeDestinationController,
                  onChanged: (value) {
                    if (controller.placeDestinationController.text.length > 2) {
                      controller.getPlaces();
                      controller.changeHeightPlaces();
                    } else if (controller
                        .placeDestinationController.text.isEmpty) {
                      controller.clearPlacesDestination();
                      controller.changeHeightPlaces();
                    }
                  },
                  decoration: InputDecoration(
                    hintText: controller.hintTextDestinationPoint,
                    hintStyle:
                        AppStyle.subtitle.copyWith(color: Colors.grey[600]),
                    prefixIcon:
                        const Icon(Icons.search, color: AppColor.primaryColor),
                    suffixIcon: controller
                            .placeDestinationController.text.isNotEmpty
                        ? IconButton(
                            icon: Icon(Icons.clear, color: Colors.grey[400]),
                            onPressed: () {
                              controller.placeDestinationController.clear();
                              controller.clearPlacesDestination();
                              controller.changeHeightPlaces();
                            },
                          )
                        : 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: () {
                  controller.changeMainBottomMenuMap();
                  controller.changePickerShown();
                },
                icon: Icon(Icons.location_on_outlined,
                    color: AppColor.accentColor, size: 30),
                tooltip: controller.isAnotherOreder
                    ? 'Pick destination on map'
                    : 'Pick on map',
              ),
            ],
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildQuickActionButton(
                icon: Icons.work_outline,
                text: box.read(BoxName.addWork) == 'addWork'
                    ? 'Add Work'.tr
                    : 'To Work'.tr,
                onTap: () async {
                  if (box.read(BoxName.addWork) == '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: box.read(BoxName.addHome) == 'addHome'
                    ? 'Add Home'.tr
                    : 'To Home'.tr,
                onTap: () async {
                  if (box.read(BoxName.addHome) == 'addHome') {
                    controller.homeLocationFromMap = true;
                    controller.changeMainBottomMenuMap();
                    controller.changePickerShown();
                  } else {
                    _handleQuickAction(controller, BoxName.addHome, 'To Home');
                  }
                },
                onLongPress: () =>
                    _showChangeLocationDialog(controller, 'Home'),
              ),
            ],
          ),
        ),
        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 NeverScrollableScrollPhysics(),
            itemCount: controller.placesDestination.length,
            separatorBuilder: (context, index) =>
                const Divider(height: 1, color: Colors.grey),
            itemBuilder: (BuildContext context, int index) {
              var res = controller.placesDestination[index];

              // استخراج البيانات حسب بنية السيرفر الجديد
              var title = res['name'] ?? 'Unknown Place';
              var address = res['address'] ?? 'Unknown Address';
              var latitude = res['latitude'];
              var longitude = res['longitude'];
              var primaryCategory =
                  'Place'; // يمكن تطويره لاحقاً لو أضفت نوع للمكان

              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: () 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,
                      );
                    }
                  },
                ),
                onTap: () async {
                  if (latitude != null && longitude != null) {
                    await sql.insertMapLocation({
                      'latitude': latitude,
                      'longitude': longitude,
                      'name': title,
                      'rate': 'N/A',
                      'createdAt': DateTime.now().toIso8601String(),
                    }, TableName.recentLocations);

                    controller.passengerLocation = controller.newMyLocation;
                    controller.myDestination = LatLng(latitude, longitude);
                    controller.convertHintTextDestinationNewPlaces(index);

                    controller.placesDestination = [];
                    controller.placeDestinationController.clear();
                    controller.changeMainBottomMenuMap();
                    controller.passengerStartLocationFromMap = true;
                    controller.isPickerShown = true;
                  } else {
                    Toast.show(
                      context,
                      'Invalid location data',
                      AppColor.redColor,
                    );
                  }
                },
              );
            },
          ),
        ),
      ],
    ),
  );
}

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 {
  final latLng = LatLng(
    double.parse(box.read(boxName).toString().split(',')[0]),
    double.parse(box.read(boxName).toString().split(',')[1]),
  );
  controller.hintTextDestinationPoint = hintText;
  controller.changeMainBottomMenuMap();

  await controller.getDirectionMap(
    '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
    '${latLng.latitude},${latLng.longitude}',
  );
  controller.currentLocationToFormPlaces = false;
  controller.placesDestination = [];
  controller.clearPlacesStart();
  controller.clearPlacesDestination();
  controller.passengerStartLocationFromMap = false;
  controller.isPickerShown = false;
  controller.showBottomSheet1();
}
