import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;

extension PhoneValidator on String {
  bool isPhoneValid() {
    final phone = replaceAll(RegExp(r'\s+'), '');
    final regex = RegExp(r'^(0|\+84)(3[2-9]|5[6|8|9]|7[0|6-9]|8[1-5]|9[0-4|6-9])[0-9]{7}$');
    return regex.hasMatch(phone);
  }
}

extension NullableString on String? {
  String orIfBlank(String fallback) {
    final s = this?.trim();
    return (s == null || s.isEmpty) ? fallback : s;
  }

  String get orEmpty => this ?? '';

  bool get hasText => (this?.trim().isNotEmpty ?? false);

  bool get isNullOrBlank => (this == null || this!.trim().isEmpty);
}

extension StringUrlExtension on String {
  String get urlDecoded => Uri.decodeFull(this);

  Uri? toUri() {
    final s = trim();
    if (s.isEmpty) return null;

    final normalized = s.startsWith(RegExp(r'https?://', caseSensitive: false))
        ? s
        : 'https://$s';

    final cleaned = normalized.replaceAll('\n', '').replaceAll('\r', '');
    try {
      return Uri.parse(cleaned);
    } catch (e) {
      debugPrint('Invalid URL: $cleaned ($e)');
      return null;
    }
  }
}

extension StringConvert on String {
  String toSha256() {
    var bytes1 = utf8.encode(this);
    var digest1 = sha256.convert(bytes1);
    return digest1.toString();
  }

  String capitalizeWords() {
    return split(' ').map((word) {
      if (word.isEmpty) return word;
      return word[0].toUpperCase() + word.substring(1).toLowerCase();
    }).join(' ');
  }
}

/// Hàm parse hex -> Color
Color parseHexColor(String hexString, {Color fallbackColor = Colors.grey}) {
  try {
    if (hexString.startsWith('#')) {
      hexString = hexString.replaceFirst('#', '');
    }
    if (hexString.length == 6) {
      hexString = 'ff$hexString';
    }
    return Color(int.parse(hexString, radix: 16));
  } catch (e) {
    return fallbackColor;
  }
}

extension StringDateExtension on String {
  DateTime? toDate() {
    if (trim().isEmpty) return null;
    try {
      return DateTime.parse(this); // 🚀 Dùng Dart core parse luôn đúng
    } catch (e) {
      print('❌ Date parse failed for "$this": $e');
      return null;
    }
  }

  DateTime? toDateFormat(String format) {
    if (trim().isEmpty) return null;
    try {
      return intl.DateFormat(format).parseStrict(this);
    } catch (e) {
      print('❌ Date parse failed for "$this" with format "$format": $e');
      return null;
    }
  }
}

extension HexColorExtension on String {
  Color? toColor() {
    try {
      final hex = replaceAll('#', '').toUpperCase();
      if (hex.length == 6) {
        return Color(int.parse('FF$hex', radix: 16)); // thêm alpha mặc định
      } else if (hex.length == 8) {
        return Color(int.parse(hex, radix: 16));
      }
    } catch (_) {
      // Ignored – return null bên dưới
    }
    return null;
  }
}

extension ParseInt on String {
  num? toNum() {
    try {
      final doubleValue = double.parse(this);
      return doubleValue % 1 == 0 ? doubleValue.toInt() : doubleValue;
    } catch (e) {
      print('❌ String to Int parse failed for "$this": $e');
      return 0;
    }
  }

  int? toInt() {
    final s = trim();
    if (s.isEmpty) return null;
    final normalized = s.replaceAll(RegExp(r'[,\s_]'), '');
    final asInt = int.tryParse(normalized);
    if (asInt != null) return asInt;

    final asDouble = double.tryParse(normalized);
    if (asDouble != null && asDouble == asDouble.truncateToDouble()) {
      return asDouble.toInt();
    }
    return null;
  }
}

bool isHttpUrl(String? url) {
  if (url == null) return false;
  return url.startsWith('http://') || url.startsWith('https://');
}
