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

import '../common/settings.dart';


class PlanRequestModel {
  String typeofwater='';
  String supplierName = '';
  String date = '';
  String time = '';
  String address='';
  String displayAddress = '';
  String capacity = '';
  String quantity = '';
  String quotedAmount='';
  String status='';
  double lat=0;
  double lng=0;
  double distanceInMeters=0;
  Color cardColor=Colors.white;
  String dbId = '';
  String supplierId = '';
  String acceptedTime = '';
  String startDate = '';
  String endDate = '';
  String biddingPrice = '';
  String actualPrice='';
  String paymentType='';
  String advanceAmount='';
  List dates=[];
  String frequency='';

  PlanRequestModel();

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

    rtvm.status = json['status'] ?? '';
    rtvm.typeofwater = json['type_of_water'] ?? '';
    rtvm.date = json['date'] ?? '';
    rtvm.time = json['time'] ?? '';
    rtvm.startDate=json['start_date']??'';
    rtvm.endDate=json['end_date']??'';
    rtvm.capacity = json['capacity'] ?? '';
    rtvm.quantity = json['quantity'] ?? '';
    rtvm.biddingPrice = json['bidding_price'].toString() ?? '';
    rtvm.actualPrice = json['actual_price'].toString() ?? '';
    rtvm.paymentType = json['payment_type'].toString() ?? '';
    rtvm.advanceAmount = json['adavnce_amount'].toString() ?? '';
    rtvm.dates = json['dates']?? [];
    rtvm.dbId=json['_id']?? '';
    rtvm.frequency= json["weekly_count"].toString()??'';
    final suppliers = json['requested_suppliers'] as List?;

    if (suppliers != null && suppliers.isNotEmpty) {
      final supplier = suppliers[0];
      rtvm.quotedAmount = supplier['quoted_amount']?.toString() ?? '0.00';
      rtvm.supplierName = supplier['supplier']?['suppliername'] ?? '';
      rtvm.supplierId = supplier['supplierId'] ?? '';
      rtvm.address = supplier['supplier']['profile']['office_address'] ?? '';
      rtvm.lat =supplier['supplier']?['latitude'] ?? '';
      rtvm.lng = supplier['supplier']?['longitude'] ?? '';
      rtvm.acceptedTime = supplier['time'] ?? '';
    } else {
      rtvm.quotedAmount = '';
      rtvm.supplierName = '';
      rtvm.address = '';
      rtvm.lat =0.0;
      rtvm.lng =0.0;
    }
    List<String> parts = rtvm.address.split(',');
    if (parts.length > 4) {
      rtvm.displayAddress = parts[2].trim();
    } else {
      rtvm.displayAddress = rtvm.address; // fallback
    }



    rtvm.distanceInMeters = double.parse((Geolocator.distanceBetween(
        rtvm.lat,
        rtvm.lng,
        AppSettings.userLatitude,
        AppSettings.userLongitude
    ) / 1000).toStringAsFixed(2));

    return rtvm;
  }

}