import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gifunavi/model/destination.dart';
import 'package:gifunavi/pages/destination/destination_controller.dart';
import 'package:gifunavi/pages/index/index_controller.dart';
import 'package:gifunavi/utils/const.dart';
import 'package:gifunavi/utils/database_helper.dart';
//import 'package:gifunavi/widgets/bottom_sheets/bottom_sheet_start.dart';
//import 'package:gifunavi/widgets/bottom_sheets/bottom_sheet_goal.dart';
//import 'package:gifunavi/widgets/bottom_sheets/bottom_sheet_normal_point.dart';
import 'package:gifunavi/widgets/bottom_sheet_new.dart';
import 'package:timeline_tile/timeline_tile.dart';

class DestinationWidget extends StatelessWidget {
  DestinationWidget({super.key});

  final DestinationController destinationController =
      Get.find<DestinationController>();

  final IndexController indexController = Get.find<IndexController>();

  final List<int> _items = List<int>.generate(50, (int index) => index);

  Image getImage(int index) {
    if (destinationController.destinations[index].photos == null ||
        destinationController.destinations[index].photos == "") {
      return const Image(image: AssetImage('assets/images/empty_image.png'));
    } else {
      // print(
      //     "------- image is ${destinationController.destinations[index].photos!}------");
      String photo = destinationController.destinations[index].photos!;
      if (photo.contains('http')) {
        return Image(
          image:
              NetworkImage(destinationController.destinations[index].photos!),
          errorBuilder:
              (BuildContext context, Object exception, StackTrace? stackTrace) {
            return Image.asset("assets/images/empty_image.png");
          },
        );
      } else {
        String serverUrl = ConstValues.currentServer();
        //print("==== photo is ${server_url + '/media/compressed/' + destinationController.destinations[index].photos!} ===");
        return Image(
          image: NetworkImage(
              '$serverUrl/media/compressed/${destinationController.destinations[index].photos!}'),
          errorBuilder:
              (BuildContext context, Object exception, StackTrace? stackTrace) {
            return Image.asset("assets/images/empty_image.png");
          },
        );
      }
    }
  }

  // bool getSelection(int index){
  //   bool ret = false;
  //   destinationController.destination_index_data.forEach((element) {
  //     if(index == element["index"]){
  //       if(element["selected"] == true){
  //         ret = true;
  //         return;
  //       }
  //     }
  //   });
  //   return ret;
  // }

  void doDelete() {
    for (var element in destinationController.currentSelectedDestinations) {
      destinationController.deleteDestination(element);
      destinationController.resetRogaining();
    }
    // destinationController.destination_index_data.forEach((element) {
    //   //print(element["index"]);
    //   destinationController.deleteDestination(element["index"]);
    // });
    // destinationController.destination_index_data.clear();
  }

  void moveUp() {
    Destination? d;
    for (Destination ad in destinationController.destinations) {
      if (ad.selected == true) {
        d = ad;
        break;
      }
    }
    if (d != null) {
      //print("--- selected destination is ${d.list_order}");
      destinationController.makeOrder(d, -1);
    }
  }

  void moveDown() {
    Destination? d;
    for (Destination ad in destinationController.destinations) {
      if (ad.selected == true) {
        d = ad;
        break;
      }
    }
    if (d != null) {
      //print("--- selected destination is ${d.list_order}");
      destinationController.makeOrder(d, 1);
    }
  }

  void clearall() {
    Get.defaultDialog(
        title: "are_you_sure_want_to_delete_all".tr,
        middleText: "all_added_destination_will_be_deleted".tr,
        backgroundColor: Colors.blue.shade300,
        titleStyle: const TextStyle(color: Colors.white),
        middleTextStyle: const TextStyle(color: Colors.white),
        textConfirm: "confirm".tr,
        textCancel: "cancel".tr,
        cancelTextColor: Colors.white,
        confirmTextColor: Colors.blue,
        buttonColor: Colors.white,
        barrierDismissible: false,
        radius: 10,
        content: const Column(
          children: [],
        ),
        onConfirm: () {
          destinationController.deleteAllDestinations();
          Get.back();
          Get.snackbar(
              "deleted".tr, "all_destinations_are_deleted_successfully".tr,
              backgroundColor: Colors.green,
              colorText: Colors.white);
        });
  }

  void interChange() {
    // int first_index = -1;
    // destinationController.destination_index_data.forEach((element) {
    //   //print(element["index"]);
    //   int action_id = destinationController.destinations[element["index"]]["id"] as int;
    //   destinationController.makeOrder(action_id, (element["index"] as int) + 1, "up");

    // });
  }

  Future getIsLocationAvilable(int locationId) async {
    DatabaseHelper db = DatabaseHelper.instance;
    return await db.isAlreadyAvailable(locationId);
  }

  @override
  Widget build(BuildContext context) {
    print(
        "------ destination widget------ ${destinationController.destinationCount.value} ----------");

    return Obx(() => Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 45.0),
              child: ListView.builder(
                  itemCount: destinationController.destinationCount.value,
                  itemBuilder: (BuildContext context, int index) {
                    return TimelineTile(
                      alignment: TimelineAlign.manual,
                      lineXY: 0.2,
                      isFirst: index == 0 ? true : false,
                      indicatorStyle: IndicatorStyle(
                        indicator: CircleAvatar(
                          backgroundColor: Colors.red,
                          child: Text(
                            destinationController.destinations[index].list_order
                                .toString(),
                            style: const TextStyle(color: Colors.white),
                          ),
                        ),
                      ),
                      key: Key(index.toString()),
                      endChild: Card(
                        child: Container(
                          constraints: const BoxConstraints(
                            minHeight: 80,
                          ),
                          child: ListTile(
                            onTap: () async {
                              {
                                Destination? fs =
                                    destinationController.destinations[index];
                                //print("----fsf-----$index");
                                if (indexController
                                    .currentDestinationFeature.isNotEmpty) {
                                  indexController.currentDestinationFeature
                                      .clear();
                                }
                                indexController.currentDestinationFeature
                                    .add(fs);
                                // print(
                                //     "--- ndexController.currentDestinationFeature ----- ${indexController.currentDestinationFeature[0].name} ----");
                                //indexController.getAction();

                                Widget bottomSheet = BottomSheetNew(destination: fs);
                                    /*
                                if (fs.cp == -1 || fs.cp == 0) {
                                  bottomSheet = BottomSheetStart(destination: fs);
                                } else if (fs.cp == -2 || fs.cp == 0) {
                                  bottomSheet = BottomSheetGoal(destination: fs);
                                } else {
                                  bottomSheet = BottomSheetNormalPoint(destination: fs);
                                }
                                     */

                                showModalBottomSheet(
                                    constraints: BoxConstraints.loose(
                                        Size(Get.width, Get.height * 0.85)),
                                    context: context,
                                    isScrollControlled: true,
                                    //builder:((context) => BottomSheetWidget())
                                    builder: ((context) => bottomSheet)
                                );
                              }
                            },
                            onLongPress: () {
                              destinationController.toggleSelection(
                                  destinationController.destinations[index]);
                            },
                            selectedTileColor: Colors.amberAccent,
                            selected: destinationController
                                .destinations[index].selected!,
                            leading: getImage(index),
                            title: Text(destinationController
                                .destinations[index].name!),
                            subtitle: Text(destinationController
                                .destinations[index].category!),
                          ),
                        ),
                      ),
                      startChild: index > 0 &&
                              destinationController.matrix["routes"][0]
                                      ["legs"] !=
                                  null
                          ? Column(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                Text(destinationController.matrix["routes"][0]
                                            ["legs"][index - 1]["distance"] !=
                                        null
                                    ? destinationController.matrix["routes"][0]
                                            ["legs"][index - 1]["distance"]
                                            ["text"]
                                        .toString()
                                    : ''),
                                Text(destinationController.matrix["routes"][0]
                                            ["legs"][index - 1]["duration"] !=
                                        null
                                    ? destinationController.matrix["routes"][0]
                                            ["legs"][index - 1]["duration"]
                                            ["text"]
                                        .toString()
                                    : '')
                              ],
                            )
                          : Container(),
                    );
                  }),
            ),
            Container(
              decoration: BoxDecoration(
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.3),
                    spreadRadius: 5,
                    blurRadius: 3,
                    offset: const Offset(0, 7), // changes position of shadow
                  ),
                ],
              ),
              height: 44.0,
              width: MediaQuery.of(context).size.width,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  IconButton(
                    icon: const Icon(Icons.delete_forever),
                    //onPressed: (){doDelete();},
                    onPressed: clearall,
                  ),
                  IconButton(
                    icon: const Icon(Icons.cancel),
                    //onPressed: (){doDelete();},
                    onPressed: destinationController
                            .currentSelectedDestinations.isNotEmpty
                        ? doDelete
                        : null,
                  ),
                  IconButton(
                    icon: const Icon(Icons.move_up),
                    onPressed: destinationController
                            .currentSelectedDestinations.isNotEmpty
                        ? moveUp
                        : null,
                  ),
                  IconButton(
                    icon: const Icon(Icons.move_down),
                    onPressed: destinationController
                            .currentSelectedDestinations.isNotEmpty
                        ? moveDown
                        : null,
                  ),
                  // IconButton(
                  //   icon:Icon(Icons.sync),
                  //   onPressed: destinationController.destination_index_data.length == 2 ? interChange : null,
                  // ),
                ],
              ),
            )
          ],
        ));
  }
}
