import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:qpay/http/http.dart';
import 'package:qpay/models/api_response.dart';
import 'package:qpay/screens/home/home_controller.dart' as hc;
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:qpay/screens/transaction_controller.dart';

import '../../models/pageable_model.dart';

part 'recipients_controller.freezed.dart';
part 'recipients_controller.g.dart';

class RecipientModel {
  String? creditAccount;
  String? errorMessage;
  hc.BillProvider? selectedProvider;
  bool isLoading = false;
  List<Recipient> recipients = [];
}

@freezed
abstract class Recipient with _$Recipient {
  const factory Recipient({
    @JsonKey(includeIfNull: false) String? uid,
    @JsonKey(includeIfNull: false) String? name,
    @JsonKey(includeIfNull: false) String? email,
    @JsonKey(includeIfNull: false) String? phoneNumber,
    @JsonKey(includeIfNull: false) String? address,
    @JsonKey(includeIfNull: false) String? account,
    @JsonKey(includeIfNull: false) String? initials,
    @JsonKey(includeIfNull: false) String? latestProviderLabel,
  }) = _Recipient;

  factory Recipient.fromJson(Map<String, dynamic> json) =>
      _$RecipientFromJson(json);
}

class RecipientsController extends ChangeNotifier {
  final RecipientModel model = RecipientModel();
  final http = Http();
  BuildContext context;

  RecipientsController(this.context) {
    model.selectedProvider = Provider.of<TransactionController>(
      context,
      listen: false,
    ).model.selectedProvider;
  }

  Future<ApiResponse<List<Recipient>>> getRecipients([
    Map<String, String>? params,
  ]) async {
    model.errorMessage = null;
    model.isLoading = true;
    model.recipients = getDummyRecipients();

    notifyListeners();

    try {
      final response = await http.get(
        '/public/recipients?${buildQueryParameters(params ?? {})}',
      );
      final page = PageableModel.fromJson(response as Map<String, dynamic>);
      model.recipients.clear();
      model.recipients.addAll(
        page.content.map((e) => Recipient.fromJson(e)).toList(),
      );
      model.isLoading = false;
      notifyListeners();
      return ApiResponse.success(model.recipients);
    } catch (e, s) {
      if (kDebugMode) {
        logger.e(e);
        logger.e(s);
      }

      model.errorMessage = e.toString();
      model.recipients = [];
      model.isLoading = false;
      notifyListeners();
      return ApiResponse.failure(
        "Problem fetching recipients, are you connected to the internet?",
      );
    }
  }

  String buildQueryParameters(Map<String, String> params) {
    if (params.isEmpty) {
      return '';
    }

    String query = '';
    params.forEach((key, value) {
      query += '$key=$value&';
    });
    return query.substring(0, query.length - 1);
  }

  void updateCreditAccount(String account) {
    model.creditAccount = account;
    notifyListeners();
  }

  void addRecipient(Recipient recipient) {
    model.recipients.add(recipient);
    notifyListeners();
  }

  void removeRecipient(String uid) {
    model.recipients.removeWhere((recipient) => recipient.uid == uid);
    notifyListeners();
  }

  List<Recipient> getDummyRecipients() {
    return [
      Recipient(
        uid: '1',
        name: 'Vusumuzi Khoza',
        phoneNumber: '+263773591219',
        email: 'vusumuzi@gmail.com',
        address: '123 Main St, Anytown, USA',
        account: '1234567890',
        initials: 'VK',
        latestProviderLabel: 'MTN',
      ),
    ];
  }
}
