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 StringConvert on String {
  String toSha256() {
    var bytes1 = utf8.encode(this);
    var digest1 = sha256.convert(bytes1);
    return digest1.toString();
  }
}

/// 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;
  }
}