import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sk_base_mobile/db_helper/dbHelper.dart';
import 'package:sk_base_mobile/models/base_response.dart';
import 'package:sk_base_mobile/models/product.model.dart';
import 'package:sk_base_mobile/models/project.model.dart';
import 'package:sk_base_mobile/models/task_model.dart';
import 'package:sk_base_mobile/screens/inventory_inout/inventory_inout_controller.dart';
import 'package:sk_base_mobile/apis/api.dart' as Api;
import 'package:sk_base_mobile/util/date.util.dart';
import 'package:sk_base_mobile/util/snack_bar.util.dart';

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

  DateTime? pickedDate;
  final DbHelper db = DbHelper();
  RxInt selectedImage = 0.obs;
  RxBool lowPeriority = false.obs;
  RxBool labelFocus = false.obs;
  RxBool categoryFocus = false.obs;
  RxBool descriptionFocus = false.obs;
  RxString selectedDate = ''.obs;
  RxString startTime = ''.obs;
  RxString endTime = ''.obs;
  RxBool loading = false.obs;
  final inventoryInoutController = Get.put(InventoryInoutController());
  final label = TextEditingController().obs;
  final description = TextEditingController().obs;
  final category = TextEditingController().obs;
  RxList<ProjectModel> projects = <ProjectModel>[].obs;
  RxList<ProductModel> products = <ProductModel>[].obs;
  final projectTextController = TextEditingController();
  final productTextController = TextEditingController();
  final dateTextController = TextEditingController();
  final quantityTextController = TextEditingController();
  final agentTextController = TextEditingController();
  final remarkTextController = TextEditingController();
  Map<String, dynamic> payload = {};

  Future<List<ProjectModel>> getProjects({String? keyword}) async {
    final res =
        await Api.getProjects({'page': 1, 'pageSize': 10, 'name': keyword});
    if (res.data != null) {
      projects.assignAll(
          res.data!.items.map((e) => ProjectModel.fromJson(e)).toList());
    }
    return projects;
  }

  Future<List<ProductModel>> getProducts({String? keyword}) async {
    final res =
        await Api.getProducts({'page': 1, 'pageSize': 10, 'name': keyword});
    if (res.data != null) {
      products.assignAll(
          res.data!.items.map((e) => ProductModel.fromJson(e)).toList());
    }
    return products;
  }

  picStartTime(BuildContext context) async {
    var picker =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (picker != null) {
      startTime.value =
          '${DateUtil.addPrefix(picker.hourOfPeriod.toString())}:${DateUtil.addPrefix(picker.minute.toString())}:${picker.period.name.toUpperCase()}';
    }
  }

  picEndTime(BuildContext context) async {
    var picker =
        await showTimePicker(context: context, initialTime: TimeOfDay.now());
    if (picker != null) {
      endTime.value =
          '${DateUtil.addPrefix(picker.hourOfPeriod.toString())}:${DateUtil.addPrefix(picker.minute.toString())}:${picker.period.name.toUpperCase()}';
    }
  }

  showDatePick() async {
    final picker = await showDatePicker(
        context: Get.context!,
        initialDate: DateTime.now(),
        firstDate: DateTime(2000, 1, 1),
        lastDate: DateTime.now().add(const Duration(days: 7)));
    if (picker != null) {
      pickedDate = picker;
      selectedDate.value =
          '${DateUtil.addPrefix(picker.day.toString())}/${DateUtil.addPrefix(picker.month.toString())}/${picker.year}';
    }
  }

  changeImage(int index) {
    selectedImage.value = index;
  }

  setLabelFocus() {
    labelFocus.value = true;
    categoryFocus.value = false;
    descriptionFocus.value = false;
  }

  setCategoryFocus() {
    labelFocus.value = false;
    categoryFocus.value = true;
    descriptionFocus.value = false;
  }

  setDescriptionFocus() {
    labelFocus.value = false;
    categoryFocus.value = false;
    descriptionFocus.value = true;
  }

  onTapOutside() {
    labelFocus.value = false;
    categoryFocus.value = false;
    descriptionFocus.value = false;
  }

  insertTask(BuildContext context) {
    if (label.value.text.toString().isEmpty) {
      SnackBarUtil().warning(
        'Warning',
        message: 'Enter valid label',
      );
      return;
    }
    if (category.value.text.toString().isEmpty) {
      SnackBarUtil().warning(
        'Warning',
        message: 'Enter Correct Category',
      );
      return;
    }
    if (selectedDate.isEmpty) {
      // selectedDate.value =
      //     '${Utils.addPrefix(DateTime.now().day.toString())}/${Utils.addPrefix(DateTime.now().month.toString())}/${Utils.addPrefix(DateTime.now().year.toString())}';
      showDatePick();
    }
    if (startTime.isEmpty) {
      picStartTime(context);
      return;
    }
    if (endTime.isEmpty) {
      picEndTime(context);
      return;
    }
    loading.value = true;

    db
        .insert(TaskModel(
            key: DateTime.now().microsecondsSinceEpoch.toString(),
            startTime: startTime.value,
            endTime: endTime.value,
            date: selectedDate.value,
            periority: lowPeriority.value ? 'Low' : 'High',
            description: description.value.text.toString(),
            category: category.value.text.toString(),
            title: label.value.text.toString(),
            image: selectedImage.value.toString(),
            show: 'yes',
            status: 'unComplete'))
        .then((value) {
      Duration dif = pickedDate!.difference(DateTime(
          DateTime.now().year, DateTime.now().month, DateTime.now().day));
      inventoryInoutController.list[dif.inDays].add(value);
      Timer(const Duration(seconds: 1), () {
        loading.value = false;
        Get.back();
        SnackBarUtil().success(
          'Successful',
          message: 'Task is created',
        );
      });
    });
  }
}
