import 'package:didvan/models/enums.dart';
import 'package:didvan/providers/core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import '../../models/day_time.dart';
import '../../models/view/alert_data.dart';
import '../../services/network/request.dart';
import '../../services/network/request_helper.dart';
import '../../utils/action_sheet.dart';
import '../../utils/date_time.dart';

class NotificationTimeState extends CoreProvier {
  late DayTime selectedTime;
  bool isAnytime = false;
  bool fromFav = false;

  late void Function() onTimeChanged = () {};

  Future<void> getTime() async {
    appState = AppState.busy;

    final service = RequestService(
      RequestHelper.notificationTime(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      var time = service.data('time');
      if (time.toString().isEmpty) {
        time = "12:00";
        isAnytime = true;
      }
      selectedTime = DateTimeUtils.handleDayTime(time);

      appState = AppState.idle;
    } else {
      appState = AppState.failed;
    }

    update();
  }

  Future<void> putTime(BuildContext context) async {
    appState = AppState.busy;

    final favoritesRequest = {
      "time": isAnytime ? "" : DateTimeUtils.handleDayTimeReverse(selectedTime)
    };
    final service = RequestService(
      RequestHelper.notificationTime(),
      body: favoritesRequest,
    );
    await service.put();
    if (service.isSuccess) {
      onTimeChanged();
      Future.delayed(
        Duration.zero,
        () {
          if (fromFav) {
            Navigator.of(context).pop();
            Navigator.of(context).pop();
          } else {
            Navigator.of(context).pop();
          }
        },
      );
      Future.delayed(
        Duration.zero,
        () => ActionSheetUtils(context).showAlert(AlertData(
            message: "تغییرات شما با موفقیت اعمال شد.",
            aLertType: ALertType.success)),
      );

      appState = AppState.idle;
      return;
    }

    appState = AppState.failed;
  }
}
