import 'package:krow/features/profile/certificates/data/models/staff_certificate.dart';

class CertificatesState {
  final bool showError;
  final bool loading;
  final bool success;
  List<CertificatesViewModel> certificatesItems = [];

  CertificatesState(
      {this.showError = false,
      this.certificatesItems = const [],
      this.loading = false,
      this.success = false});

  copyWith(
      {bool? showError,
      List<CertificatesViewModel>? certificatesItems,
      bool? loading,
      bool? success}) {
    return CertificatesState(
      showError: showError ?? this.showError,
      certificatesItems: certificatesItems ?? this.certificatesItems,
      loading: loading ?? false,
      success: success ?? false,
    );
  }
}

class CertificatesViewModel {
  String? id;
  String certificateId;
  final String title;
  bool uploading;
  String? imageUrl;
  String? expirationDate;
  CertificateStatus? status;

  CertificatesViewModel({
    this.id,
    required this.certificateId,
    required this.title,
    this.expirationDate,
    this.imageUrl,
    this.uploading = false,
    this.status,
  });

  void clear() {
    id = null;
    imageUrl = null;
    expirationDate = null;
    status = null;
  }

  void applyNewStaffCertificate(StaffCertificate newCertificate) {
    id = newCertificate.id;
    imageUrl = newCertificate.file;
    expirationDate = newCertificate.expirationDate;
    status = newCertificate.status;
  }

  bool get isExpired {
    if (expirationDate == null) return false;
    DateTime expiration = DateTime.parse(expirationDate!);
    DateTime now = DateTime.now();
    return now.isAfter(expiration);
  }

  String getExpirationInfo() {
    if (expirationDate == null) return '';
    DateTime expiration = DateTime.parse(expirationDate!);
    DateTime now = DateTime.now();
    Duration difference = expiration.difference(now);
    String formatted =
        '${expiration.month.toString().padLeft(2, '0')}.${expiration.day.toString().padLeft(2, '0')}.${expiration.year}';

    if (difference.inDays <= 0) {
      return '$formatted (expired)';
    } else if (difference.inDays < 14) {
      return '$formatted (expires in ${difference.inDays} days)';
    } else {
      return formatted;
    }
  }

  bool expireSoon() {
    if (expirationDate == null) return false;
    DateTime expiration = DateTime.parse(expirationDate!);
    DateTime now = DateTime.now();
    Duration difference = expiration.difference(now);
    return difference.inDays <= 14;
  }
}
