import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:functions/src/features/functions/state/call_watch_view_state.dart';
import 'package:url_launcher/url_launcher.dart';

final callWatchViewModelProvider =
NotifierProvider.autoDispose<CallWatchViewModel, CallWatchViewState>(
  CallWatchViewModel.new,
);

class CallWatchViewModel extends Notifier<CallWatchViewState> {

  late final TextEditingController phoneController;

  static final RegExp _phoneRegex = RegExp(r'^\+?\d{6,15}$');
  
  @override
  CallWatchViewState build() {

    phoneController = TextEditingController();

    phoneController.addListener(_onPhoneChanged);

    ref.onDispose(disposeControllers);

    return const CallWatchViewState();
  }

  void _onPhoneChanged() {
    final text = phoneController.text;
    if (text == state.phone) return;

    state = state.copyWith(phone: text, errorMessage: '');
  }
  
  void call() async {
    final phone = state.phone;
    if (phone.isEmpty){
      state = state.copyWith(errorMessage: 'errorMessagePhoneIsEmpty');
      return;
    }
    if (!_phoneRegex.hasMatch(phone)) {
      state = state.copyWith(errorMessage: 'errorMessagePhoneIsInvalid');
      return;
    }

    final url = Uri(scheme: 'tel', path: phone);

    if (await canLaunchUrl(url)) {
      launchUrl(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  void disposeControllers() {
    phoneController.removeListener(_onPhoneChanged);

    phoneController.dispose();
  }
}
