import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/core/database/models/enums.dart';

part 'invoice_model.g.dart';

@HiveType(typeId: HiveTypeIds.invoiceModel)
class InvoiceModel extends HiveObject {
  InvoiceModel({
    required this.invoiceId,
    required this.invoiceNumber,
    required this.userId,
    this.orderId,
    required this.invoiceType,
    required this.issueDate,
    required this.dueDate,
    required this.currency,
    required this.subtotalAmount,
    required this.taxAmount,
    required this.discountAmount,
    required this.shippingAmount,
    required this.totalAmount,
    required this.amountPaid,
    required this.amountRemaining,
    required this.status,
    this.paymentTerms,
    this.notes,
    this.erpnextInvoice,
    required this.createdAt,
    this.updatedAt,
    this.lastReminderSent,
  });

  @HiveField(0)
  final String invoiceId;
  @HiveField(1)
  final String invoiceNumber;
  @HiveField(2)
  final String userId;
  @HiveField(3)
  final String? orderId;
  @HiveField(4)
  final InvoiceType invoiceType;
  @HiveField(5)
  final DateTime issueDate;
  @HiveField(6)
  final DateTime dueDate;
  @HiveField(7)
  final String currency;
  @HiveField(8)
  final double subtotalAmount;
  @HiveField(9)
  final double taxAmount;
  @HiveField(10)
  final double discountAmount;
  @HiveField(11)
  final double shippingAmount;
  @HiveField(12)
  final double totalAmount;
  @HiveField(13)
  final double amountPaid;
  @HiveField(14)
  final double amountRemaining;
  @HiveField(15)
  final InvoiceStatus status;
  @HiveField(16)
  final String? paymentTerms;
  @HiveField(17)
  final String? notes;
  @HiveField(18)
  final String? erpnextInvoice;
  @HiveField(19)
  final DateTime createdAt;
  @HiveField(20)
  final DateTime? updatedAt;
  @HiveField(21)
  final DateTime? lastReminderSent;

  factory InvoiceModel.fromJson(Map<String, dynamic> json) => InvoiceModel(
    invoiceId: json['invoice_id'] as String,
    invoiceNumber: json['invoice_number'] as String,
    userId: json['user_id'] as String,
    orderId: json['order_id'] as String?,
    invoiceType: InvoiceType.values.firstWhere(
      (e) => e.name == json['invoice_type'],
    ),
    issueDate: DateTime.parse(json['issue_date']?.toString() ?? ''),
    dueDate: DateTime.parse(json['due_date']?.toString() ?? ''),
    currency: json['currency'] as String? ?? 'VND',
    subtotalAmount: (json['subtotal_amount'] as num).toDouble(),
    taxAmount: (json['tax_amount'] as num).toDouble(),
    discountAmount: (json['discount_amount'] as num).toDouble(),
    shippingAmount: (json['shipping_amount'] as num).toDouble(),
    totalAmount: (json['total_amount'] as num).toDouble(),
    amountPaid: (json['amount_paid'] as num).toDouble(),
    amountRemaining: (json['amount_remaining'] as num).toDouble(),
    status: InvoiceStatus.values.firstWhere((e) => e.name == json['status']),
    paymentTerms: json['payment_terms'] as String?,
    notes: json['notes'] as String?,
    erpnextInvoice: json['erpnext_invoice'] as String?,
    createdAt: DateTime.parse(json['created_at']?.toString() ?? ''),
    updatedAt: json['updated_at'] != null
        ? DateTime.parse(json['updated_at']?.toString() ?? '')
        : null,
    lastReminderSent: json['last_reminder_sent'] != null
        ? DateTime.parse(json['last_reminder_sent']?.toString() ?? '')
        : null,
  );

  Map<String, dynamic> toJson() => {
    'invoice_id': invoiceId,
    'invoice_number': invoiceNumber,
    'user_id': userId,
    'order_id': orderId,
    'invoice_type': invoiceType.name,
    'issue_date': issueDate.toIso8601String(),
    'due_date': dueDate.toIso8601String(),
    'currency': currency,
    'subtotal_amount': subtotalAmount,
    'tax_amount': taxAmount,
    'discount_amount': discountAmount,
    'shipping_amount': shippingAmount,
    'total_amount': totalAmount,
    'amount_paid': amountPaid,
    'amount_remaining': amountRemaining,
    'status': status.name,
    'payment_terms': paymentTerms,
    'notes': notes,
    'erpnext_invoice': erpnextInvoice,
    'created_at': createdAt.toIso8601String(),
    'updated_at': updatedAt?.toIso8601String(),
    'last_reminder_sent': lastReminderSent?.toIso8601String(),
  };

  bool get isOverdue =>
      DateTime.now().isAfter(dueDate) && status != InvoiceStatus.paid;
  bool get isPaid => status == InvoiceStatus.paid;
}
