import 'dart:convert';
import 'dart:math';

import 'package:gymlink_module_web/interfaces/items.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<List<GymHistoryItem>> getHistory() async {
  final prefs = await SharedPreferences.getInstance();
  String historyString = prefs.getString('history') ?? "[]";
  List<GymHistoryItem> history = [];
  for (var historyItem in jsonDecode(historyString) as List<dynamic>) {
    history.add(GymHistoryItem.fromJson(historyItem));
  }
  history.sort((a, b) => b.id.compareTo(a.id));
  history = history.reversed.toList();
  return history;
}

Future<void> addToHistory(GymHistoryItemDetail item) async {
  final prefs = await SharedPreferences.getInstance();
  String historyString = prefs.getString('history') ?? "[]";
  List<GymHistoryItem> history = [];
  for (var historyItem in jsonDecode(historyString) as List<dynamic>) {
    history.add(GymHistoryItem.fromJson(historyItem));
  }
  item.id = Random().nextInt(100000).toString();
  String detailHistoryString = prefs.getString('detail_history') ?? "[]";
  List<GymHistoryItemDetail> detailHistory = [];
  for (var historyItem in jsonDecode(detailHistoryString) as List<dynamic>) {
    detailHistory.add(GymHistoryItemDetail.fromJson(historyItem));
  }
  List<Map<String, dynamic>> providers = [];
  for (final provider in item.providers) {
    providers.add(provider.toJson());
  }
  var json = {
    "id": item.id,
    "date": DateTime.now()
        .toLocal()
        .toLocal()
        .toString()
        .split(' ')[0]
        .replaceAll('-', '.')
        .split('.')
        .reversed
        .join('.'),
    "sum": item.sum,
    "pay_url": item.providers.where((e) => e.status == 'Не оплачен').isNotEmpty
        ? 'https://example.org'
        : null,
    "receiver": item.receiver,
    "email": item.email,
    "address": item.address,
    "providers": providers
  };
  final detailHistoryItem = GymHistoryItemDetail.fromJson(json);
  detailHistory.add(detailHistoryItem);
  history.add(GymHistoryItem(
    date: detailHistoryItem.date,
    id: detailHistoryItem.id,
    photo: detailHistoryItem.providers[0].items[0].photo,
    sum: detailHistoryItem.sum,
  ));
  prefs.setString('history', jsonEncode(history));
  prefs.setString('detail_history', jsonEncode(detailHistory));
}

Future<GymHistoryItemDetail?> getHistoryDetail(String id) async {
  final prefs = await SharedPreferences.getInstance();
  String historyString = prefs.getString('detail_history') ?? "[]";
  for (var historyItem in jsonDecode(historyString) as List<dynamic>) {
    if (GymHistoryItemDetail.fromJson(historyItem).id == id) {
      return GymHistoryItemDetail.fromJson(historyItem);
    }
  }
  return null;
}

Future<void> payOrder(String id) async {
  final prefs = await SharedPreferences.getInstance();
  String historyString = prefs.getString('detail_history') ?? "[]";
  List<GymHistoryItemDetail> history = [];
  for (var historyItem in jsonDecode(historyString) as List<dynamic>) {
    history.add(GymHistoryItemDetail.fromJson(historyItem));
  }
  List<GymHistoryItemDetail> newHistory = [];
  for (final historyItem in history) {
    if (historyItem.id == id) {
      for (final provider in historyItem.providers) {
        if (provider.status == 'Не оплачен') {
          provider.status = 'Оплачен';
        }
      }
      historyItem.payUrl = null;
    }
    newHistory.add(historyItem);
  }
  prefs.setString('detail_history', jsonEncode(newHistory));
}
