import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:functions/src/core/data/models/entities/set_pedometer_request_entity.dart';
import 'package:functions/src/features/activity_meter/domain/entities/activity_entity.dart';
import 'package:functions/src/features/activity_meter/domain/get_device_steps_use_case.dart';
import 'package:functions/src/features/activity_meter/domain/set_pedometer_use_case.dart';
import 'package:functions/src/features/activity_meter/presentation/providers/get_device_steps_use_case_provider.dart';
import 'package:functions/src/features/activity_meter/presentation/providers/set_pedometer_use_case_provider.dart';
import 'package:functions/src/features/activity_meter/presentation/state/activity_meter_view_state.dart';
import 'package:legacy_shared/legacy_shared.dart';

final activityMeterViewModelProvider =
NotifierProvider.autoDispose<ActivityMeterViewModel, ActivityMeterViewState>(
  ActivityMeterViewModel.new,
);

class ActivityMeterViewModel extends Notifier<ActivityMeterViewState> {
  late final GetDeviceStepsUseCase _getDeviceStepsUseCase;
  late final SetPedometerUseCase _setPedometerUseCase;

  late final TextEditingController stepLengthController;
  late final TextEditingController weightController;

  @override
  ActivityMeterViewState build() {
    _getDeviceStepsUseCase = ref.read(getDeviceStepsUseCaseProvider);
    _setPedometerUseCase = ref.read(setPedometerUseCaseProvider);

    final selectedDevice = ref.watch(selectedDeviceProvider);

    _getDeviceStepsUseCase.getDeviceSteps(deviceId: selectedDevice!.identificator)
      .then(setActivity);

    stepLengthController = TextEditingController();
    stepLengthController.text = selectedDevice.carrierStepLength.toString();
    stepLengthController.addListener(_onStepLengthChanged);

    weightController = TextEditingController();
    weightController.text = selectedDevice.carrierWeight.toString();
    weightController.addListener(_onWeightChanged);

    return ActivityMeterViewState(
      selectedDevice: selectedDevice,
      selectedDate: DateTime.now(),
      enabled: selectedDevice.capabilities?.podometer ?? false,
      stepLength: selectedDevice.carrierStepLength ?? 0,
      weight: selectedDevice.carrierWeight ?? 0,
    );
  }

  void setActivity(List<ActivityEntity> activity) {
    state = state.copyWith(
      activityList: activity,
      isLoading: false,
    );
    setSelectedActivity();
  }

  void _onStepLengthChanged(){
    final value = double.tryParse(stepLengthController.text);

    if (value == null || value <= 0){
      state = state.copyWith(errorMessage: 'errorMessageStepLengthIsInvalid');
      return;
    }

    if (value == state.stepLength) return;

    state = state.copyWith(
      stepLength: value,
    );
  }

  void _onWeightChanged(){
    final value = double.tryParse(weightController.text);

    if (value == null || value <= 0){
      state = state.copyWith(errorMessage: 'errorMessageWeightIsInvalid');
      return;
    }

    if (value == state.weight) return;

    state = state.copyWith(
      weight: value,
    );
  }

  bool isSameDate(DateTime a, DateTime b){
    return a.year == b.year
        && a.month == b.month
        && a.day == b.day;
  }

  void setSelectedActivity() {

    final currentDate = state.selectedDate!;
    final weekAgo = DateTime(
      currentDate.year,
      currentDate.month,
      currentDate.day - 6
    );
    final weekActivity = state.activityList.where(
      (activity)=>activity.occurredAt.isAfter(weekAgo) && activity.occurredAt.isBefore(currentDate)
    ).toList();

    final selectedDateActivity = state.activityList.where(
      (activity)=>isSameDate(activity.occurredAt, currentDate)
    );

    final selectedActivity = selectedDateActivity.firstOrNull;

    state = state.copyWith(
        selectedActivity: selectedActivity,
        weekActivity: weekActivity
    );
  }

  Future<void> toggleEnabled(bool value) async {
    try {
      state = state.copyWith(isLoading: true);

      SetPedometerRequestEntity request = SetPedometerRequestEntity(deviceName: state.selectedDevice!.identificator);
      await _setPedometerUseCase.setPedometer(request: request);

      state = state.copyWith(enabled: value, isLoading: false);
    } catch (e) {
      if (!ref.mounted) return;

      state = state.copyWith(
        isLoading: false,
        errorMessage: e.toString(),
      );
    }
  }

  Future<void> pickDate(BuildContext context) async {
    FocusManager.instance.primaryFocus?.unfocus();

    final now = DateTime.now();
    final DateTime initial = state.selectedDate ?? now;

    final date = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: DateTime(1900, 1, 1),
      lastDate: now,
    );

    if (!ref.mounted) return;
    if (date == null) return;

    state = state.copyWith(selectedDate: date, errorMessage: '');
    setSelectedActivity();
  }

  Future<void> setStartTime(int index, TimeOfDay? value) async {
    if (value == null) return;

  }

  Future<void> setEndTime(int index, TimeOfDay? value) async {
    if (value == null) return;

  }

  Future<void> updateStepLength() async {
    if (state.errorMessage.isNotEmpty) return;
    print('FINO');
    //_updateSettingsUseCase.updateSettings(request:request);
  }

  Future<void> updateWeight() async {
    if (state.errorMessage.isNotEmpty) return;
    print('FINO');
    //_updateSettingsUseCase.updateSettings(request:request);
  }
}