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() {
    return RegExp(r'^0\d{9}$').hasMatch(this);
  }
}

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

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

  Uri? toUri() {
    final s = trim();
    if (s.isEmpty || s.contains(' ')) return null;
    final uri = Uri.tryParse(s);
    if (uri == null) return null;
    // Phải là URL tuyệt đối + http/https
    if (!uri.isAbsolute) return null;
    if (uri.scheme != 'http' && uri.scheme != 'https') return null;
    return uri;
  }
}

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://');
}
