import 'dart:convert';
import 'dart:math';

import 'package:SEFER/controller/auth/captin/login_captin_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/controller/functions/ocr_controller.dart';
import 'package:SEFER/main.dart';
import 'package:SEFER/views/auth/captin/login_captin.dart';
import 'package:SEFER/views/auth/captin/verify_email_captain.dart';

import '../../../views/auth/captin/ai_page.dart';
import '../../../views/auth/captin/car_license_page.dart';
import '../../../views/home/Captin/home_captain/home_captin.dart';

class RegisterCaptainController extends GetxController {
  final formKey = GlobalKey<FormState>();

  TextEditingController emailController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController verifyCode = TextEditingController();

  String birthDate = 'Birth Date'.tr;
  String gender = 'Male'.tr;
  bool isLoading = false;
  late String name;
  late String licenseClass;
  late String documentNo;
  late String address;
  late String height;
  late String postalCode;
  late String sex;
  late String stateCode;
  late String expireDate;
  late String dob;

  getBirthDate() {
    Get.defaultDialog(
      title: 'Select Date'.tr,
      content: SizedBox(
        width: 300,
        child: CalendarDatePicker(
          initialDate: DateTime.now().subtract(const Duration(days: 18 * 365)),
          firstDate: DateTime.parse('1940-06-01'),
          lastDate: DateTime.now().subtract(const Duration(days: 18 * 365)),
          onDateChanged: (date) {
            // Get the selected date and convert it to a DateTime object
            DateTime dateTime = date;
            // Call the getOrders() function from the controller
            birthDate = dateTime.toString().split(' ')[0];
            update();
            Get.back();
          },

          // onDateChanged: (DateTime value) {},
        ),
      ),
    );
  }

  void changeGender(String value) {
    gender = value;
    update();
  }

  sendVerifications() async {
    var res = await CRUD().post(link: AppLink.verifyEmail, payload: {
      'email': emailController.text.isEmpty
          ? Get.find<LoginCaptinController>().emailController.text.toString()
          : emailController.text,
      'token': verifyCode.text,
    });

    if (res != 'failure') {
      if (Get.find<LoginCaptinController>().emailController.text.toString() !=
          '') {
        Get.offAll(() => HomeCaptain());
      } else {
        Get.to(() => CarLicensePage());
      }
    }
  }

  void nextToAIDetection() async {
    //Todo dont forget this
    if (formKey.currentState!.validate()) {
      isLoading = true;
      update();
      Get.to(() => AiPage());
    }
  }

  Map<String, dynamic> payloadLisence = {};

  void getFromController() {
    name = Get.find<ScanDocumentsByApi>().name;
    licenseClass = Get.find<ScanDocumentsByApi>().licenseClass.toString();
    documentNo = Get.find<ScanDocumentsByApi>().documentNo.toString();
    address = Get.find<ScanDocumentsByApi>().address.toString();
    height = Get.find<ScanDocumentsByApi>().height.toString();
    postalCode = Get.find<ScanDocumentsByApi>().address.toString();
    sex = Get.find<ScanDocumentsByApi>().sex.toString();
    stateCode = Get.find<ScanDocumentsByApi>().postalCode.toString();
    expireDate = Get.find<ScanDocumentsByApi>().expireDate.toString();
    dob = Get.find<ScanDocumentsByApi>().dob.toString();
    update();
  }

  Future addLisence() async {
    getFromController();
    var res = await CRUD().post(link: AppLink.addLicense, payload: {
      'name': name,
      'licenseClass': licenseClass,
      'documentNo': documentNo,
      'address': address,
      'height': height,
      'postalCode': postalCode,
      'sex': sex,
      'stateCode': stateCode,
      'expireDate': expireDate,
      'dateOfBirth': dob,
    });
    print(jsonDecode(res));
    isLoading = false;
    update();
    if (jsonDecode(res)['status'] == 'success') {
      // Get.to(() => AiPage()); //todo rplace this
    }
  }

  void addRegisrationCarForDriver(String vin, make, model, year, color, owner,
      expirationDate, registrationDate) async {
    getFromController();
    var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
      'vin': vin,
      'make': make,
      'model': model,
      'year': year,
      'expirationDate': expirationDate,
      'color': color,
      'owner': owner,
      'registrationDate': registrationDate,
    });
    print(jsonDecode(res));
    box.write(BoxName.vin, vin);
    box.write(BoxName.make, make);
    box.write(BoxName.model, model);
    box.write(BoxName.year, year);
    box.write(BoxName.expirationDate, expirationDate);
    box.write(BoxName.color, color);
    box.write(BoxName.owner, owner);
    box.write(BoxName.registrationDate, registrationDate);
    isLoading = false;
    update();
    if (jsonDecode(res)['status'] == 'success') {
      Get.offAll(() => LoginCaptin()); //todo replace this
    }
  }

  Future register() async {
    getFromController();
    if (formKey.currentState!.validate()) {
      isLoading = true;
      update();
      var res = await CRUD().post(link: AppLink.signUpCaptin, payload: {
        'first_name': name.split(' ')[1],
        'last_name': name.split(' ')[0],
        'email': emailController.text,
        'phone': phoneController.text,
        'password': passwordController.text,
        'gender': sex,
        'site': address,
        'birthdate': dob,
      });

      isLoading = false;
      update();
      if (jsonDecode(res)['status'] == 'success') {
        box.write(BoxName.driverID, jsonDecode(res)['message']);
        box.write(BoxName.dobDriver, dob);
        box.write(BoxName.sexDriver, sex);
        box.write(BoxName.phoneDriver, phoneController.text);
        box.write(BoxName.lastNameDriver, name.split(' ')[0]);
        int randomNumber = Random().nextInt(100000) + 1;
        await CRUD().post(link: AppLink.sendVerifyEmail, payload: {
          'email': emailController.text,
          'token': randomNumber.toString(),
        }).then((value) => print(value));
        Get.to(() => VerifyEmailCaptainPage());
      }
    }
  }
}
