import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/extensions/string_extension.dart';
import '../../voucher/models/my_product_status_type.dart';

class MyProductModel {
  final int? id;
  final String? title;
  final String? logo;
  final String? brandName;
  final String? expireTime;
  final String? createdAt;
  final String? updatedAt;
  final int? rawStatus;

  const MyProductModel({
    this.id,
    this.title,
    this.logo,
    this.brandName,
    this.expireTime,
    this.createdAt,
    this.updatedAt,
    this.rawStatus,
  });

  factory MyProductModel.fromJson(Map<String, dynamic> json) {
    try {
      return MyProductModel(
        id: (json['id'] as num?)?.toInt(),
        title: json['title'] as String?,
        logo: json['logo'] as String?,
        brandName: json['brand_name'] as String?,
        expireTime: json['expire_time'] as String?,
        createdAt: json['created_at'] as String?,
        updatedAt: json['updated_at'] as String?,
        rawStatus: json['status'] as int?,
      );
    } catch (e) {
      if (kDebugMode) {
        print('Failed to parse MyProductModel: $e');
      }
      rethrow;
    }
  }

  Map<String, dynamic> toJson() => {
    'id': id,
    'title': title,
    'logo': logo,
    'brand_name': brandName,
    'expire_time': expireTime,
    'created_at': createdAt,
    'updated_at': updatedAt,
    'status': rawStatus,
  };

  MyProductStatusType? get status {
    if (rawStatus == null) return null;
    return MyProductStatusType.fromRaw(rawStatus!);
  }

  DateTime? get expireDate {
    if (expireTime == null || expireTime!.isEmpty) return null;
    try {
      return DateTime.tryParse(expireTime!);
    } catch (e) {
      if (kDebugMode) {
        print('Failed to parse expireTime: $expireTime - $e');
      }
      return null;
    }
  }

  String get expire {
    final ex = expireTime ?? "";
    return ex.toDate()?.toFormattedString() ?? "";
  }

  String get deadline {
    if (expireDate == null) return '';
    try {
      final formatted = _formatDate(expireDate!);
      return 'HSD: $formatted';
    } catch (e) {
      if (kDebugMode) {
        print('Failed to format deadline: $e');
      }
      return 'HSD: Không xác định';
    }
  }

  String _formatDate(DateTime date) {
    return "${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}";
  }
}
