import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class DateHelper {
  static String formatDateT(String dateString) {
    return dateString.split('T')[0];
  }

  static DateTime parseStringToDate(String dateString) {
    final formatter = DateFormat('yyyy-MM-dd');
    return formatter.parse(dateString);
  }

  static String formatAsShortDate(DateTime date) {
    final formatter = DateFormat.yMd();
    return formatter.format(date);
  }

  static String formatAsLongDate(DateTime date) {
    final formatter = DateFormat.yMMMMEEEEd();
    return formatter.format(date);
  }

  static String formatAsTime(DateTime date) {
    final formatter = DateFormat.jm();
    return formatter.format(date);
  }

  static String formatAsYearMonthDay(DateTime date) {
    final formatter = DateFormat('y-MM-d');
    return date != null ? formatter.format(date) : "N/A";
  }

  static String formatAsCustomPattern(DateTime date, String pattern) {
    final formatter = DateFormat(pattern);
    return formatter.format(date);
  }

  static String formatAsDayMonthYear(DateTime? date) {
    final formatter = DateFormat('d MMM, y');
    return date != null ? formatter.format(date) : "N/A";
  }

  static String formatAsMonthDayYear(DateTime date) {
    final formatter = DateFormat('MMMM d, y');
    return formatter.format(date);
  }

  static String formatAsMonthYear(DateTime date) {
    final formatter = DateFormat('MMMM y');
    return formatter.format(date);
  }
}

extension TimeOfDayUtils on TimeOfDay {
  bool isAfter(TimeOfDay other) {
    final thisTime = DateTime(0, 1, 1, hour, minute);
    final otherTime = DateTime(0, 1, 1, other.hour, other.minute);
    return thisTime.isAfter(otherTime);
  }

  bool isBefore(TimeOfDay other) {
    final thisTime = DateTime(0, 1, 1, hour, minute);
    final otherTime = DateTime(0, 1, 1, other.hour, other.minute);
    return thisTime.isBefore(otherTime);
  }

  static TimeOfDay convertStringToTimeOfDay(String timeString) {
    bool is12HourFormat = timeString.contains(RegExp(r'AM|PM', caseSensitive: false));

    int hour;
    int minute;

    if (is12HourFormat) {
      List<String> parts = timeString.split(' '); // Split time and AM/PM part
      List<String> timeParts = parts[0].split(':'); // Split hours and minutes

      hour = int.parse(timeParts[0]);
      minute = int.parse(timeParts[1]);

      if (parts[1].toUpperCase() == 'PM' && hour != 12) {
        hour += 12;
      } else if (parts[1].toUpperCase() == 'AM' && hour == 12) {
        hour = 0;
      }
    } else {
      List<String> timeParts = timeString.split(':');
      hour = int.parse(timeParts[0]);
      minute = int.parse(timeParts[1]);
    }

    return TimeOfDay(hour: hour, minute: minute);
  }
}
