import 'dart:async';

import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_ecommerce_v1/core/system/system_setting.dart';
import 'package:niogu_ecommerce_v1/features/account/data/models/account_model.dart';
import 'package:niogu_ecommerce_v1/features/account/domain/entities/account.dart';
import 'package:niogu_ecommerce_v1/features/account/domain/repositories/i_account_repository.dart';
import 'package:niogu_ecommerce_v1/features/account/presentation/providers/account_provider.dart';

class CustomerController extends AutoDisposeAsyncNotifier<void> {
  late final IAccountRepository _accountRepository;

  @override
  FutureOr<void> build() {
    _accountRepository = ref.read(accountRepositoryProvider);
  }

  Future<void> updateCustomer(String name) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      final data = await _accountRepository.updateCustomer(
        CustomerInfoRequest(name: name),
      );

      if (data == null) return;

      await SystemSetting.setCustomerInfo(
        name: data.name,
        email: data.email,
        phoneNumber: data.phoneNumber,
      );
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> updatePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _accountRepository.updatePassword(
        oldPassword: oldPassword,
        newPassword: newPassword,
      );
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> saveCustomerAddress(CustomerAddress address) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _accountRepository.saveCustomerAddress(address);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }

  Future<void> deleteCustomerAddress(String id) async {
    state = const AsyncValue.loading();

    final result = await AsyncValue.guard(() async {
      await _accountRepository.deleteCustomerAddress(id);
    });

    state = result;

    if (result is AsyncError) throw result.error!;
  }
}

class CustomerAddressController
    extends AutoDisposeAsyncNotifier<List<CustomerAddress>> {
  @override
  FutureOr<List<CustomerAddress>> build() => _fetchCustomerAddresses();

  Future<List<CustomerAddress>> _fetchCustomerAddresses() async {
    final accountRepository = ref.read(accountRepositoryProvider);

    return await accountRepository.fetchCustomerAddresses();
  }

  Future<void> refresh() async {
    ref.invalidateSelf();

    await future;
  }
}
