import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:generp/Models/TechniciansPendingComplaintsResponse.dart';
import 'package:generp/Notifiers/HomeScreenNotifier.dart';
import 'package:generp/Utils/SharedpreferencesService.dart';
import 'package:generp/screens/serviceEngineer/serviceEngineerDashboard.dart';
import 'package:generp/services/api_calling.dart';
import 'package:get/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

import '../Utils/commonServices.dart';
import '../screens/splash.dart';

class Pendingcomplaintsprovider extends ChangeNotifier {
  TextEditingController fsrNumberController = TextEditingController();
  TextEditingController runningHoursController = TextEditingController();
  TextEditingController feedbackController = TextEditingController();
  List<TP_List> _technician_complaint_list = [];
  bool _isLoading = false;
  String? _statusId;
  String? _selectedValue;
  TimeOfDay _selectedTime = TimeOfDay.now();
  String _formattedTime = "";
  final ImagePicker _picker = ImagePicker();
  File? _image;
  File? _imageName;
  var _image_picked = 0;
  bool _submitLoading = false;
  String? statusError;
  String? fsrError;
  String? _runningHoursError;
  List<TP_List> get technician_complaint_list => _technician_complaint_list;
  bool get isLoading => _isLoading;
  bool get submitLoading => _submitLoading;
  String? get statusID => _statusId;
  String? get selectedValue => _selectedValue;
  TimeOfDay get selectedTime => _selectedTime;
  String get formattedTime => _formattedTime;
  int get imagePicked => _image_picked;
  File? get imagePath => _imageName;
  File? get imageFilePath => _image;
  String? get runningHoursError => _runningHoursError;
  final List<Map<String, dynamic>> CompletedStatus = [
    {"id": "1", "name": "Pending"},
    {"id": "2", "name": "Completed"},
  ];
  set runningHoursError(String? values) {
    _runningHoursError = values;
    notifyListeners();
  }

  set imagePicked(int value) {
    _image_picked = value;
    notifyListeners();
  }

  set imagePath(File? value) {
    _imageName = value;
    notifyListeners();
  }

  set imageFilePath(File? value) {
    _image = value;
    notifyListeners();
  }

  set statusID(String? value) {
    _statusId = value;
    notifyListeners();
  }

  set submitLoading(bool value) {
    _submitLoading = value;
    notifyListeners();
  }

  void resetAll() {
    _submitLoading = false;
    _statusId = "";
    _image_picked = 0;
    fsrNumberController.clear();
    runningHoursController.clear();
    feedbackController.clear();
    statusError = "";
    fsrError = "";
    _runningHoursError = "";
    _image = null;
    _imageName = null;
    _selectedTime = TimeOfDay.now();
    checkDropDownSelected();
    notifyListeners();
  }

  void checkDropDownSelected() {
    if (_statusId != null && !CompletedStatus.contains(_statusId)) {
      _statusId = null;
    }
    notifyListeners();
  }

  Future<void> TechnicianPendingComplaints(BuildContext context) async {
    var HomeProvider = Provider.of<HomescreenNotifier>(context, listen: false);
    try {
      final data = await ApiCalling.LoadTechnicianComplaintsAPI(
        HomeProvider.empId,
        HomeProvider.session,
      );
      //await UserApi.LoadTechnicianComplaintsAPI("752","bb1bd615748920990e679a575b0684cf3f53367620dd775a47e4a771bde22f313f4d7722ce131d65427ce054053aed8eb0ca").then((data) => {
      if (data != null) {
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            _technician_complaint_list = data.list!;
            _isLoading = false;
            notifyListeners();
          } else {
            _isLoading = false;
          }
        } else {
          // SharedpreferencesService().clearPreferences();
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      }
    } on Error catch (e) {
      debugPrint(e.toString());
    }
  }

  Future TimePicker(context) async {
    return await showDialog(
          context: context,
          builder:
              (BuildContext context) => AlertDialog(
                content: TimePickerDialog(
                  initialTime: TimeOfDay.now(),
                  initialEntryMode: TimePickerEntryMode.input,
                ),
              ),
        ) ??
        false;
  }

  Future<void> selectTime(BuildContext context) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: _selectedTime,
    );
    if (picked != null && picked != _selectedTime) _selectedTime = picked;
    _formattedTime = "${_selectedTime.hour}:${_selectedTime.minute}";
    notifyListeners();
  }

  String formatTime(int hour, int minute) {
    String period = (hour >= 12) ? 'pm' : 'am';
    if (hour == 0) {
      hour = 12;
    } else if (hour > 12) {
      hour -= 12;
    }

    String formattedHour = (hour < 10) ? '0$hour' : '$hour';
    String formattedMinute = (minute < 10) ? '0$minute' : '$minute';

    print("formattedTime: $formattedHour:$formattedMinute $period");
    return '$formattedHour:$formattedMinute $period';
  }

  Future<void> UpdateComplaintAPIFunction(
    BuildContext context,
    complaintId,
    feedback,
    fsrNumber,
    runningHr,
    statusId,
  ) async {
    var HomeProvider = Provider.of<HomescreenNotifier>(context, listen: false);
    try {
      if (!validatereceiptForm(context)) {
        return;
      }
      final data = await ApiCalling.UpdateComplaintAPI(
        HomeProvider.empId,
        HomeProvider.session,
        complaintId,
        "${_selectedTime.hour}:${_selectedTime.minute}",
        feedback,
        fsrNumber,
        runningHr,
        statusId,
        _image,
      );
      if (data != null) {
        _submitLoading = false;
        notifyListeners();
        if (data.sessionExists == 1) {
          if (data.error == 0) {
            toast(context, "Complaint Status Updated!");
            resetAll();
            Navigator.pop(context);
          } else if (data.error == 1) {
            toast(context, "Something Went Wrong, please try again later!");
          } else if (data.error == 2) {
            toast(context, "Tag Generator before updating visit !");
          } else if (data.error == 3) {
            toast(context, "Tag Location before updating visit !");
          } else {
            toast(context, "Something Went Wrong, please try again later!");
          }
        } else {
          // SharedpreferencesService().clearPreferences();
          // Navigator.push(
          //   context,
          //   MaterialPageRoute(builder: (context) => Splash()),
          // );
        }
      } else {
        _submitLoading = false;
        notifyListeners();
      }
    } on Error catch (e) {
      _submitLoading = false;
      notifyListeners();
      print(e.toString());
    }
  }

  bool validatereceiptForm(BuildContext context) {
    statusError = null;
    fsrError = null;
    _runningHoursError = null;
    _submitLoading = false;
    bool isValid = true;
    if (_statusId == null || _statusId!.isEmpty) {
      statusError = "Please Select Status";
      _submitLoading = false;
      isValid = false;
    }
    if (_statusId != "Pending") {
      if (fsrNumberController.text.trim().isEmpty) {
        fsrError = "Please Enter FSR number";
        _submitLoading = false;
        isValid = false;
      }
    }

    if (runningHoursController.text.trim().isEmpty) {
      _runningHoursError = "Enter Running Hours";
      _submitLoading = false;
      isValid = false;
    }

    notifyListeners();
    return isValid;
  }

  Future SelectAttachmentDialogue(BuildContext context) async {
    return await showDialog(
          context: context,
          builder:
              (context) => AlertDialog(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5.0),
                ),
                elevation: 20,
                shadowColor: Colors.black,
                title: Align(
                  alignment: Alignment.center,
                  child: Text(
                    "Select Source",
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.w500,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
                content: SizedBox(
                  height: 85,
                  child: Column(
                    children: [
                      InkWell(
                        onTap: () {
                          Navigator.of(context).pop(false);
                          imgFromGallery();
                        },
                        child: SizedBox(
                          height: 35,
                          child: Text("Select photo from gallery"),
                        ),
                      ),
                      SizedBox(height: 10),
                      InkWell(
                        onTap: () {
                          Navigator.of(context).pop(false);
                          imgFromCamera();
                        },
                        child: SizedBox(
                          height: 35,
                          child: Text("Capture photo from camera"),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          barrierDismissible: true,
        ) ??
        false;
  }

  imgFromCamera() async {
    // Capture a photo
    try {
      final XFile? galleryImage = await _picker.pickImage(
        source: ImageSource.camera,
        imageQuality: 50,
      );
      print("added");
      _image = File(galleryImage!.path);
      _imageName = File(galleryImage.name);
      _image_picked = 1;

      notifyListeners();
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }

  imgFromGallery() async {
    // Pick an image
    try {
      final XFile? galleryImage = await _picker.pickImage(
        source: ImageSource.gallery,
      );
      final bytes = (await galleryImage?.readAsBytes())?.lengthInBytes;
      final kb = bytes! / 1024;
      final mb = kb / 1024;

      debugPrint("Jenny: bytes:$bytes, kb:$kb, mb: $mb");

      _image = File(galleryImage!.path);
      _imageName = File(galleryImage.name);
      _image_picked = 1;
      notifyListeners();
    } catch (e) {
      debugPrint("mmmm: ${e.toString()}");
    }
  }
}
