// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'dart:async';

import 'package:wyatt_authentication_bloc/src/core/constants/form_field.dart';
import 'package:wyatt_authentication_bloc/src/core/constants/form_name.dart';
import 'package:wyatt_authentication_bloc/src/domain/repositories/authentication_repository.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';

part 'password_reset_state.dart';

/// {@template password_reset_cubit}
/// Cubit that allows user to reset his password
/// {@endtemplate}
class PasswordResetCubit<Extra> extends FormDataCubit<PasswordResetState> {
  /// {@macro password_reset_cubit}
  PasswordResetCubit({
    required this.authenticationRepository,
  }) : super(
          PasswordResetState(
            form: authenticationRepository.formRepository
                .accessForm(AuthFormName.passwordResetForm),
          ),
        );

  /// The repository that handles the authentication
  final AuthenticationRepository<Extra> authenticationRepository;
  FormRepository get formRepository => authenticationRepository.formRepository;

  @override
  String get formName => AuthFormName.passwordResetForm;

  @override
  FutureOr<void> dataChanged<Value>(
    String key,
    FormInputValidator<Value, ValidationError> dirtyValue,
  ) {
    final form = formRepository.accessForm(formName).clone();

    try {
      form.updateValidator(key, dirtyValue);
      formRepository.updateForm(form);
    } catch (e) {
      rethrow;
    }

    emit(
      state.copyWith(form: form, status: form.validate()),
    );
  }

  @override
  FutureOr<void> reset() {
    final form = state.form.reset();
    formRepository.updateForm(form);
    emit(
      state.copyWith(form: form, status: form.validate()),
    );
  }

  @override
  FutureOr<void> update(
    WyattForm form, {
    SetOperation operation = SetOperation.replace,
  }) {
    final WyattForm current = formRepository.accessForm(formName).clone();
    final WyattForm newForm = operation.operation.call(current, form);
    formRepository.updateForm(newForm);

    emit(
      state.copyWith(
        form: newForm,
        status: newForm.validate(),
      ),
    );
  }

  @override
  FutureOr<void> validate() {
    emit(
      state.copyWith(
        status: formRepository.accessForm(formName).validate(),
      ),
    );
  }

  /// Sends a password reset email to the user
  @override
  FutureOr<void> submit() async {
    if (!state.status.isValidated) {
      return;
    }

    emit(state.copyWith(status: FormStatus.submissionInProgress));

    final form = formRepository.accessForm(formName);
    final email = form.valueOf<String?>(AuthFormField.email);

    if (email.isNullOrEmpty) {
      emit(
        state.copyWith(
          errorMessage: 'An error occured while retrieving data from the form.',
          status: FormStatus.submissionFailure,
        ),
      );
    }

    final response = await authenticationRepository.sendPasswordResetEmail(
      email: email!,
    );

    emit(
      response.fold(
        (value) => state.copyWith(status: FormStatus.submissionSuccess),
        (error) => state.copyWith(
          errorMessage: error.message,
          status: FormStatus.submissionFailure,
        ),
      ),
    );
  }

  void emailChanged(String value) {
    final emailValidatorType = formRepository
        .accessForm(formName)
        .validatorOf(AuthFormField.email)
        .runtimeType;
    assert(
      emailValidatorType == Email,
      'Use emailCustomChanged(...) with validator $emailValidatorType',
    );

    final Email email = Email.dirty(value);
    dataChanged(AuthFormField.email, email);
  }

  /// Same as [emailChanged] but with a custom [Validator].
  ///
  /// Sort of short hand for [dataChanged].
  void emailCustomChanged<
      Validator extends FormInputValidator<String?, ValidationError>>(
    Validator validator,
  ) {
    dataChanged(AuthFormField.email, validator);
  }

  // TODO(wyatt): create base_password_reset_cubit and create mixins
}
