import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:helpers/helpers/print.dart';
import 'package:intl/intl.dart';
import 'package:rluv/global/styles.dart';
import 'package:rluv/main.dart';

String formatDate(DateTime time) {
  return DateFormat('EEEE, dd MMMM yyyy').format(time);
}

DateTime dateFromJson(int value) => DateTime.fromMillisecondsSinceEpoch(value);

int? dateToJson(DateTime? value) => value?.millisecondsSinceEpoch;

bool boolFromJson(int value) => value == 1;

int boolToJson(bool hide) => hide ? 1 : 0;

String colorToJson(Color color) =>
    color.toString().split('(0x')[1].split(')')[0];

Color colorFromJson(String hex) => Color(int.parse(hex, radix: 16));

String? optionalColorToJson(Color? optionalColor) => optionalColor == null
    ? null
    : optionalColor.toString().split('(0x')[1].split(')')[0];

Color? optionalColorFromJson(String? hex) =>
    hex == null ? null : Color(int.parse(hex, radix: 16));

Brightness getBrightness(Color color) =>
    ThemeData.estimateBrightnessForColor(color);

List<Color> generateColorList() {
  List<Color> colors = [];
  for (int i = 100; i <= 255; i += 30) {
    // Red value variations
    for (int j = 100; j <= 255; j += 30) {
      // Green value variations
      for (int k = 100; k <= 255; k += 30) {
        // Blue value variations
        final alpha = Random().nextInt(256) + 50 % 255;
        colors.add(Color.fromARGB(alpha, i, j, k));
      }
    }
  }
  colors.shuffle();
  return colors;
}

extension MonetaryExtension on double {
  String currency() {
    final numStr = toStringAsFixed(2);
    final pieces = numStr.split(".");
    if (pieces.length == 1) {
      return "\$${pieces.first}.00";
    } else {
      if (pieces.length > 2) {
        printBlue(pieces);
      }
      return '\$${pieces[0]}.${pieces[1].padRight(2, "0")}';
    }
  }
}

void setDevicePortraitOrientation() {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);
}

enum SnackType { info, success, error }

void showSnack(
    {required WidgetRef ref,
    required String text,
    SnackType type = SnackType.info,
    Duration duration = const Duration(seconds: 2)}) {
  final messengerKey = ref.read(scaffoldMessengerKeyProvider);
  if (messengerKey.currentState == null) {
    printPink('Cannot show snackbar, state == null');
    return;
  }
  final color = type == SnackType.info
      ? Styles.washedStone
      : type == SnackType.success
          ? Styles.seaweedGreen
          : Styles.expensesRed;
  final textStyle = TextStyle(
    fontSize: 16,
    color: color,
  );
  messengerKey.currentState!.showSnackBar(SnackBar(
    elevation: 8,
    backgroundColor: Styles.deepPurpleNurple,
    shape: const RoundedRectangleBorder(
      borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)),
    ),
    content: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 14.0),
            child: Icon(
                type == SnackType.success ? Icons.check_circle : Icons.info,
                color: color),
          ),
          Text(text, style: textStyle),
        ],
      ),
    ),
  ));
}

bool isEmailValid(String email) {
  final RegExp regex =
      RegExp(r"^[a-zA-Z0-9.a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$");
  return regex.hasMatch(email);
}

bool isUsernameValid(String username) {
  final RegExp regex = RegExp(r"[a-zA-Z0-9._-]");
  return regex.hasMatch(username);
}
