import 'package:hive_ce/hive.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/features/orders/domain/entities/order.dart';

part 'order_model.g.dart';

/// Order Model - Type ID: 6
///
/// Simplified model matching API response structure
@HiveType(typeId: HiveTypeIds.orderModel)
class OrderModel extends HiveObject {
  /// Order ID/Number (from API 'name' field)
  @HiveField(0)
  final String name;

  /// Transaction date
  @HiveField(1)
  final String transactionDate;

  /// Expected delivery date
  @HiveField(2)
  final String deliveryDate;

  /// Delivery address
  @HiveField(3)
  final String address;

  /// Grand total amount
  @HiveField(4)
  final double grandTotal;

  /// Status label (Vietnamese)
  @HiveField(5)
  final String status;

  /// Status color (Warning, Success, Danger, Info, Secondary)
  @HiveField(6)
  final String statusColor;

  OrderModel({
    required this.name,
    required this.transactionDate,
    required this.deliveryDate,
    required this.address,
    required this.grandTotal,
    required this.status,
    required this.statusColor,
  });

  /// Create from JSON (API response)
  factory OrderModel.fromJson(Map<String, dynamic> json) {
    return OrderModel(
      name: json['name'] as String? ?? '',
      transactionDate: json['transaction_date'] as String? ?? '',
      deliveryDate: json['delivery_date'] as String? ?? '',
      address: json['address'] as String? ?? '',
      grandTotal: (json['grand_total'] as num?)?.toDouble() ?? 0.0,
      status: json['status'] as String? ?? '',
      statusColor: json['status_color'] as String? ?? 'Secondary',
    );
  }

  /// Convert to JSON
  Map<String, dynamic> toJson() => {
        'name': name,
        'transaction_date': transactionDate,
        'delivery_date': deliveryDate,
        'address': address,
        'grand_total': grandTotal,
        'status': status,
        'status_color': statusColor,
      };

  /// Get parsed transaction date
  DateTime? get transactionDateTime {
    try {
      return DateTime.parse(transactionDate);
    } catch (e) {
      return null;
    }
  }

  /// Get parsed delivery date
  DateTime? get deliveryDateTime {
    try {
      return DateTime.parse(deliveryDate);
    } catch (e) {
      return null;
    }
  }

  /// Convert to domain entity
  Order toEntity() {
    return Order(
      name: name,
      transactionDate: transactionDate,
      deliveryDate: deliveryDate,
      address: address,
      grandTotal: grandTotal,
      status: status,
      statusColor: statusColor,
    );
  }

  /// Create from domain entity
  factory OrderModel.fromEntity(Order entity) {
    return OrderModel(
      name: entity.name,
      transactionDate: entity.transactionDate,
      deliveryDate: entity.deliveryDate,
      address: entity.address,
      grandTotal: entity.grandTotal,
      status: entity.status,
      statusColor: entity.statusColor,
    );
  }
}
