import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class MyOrdersModel {
  String tankerName = '';
  String bookingid = '';
  String supplierId = '';
  String dateOfOrder = '';
  String typeofwater = '';
  String delivery_agent_mobile = '';
  String delivery_agent = '';
  String capacity = '';
  String address = '';
  String price = '';
  String customerId = '';
  String startTime = '';
  String stopTime = '';
  String orderStatus = '';
  String initialWaterLevel = '';
  String finalWaterLevel = '';
  String quantityDelivered = '';
  String amountPaid = '';
  String amountDue = '';
  String paymentMode = '';
  String deliverdWater = '';
  String supplierName = '';
  String deliveredDate = '';
  String displayDeliveredDate = '';
  String displayAddress = '';
  String expectedDateOfDelivery = '';
  String displayDateOfOrder = '';
  String paymentStatus = '';
  String tankName = '';
  var tankerRunningStatus;
  double lat = 0;
  double lng = 0;
  Color cardColor = Colors.white;
  String tank_otp='';
  String stop_otp='';
  String dbId='';

  MyOrdersModel();

  factory MyOrdersModel.fromJson(Map<String, dynamic> json) {
    final rtvm = MyOrdersModel();

    rtvm.tankerName = json['tankerName']?.toString() ?? '';
    rtvm.bookingid = json['bookingid']?.toString() ?? '';
    rtvm.supplierId = json['supplierId']?.toString() ?? '';
    rtvm.dateOfOrder = json['dateOfOrder']?.toString() ?? '';
    rtvm.typeofwater = json['typeofwater']?.toString() ?? '';
    rtvm.supplierName = json['supplierName']?.toString() ?? '';
    rtvm.delivery_agent_mobile = json['delivery_agent_mobile']?.toString() ?? '';
    rtvm.capacity = json['capacity']?.toString() ?? '';
    rtvm.address = json['address']?.toString() ?? '';
    rtvm.price = json['price']?.toString() ?? '';
    rtvm.orderStatus = json['orderStatus']?.toString().toLowerCase() ?? '';
    rtvm.customerId = json['customerId']?.toString() ?? '';
    rtvm.startTime = json['start_time']?.toString() ?? '';
    rtvm.stopTime = json['stop_time']?.toString() ?? '';
    rtvm.initialWaterLevel = json['initial_water_level']?.toString() ?? '';
    rtvm.finalWaterLevel = json['final_water_level']?.toString() ?? '';
    rtvm.quantityDelivered = json['quantityDelivered']?.toString() ?? '';
    rtvm.amountPaid = json['amount_paid']?.toString() ?? '';
    rtvm.amountDue = json['amount_due']?.toString() ?? '';
    rtvm.paymentMode = json['payment_mode']?.toString() ?? '';
    rtvm.deliverdWater = json['quantityDelivered']?.toString() ?? '';
    rtvm.deliveredDate = json['deliveredDate']?.toString() ?? '';
    rtvm.expectedDateOfDelivery = json["expectedDateOfDelivery"]?.toString() ?? '';
    rtvm.tankerRunningStatus = json['tankerRunningStatus'] ?? '';
    rtvm.delivery_agent = json['delivery_agent']?.toString() ?? '';
    rtvm.paymentStatus = json['payment_status']?.toString() ?? '';
    rtvm.tankName = json['tankName']?.toString() ?? '';
    rtvm.tank_otp = json['tank_otp']?.toString() ?? '';
    rtvm.dbId = json['_id']?.toString() ?? '';
    rtvm.stop_otp = json['stop_otp']?.toString() ?? '';


    // ✅ Handle Delivered Date (Safe Parsing)
    if (rtvm.deliveredDate.isNotEmpty) {
      try {
        final inputFormat = DateFormat("dd-MMM-yyyy - HH:mm");
        final dateTime = inputFormat.parse(rtvm.deliveredDate);
        final outputFormat = DateFormat("MMMM d yyyy, h:mm a");
        rtvm.displayDeliveredDate = outputFormat.format(dateTime);
      } catch (_) {
        rtvm.displayDeliveredDate = rtvm.deliveredDate; // fallback to raw
      }
    }

    // ✅ Handle Date of Order
    if (rtvm.dateOfOrder.isNotEmpty) {
      final raw = rtvm.dateOfOrder.trim();
      DateTime? dt;

      try {
        // Normalize format
        String s = raw.replaceAll(RegExp(r'\s*-\s*'), '-');
        s = s.replaceAllMapped(RegExp(r'(\d{1,2})-([A-Za-z]{3,9})-(\d{4})'), (m) {
          final mon = m.group(2)!;
          final cap = mon[0].toUpperCase() + mon.substring(1).toLowerCase();
          return "${m.group(1)}-$cap-${m.group(3)}";
        });

        final patterns = <String>[
          "dd-MMM-yyyy-HH:mm",
          "dd-MMM-yyyy HH:mm",
          "dd-MMM-yyyy",
          "dd-MM-yyyy HH:mm",
          "dd-MM-yyyy",
          "yyyy-MM-dd HH:mm:ss",
          "yyyy-MM-dd",
        ];

        for (final p in patterns) {
          try {
            dt = DateFormat(p, 'en_US').parseStrict(s);
            break;
          } catch (_) {}
        }

        if (dt == null) dt = DateTime.tryParse(raw);
      } catch (_) {}

      if (dt != null) {
        final hasTime = RegExp(r'\d{1,2}:\d{2}').hasMatch(raw);
        final fmt = DateFormat(hasTime ? "MMMM d yyyy, h:mm a" : "MMMM d yyyy");
        rtvm.displayDateOfOrder = fmt.format(dt);
      }
    }

    // ✅ Handle Address
    final rawAddr = (rtvm.address ?? '').trim();
    if (rawAddr.isNotEmpty) {
      final parts = rawAddr.split(',').map((e) => e.trim()).toList();
      parts.removeWhere((p) =>
      p.toLowerCase().contains("india") ||
          RegExp(r'\d{6}').hasMatch(p) ||
          p.toLowerCase().contains("telangana"));
      rtvm.displayAddress = parts.length >= 2 ? parts[parts.length - 2] : rawAddr;
    } else {
      rtvm.displayAddress = '';
    }

    // ✅ Latitude & Longitude Parsing
    rtvm.lat = double.tryParse(json['latitude']?.toString() ?? '0') ?? 0;
    rtvm.lng = double.tryParse(json['longitude']?.toString() ?? '0') ?? 0;

    return rtvm;
  }
}
