import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;

import 'package:fluttertoast/fluttertoast.dart';
import 'package:mc_common_app/exceptions/api_exception.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/widgets/loading_dialog.dart';

class Utils {
  static bool _isLoadingVisible = false;

  static bool get isLoading => _isLoadingVisible;

  static void showToast(String message) {
    Fluttertoast.showToast(
        msg: message, toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.BOTTOM, timeInSecForIosWeb: 2, backgroundColor: Colors.black54, textColor: Colors.white, fontSize: 16.0);
  }

  static dynamic getNotNullValue(List<dynamic> list, int index) {
    try {
      return list[index];
    } catch (ex) {
      return null;
    }
  }

  static int stringToHex(String colorCode) {
    try {
      return int.parse(colorCode.replaceAll("#", "0xff"));
    } catch (ex) {
      return (0xff000000);
    }
  }

  static void showLoading(BuildContext context) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _isLoadingVisible = true;
      showDialog(
        context: context,
        barrierColor: Colors.black.withOpacity(0.5),
        builder: (BuildContext context) => LoadingDialog(),
      ).then((value) {
        _isLoadingVisible = false;
      });
    });
  }

  static void hideLoading(BuildContext context) {
    if (_isLoadingVisible) {
      _isLoadingVisible = false;
      Navigator.of(context).pop();
    }
    _isLoadingVisible = false;
  }

  static void handleException(dynamic exception, Function(String)? onErrorMessage) {
    String errorMessage;
    if (exception is APIException) {
      if (exception.message == APIException.UNAUTHORIZED) {
        return;
      } else {
        errorMessage = exception.error?.errorMessage ?? exception.message;
      }
    } else {
      errorMessage = APIException.UNKNOWN;
    }
    if (onErrorMessage != null) {
      onErrorMessage(errorMessage);
    } else {
      showToast(errorMessage);
    }
  }

  static Color getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll('#', '');

    if (hexColor.length == 6) {
      hexColor = 'FF' + hexColor;
    }

    return Color(int.parse(hexColor, radix: 16));
  }

  static Widget spacerVertical(double v) {
    return SizedBox(
      height: v,
      width: double.infinity,
    );
  }

  static String convertFileToBase64(File file) {
    List<int> imageBytes = file.readAsBytesSync();
    return base64Encode(imageBytes);
  }

  static Future delay(int millis) async {
    return await Future.delayed(Duration(milliseconds: millis));
  }

  static inkWellCorner({double? r}) {
    return RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(r ?? 4),
    );
  }

  static Widget spacerHorizontal(double v) {
    return SizedBox(
      height: v,
      width: v,
    );
  }

  static Widget mDivider(Color color, {double? h}) {
    return Container(
      width: double.infinity,
      height: h ?? 1,
      color: color,
    );
  }

  static Widget mDivider3({double? h}) {
    return Container(
      width: double.infinity,
      height: h ?? 1,
      color: borderLightColor!.withOpacity(0.7),
    );
  }

  static Widget mDivider2(Color color, double w) {
    return Container(
      width: w,
      height: 1,
      color: color,
    );
  }

  static InputDecoration txtField(String label) {
    return InputDecoration(
      border: InputBorder.none,
      focusedBorder: InputBorder.none,
      enabledBorder: InputBorder.none,
      errorBorder: InputBorder.none,
      hintText: label,
      hintStyle: const TextStyle(color: Colors.grey),
      disabledBorder: InputBorder.none,
      isDense: false,
      contentPadding: const EdgeInsets.only(left: 15, right: 15),
    );
  }

  static Widget mFlex(int f) {
    return Flexible(
      flex: f,
      child: const SizedBox(
        width: double.infinity,
        height: double.infinity,
      ),
    );
  }

  static Widget mExp(int f) {
    return Expanded(
      flex: f,
      child: Container(
        width: double.infinity,
      ),
    );
  }

  static String checkFileExt(String path) {
    String ex = p.extension(path);
    var parts = ex.split('.');
    return parts[1] ?? "png"; // '.dart'
  }

  static spacer() {
    return const SizedBox(
      height: 8,
    );
  }

  static cardRadius(double radius) {
    return RoundedRectangleBorder(
      side: const BorderSide(color: Colors.transparent, width: 1),
      borderRadius: BorderRadius.circular(radius),
    );
  }

  static cardRadiusWithoutBorder(double radius) {
    return RoundedRectangleBorder(
      side: const BorderSide(color: Colors.transparent, width: 1),
      borderRadius: BorderRadius.circular(radius),
    );
  }

  static Image imageFromBase64String(String base64String) {
    return Image.memory(base64Decode(base64String));
  }

  static Uint8List dataFromBase64String(String base64String) {
    return base64Decode(base64String);
  }

  static String base64String(Uint8List data) {
    return base64Encode(data);
  }

  static Widget overLayWidget({double? width, double? height, List<Color>? color}) {
    return Container(
      width: width ?? double.infinity,
      height: height ?? 60,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: color ??
              [
                Colors.black.withOpacity(0.2),
                Colors.black.withOpacity(0.1),
                Colors.black.withOpacity(0.004),
              ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          tileMode: TileMode.clamp,
        ),
      ),
    );
  }

  static Decoration containerRadius(Color color, double r) {
    return BoxDecoration(
      color: color,
      borderRadius: BorderRadius.all(Radius.circular(r)),
    );
  }

  static Decoration containerRadiusTop({Color? color, double? r}) {
    return BoxDecoration(
      color: color ?? Colors.white,
      borderRadius: BorderRadius.only(topRight: Radius.circular(r ?? 12), topLeft: Radius.circular(r ?? 12)),
    );
  }

  static Decoration containerRadiusBorder(Color color, double r) {
    return BoxDecoration(
      color: Colors.transparent,
      border: Border.all(color: color, width: 1),
      borderRadius: BorderRadius.all(Radius.circular(r)),
    );
  }

  static Decoration containerRadiusBottom(Color color, double r) {
    return BoxDecoration(
      color: color,
      borderRadius: BorderRadius.only(bottomLeft: Radius.circular(r), bottomRight: Radius.circular(r)),
    );
  }

  static ShapeBorder cardRadiusTop(double radius) {
    return RoundedRectangleBorder(
      side: const BorderSide(color: Colors.transparent, width: 0),
      borderRadius: BorderRadius.only(topLeft: Radius.circular(radius), topRight: Radius.circular(radius)),
    );
  }

  static Decoration containerColorRadiusBorderWidth(Color background, double radius, Color color, double w) {
    return BoxDecoration(
      color: background,
      border: Border.all(
          width: w, //
          color: color //                  <--- border width here
          ),
      borderRadius: BorderRadius.circular(radius),
    );
  }

  static ShapeBorder cardRadiusTop2(double radius) {
    return RoundedRectangleBorder(
      borderRadius: BorderRadius.only(topLeft: Radius.circular(radius), topRight: Radius.circular(radius)),
    );
  }

  static ShapeBorder cardRadiusBottom(double radius) {
    return RoundedRectangleBorder(
      borderRadius: BorderRadius.only(bottomLeft: Radius.circular(radius), bottomRight: Radius.circular(radius)),
    );
  }

  static Decoration containerColorRadiusBorder(Color background, double radius, Color color) {
    return BoxDecoration(
      color: background,
      border: Border.all(
          width: 1, //
          color: color //                  <--- border width here
          ),
      borderRadius: BorderRadius.circular(radius),
    );
  }

  static bool passwordValidateStructure(String value) {
    String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#\$&*~]).{6,}$';
    RegExp regExp = RegExp(pattern);
    return regExp.hasMatch(value);
  }

  static bool isEmailValid(String email) {
    String p = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
    RegExp regExp = RegExp(p);
    return regExp.hasMatch(email);
  }
}
