import 'package:intl/intl.dart';
import 'package:lba/data/model/workingHours.dart';

class IsOpenChecker {
  static const Map<String, String> _dayMap = {
    'monday': 'mo',
    'tuesday': 'tu',
    'wednesday': 'we',
    'thursday': 'th',
    'friday': 'fr',
    'saturday': 'sa',
    'sunday': 'su',
  };

  static bool isOpenNow(List<WorkingHours> workingHours) {
    final now = DateTime.now();
    final todayKey = _dayMap[DateFormat('EEEE').format(now).toLowerCase()] ?? '';

    final todaySchedule = workingHours.firstWhere(
      (day) => day.day.toLowerCase() == todayKey,
      orElse: () => WorkingHours(day: todayKey, shifts: []),
    );

    if (todaySchedule.shifts.isEmpty) return false;

    for (final shift in todaySchedule.shifts) {
      if (_isTimeBetween(now, shift.openAt, shift.closeAt)) {
        return true;
      }
    }

    return false;
  }

  static WorkingHours getTodaySchedule(List<WorkingHours> workingHours) {
    final now = DateTime.now();
    final todayKey = _dayMap[DateFormat('EEEE').format(now).toLowerCase()] ?? '';

    return workingHours.firstWhere(
      (day) => day.day.toLowerCase() == todayKey,
      orElse: () => WorkingHours(day: todayKey, shifts: []),
    );
  }

  static bool _isTimeBetween(DateTime now, String open, String close) {
    try {
      final openTime = _parseTime(open);
      final closeTime = _parseTime(close);
      final nowTime = Duration(hours: now.hour, minutes: now.minute);

      if (closeTime <= openTime) {
        // شیفت شبانه (مثلاً 22:00 تا 02:00)
        return nowTime >= openTime || nowTime <= closeTime;
      }

      return nowTime >= openTime && nowTime <= closeTime;
    } catch (_) {
      return false;
    }
  }

  static Duration _parseTime(String time) {
    final parts = time.split(':');
    final hour = int.parse(parts[0]);
    final minute = int.parse(parts[1]);
    return Duration(hours: hour, minutes: minute);
  }
}


String formatTime12Hour(String time24) {
  try {
    final parts = time24.split(':');
    final hour = int.parse(parts[0]);
    final minute = int.parse(parts[1]);

    final dateTime = DateTime(0, 1, 1, hour, minute);
    final formatter = DateFormat('hh:mm a');
    return formatter.format(dateTime);
  } catch (_) {
    return time24; 
  }
}