import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:service/constant/colors.dart';
import 'package:service/constant/links.dart';
import 'package:service/controller/functions/crud.dart';
import 'package:service/controller/mainController/pages/driver_page.dart';
import 'package:service/views/widgets/my_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../print.dart';
import 'pages/passengers_page.dart';

class MainController extends GetxController {
  final formKey = GlobalKey<FormState>();
  bool isLoading = false;
  final passengerPhoneController = TextEditingController();
  final driverPhoneController = TextEditingController();
  final notesController = TextEditingController();
  final carplateController = TextEditingController();
  TextEditingController colorController = TextEditingController();
  TextEditingController makeController = TextEditingController();
  TextEditingController modelController = TextEditingController();
  TextEditingController expirationDateController = TextEditingController();
  TextEditingController yearController = TextEditingController();
  TextEditingController ownerController = TextEditingController();
  Map passengerData = {};
  Map driverData = {};
  List filteredDrivers = [];
  var color = ''.obs;
  var colorHex = ''.obs;

  searchPassengerByPhone() async {
    if (formKey.currentState!.validate()) {
      await getPassengersByPhone();
      Get.back();
      Get.to(() => PassengersPage());
    }
  }

  void searchDrivers(String query) {
    if (query.isEmpty) {
      filteredDrivers = driverNotCompleteRegistration;
      update();
    } else {
      filteredDrivers = driverNotCompleteRegistration
          .where((driver) => driver['phone_number']
              .toString()
              .toLowerCase()
              .contains(query.toLowerCase()))
          .toList();
      update();
    }
  }

  Future<void> makePhoneCall(String phoneNumber) async {
    final Uri launchUri = Uri(
      scheme: 'tel',
      path: phoneNumber,
    );
    await launchUrl(launchUri);
  }

  void launchCommunication(
      String method, String contactInfo, String message) async {
    String url;

    if (Platform.isIOS) {
      switch (method) {
        case 'phone':
          url = 'tel:$contactInfo';
          break;
        case 'sms':
          url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
          break;
        case 'whatsapp':
          url =
              'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
          break;
        case 'email':
          url =
              'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
          break;
        default:
          return;
      }
    } else if (Platform.isAndroid) {
      switch (method) {
        case 'phone':
          url = 'tel:$contactInfo';
          break;
        case 'sms':
          url = 'sms:$contactInfo?body=${Uri.encodeComponent(message)}';
          break;
        case 'whatsapp':
          // Check if WhatsApp is installed
          final bool whatsappInstalled =
              await canLaunchUrl(Uri.parse('whatsapp://'));
          if (whatsappInstalled) {
            url =
                'whatsapp://send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
          } else {
            // Provide an alternative action, such as opening the WhatsApp Web API
            url =
                'https://api.whatsapp.com/send?phone=$contactInfo&text=${Uri.encodeComponent(message)}';
          }
          break;
        case 'email':
          url =
              'mailto:$contactInfo?subject=Subject&body=${Uri.encodeComponent(message)}';
          break;
        default:
          return;
      }
    } else {
      return;
    }

    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    } else {}
  }

  List driverNotCompleteRegistration = [];
  getDriverNotCompleteRegistration() async {
    var res = await CRUD()
        .get(link: AppLink.getDriverNotCompleteRegistration, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      driverNotCompleteRegistration = d;
      filteredDrivers = driverNotCompleteRegistration;
      update();
    } else {
      Get.snackbar(res, '');
    }
  }

  List newDriverRegister = [];
  getNewDriverRegister() async {
    var res = await CRUD().get(link: AppLink.getNewDriverRegister, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      newDriverRegister = d;
      update();
    } else {
      Get.snackbar(res, '');
    }
  }

  addWelcomeCall(String driveId) async {
    var res = await CRUD().post(link: AppLink.addWelcomeDriverNote, payload: {
      "driverId": driveId,
      "notes": notesController.text,
    });
    if (res != 'failue') {
      Get.snackbar('Success'.tr, '', backgroundColor: AppColor.greenColor);
    }
  }

  String selectedStatus = "I'm not ready yet".tr;
  List passengerNotCompleteRegistration = [];
  getPassengerNotCompleteRegistration() async {
    var res = await CRUD()
        .get(link: AppLink.getPassengersNotCompleteRegistration, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      passengerNotCompleteRegistration = d;
      update();
    } else {
      Get.snackbar(res, '');
    }
  }

  void setSelectedStatus(String status) {
    selectedStatus = status;
    update();
  }

  final List<String> statusOptions = [
    "I'm not ready yet".tr,
    "I don't have a suitable vehicle".tr,
    "I'll register when the app is fully launched".tr,
    "I need more help understanding the app".tr,
    "My documents have expired".tr,
  ];

  List carPlateNotEdit = [];

  getCarPlateNotEdit() async {
    var res = await CRUD().get(link: AppLink.getCarPlateNotEdit, payload: {});
    if (res != 'failure') {
      var d = jsonDecode(res)['message'];
      carPlateNotEdit = d;
      update();
    } else {
      MyDialog().getDialog('No Car found yet'.tr, 'thanks'.tr, const SizedBox(),
          () {
        Get.back();
      });
    }
  }

  editCarPlateNotEdit(
    String driverId,
    String carPlate,
    String color,
    String colorHex,
    String year,
    String make,
    String model,
    String expirationDate,
    String owner,
  ) async {
    var res = await CRUD().post(link: AppLink.editCarPlate, payload: {
      "driverId": driverId,
      "carPlate": carPlate,
      "color": color,
      "color_hex": colorHex,
      "make": make,
      "year": year,
      "model": model,
      "expiration_date": expirationDate.toString(),
      "owner": owner,
    });
    Log.print('res: ${res}');
    if (res != 'failure') {
      Get.snackbar(res, '', backgroundColor: AppColor.greenColor);
      carplateController.clear();
      yearController.clear();
      makeController.clear();
      modelController.clear();
      ownerController.clear();
      Get.back();
      await getCarPlateNotEdit();
      update();
    } else {
      Get.snackbar(res, '', backgroundColor: AppColor.redColor);
    }
  }

  // editCarPlateNotEdit(String driverId, carPlate) async {
  //   var res = await CRUD().post(link: AppLink.editCarPlate, payload: {
  //     "driverId": driverId,
  //     "carPlate": carPlate,
  //   });
  //   if (res != 'failure') {
  //     Get.snackbar(res, '', backgroundColor: AppColor.greenColor);
  //     carplateController.clear();
  //     await getCarPlateNotEdit();
  //     update();
  //   } else {
  //     Get.snackbar(res, '', backgroundColor: AppColor.redColor);
  //   }
  // }

  saveNoteForDriverNotCompleteRegistration(String phone, editor, note) async {
    var res = await CRUD().post(
        link: AppLink.addNotesDriver,
        payload: {"phone": phone, "editor": editor, "note": note});
    if (res != 'failure') {
      Get.snackbar(res, '', backgroundColor: AppColor.greenColor);
      notesController.clear();
    } else {
      Get.snackbar(res, '', backgroundColor: AppColor.redColor);
    }
  }

  saveNoteForPassengerNotCompleteRegistration(
      String phone, editor, note) async {
    var res = await CRUD().post(
        link: AppLink.addNotesPassenger,
        payload: {"phone": phone, "editor": editor, "note": note});
    if (res != 'failure') {
      Get.snackbar(res, '', backgroundColor: AppColor.greenColor);
      notesController.clear();
    } else {
      Get.snackbar(res, '', backgroundColor: AppColor.redColor);
    }
  }

  searchDriverByPhone() async {
    if (formKey.currentState!.validate()) {
      await getDriverByPhone();
      Get.back();
      Get.to(() => DriverPage());
    }
  }

  getPassengersByPhone() async {
    var res = await CRUD().get(
        link: AppLink.getPassengersByPhone,
        payload: {"phone": '+2${passengerPhoneController.text}'});

    if (res != 'failure') {
      var d = jsonDecode(res);
      passengerData = d;
      update();
    }
  }

  getDriverByPhone() async {
    var res = await CRUD().get(
        link: AppLink.getDriverByPhone,
        payload: {"phone": '+2${driverPhoneController.text}'});

    if (res != 'failure') {
      var d = jsonDecode(res);
      driverData = d;
      update();
    }
  }
}
