import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:hmg_patient_app_new/features/qr_parking/qr_parking_repo.dart';

import '../../services/cache_service.dart';
import '../../services/error_handler_service.dart';
import 'models/qr_parking_response_model.dart';


class QrParkingViewModel extends ChangeNotifier {
  final QrParkingRepo qrParkingRepo;
  final ErrorHandlerService errorHandlerService;
  final CacheService cacheService;
   String IS_GO_TO_PARKING = 'IS_GO_TO_PARKING';

  bool isLoading = false;
  String? error;

  bool isSavePark = false;
  QrParkingResponseModel? qrParkingModel;
  List<QrParkingResponseModel> qrParkingList = [];

  QrParkingViewModel({
    required this.qrParkingRepo,
    required this.errorHandlerService,
    required this.cacheService,
  });


  Future<QrParkingResponseModel?> scanAndGetParking() async {
    try {
      error = null;
      isLoading = true;
      notifyListeners();

      final result = await BarcodeScanner.scan();

      if (result.type != ResultType.Barcode) {
        isLoading = false;
        notifyListeners();
        return null;
      }

      final raw = result.rawContent.trim();
      if (raw.isEmpty) {
        error = "Invalid QR Code";
        isLoading = false;
        notifyListeners();
        return null;
      }

      final qrParkingId = _extractQrParkingId(raw);
      if (qrParkingId == null) {
        error = "Invalid QR Code";
        isLoading = false;
        notifyListeners();
        return null;
      }

      final apiResult =
      await qrParkingRepo.getQrParking(qrParkingId: qrParkingId);

      final model = apiResult.fold(
            (failure) {
          errorHandlerService.handleError(failure: failure);
          error = failure.toString();
          return null;
        },
            (apiResponse) {
          qrParkingList = apiResponse.data ?? [];
          if (qrParkingList.isNotEmpty) {
            return qrParkingList.first;
          }
          error = "Invalid Qr Code";
          return null;
        },
      );

      if (model != null) {
        qrParkingModel = model;
        isSavePark = true;

        await cacheService.saveObject(
          key: IS_GO_TO_PARKING,
          value: model.toJson(),
        );
      }

      isLoading = false;
      notifyListeners();
      return model;
    } catch (e) {
      error = "Scan error";
      isLoading = false;
      notifyListeners();
      return null;
    }
  }

  /// Load saved parking
  Future<void> getIsSaveParking() async {
    isLoading = true;
    notifyListeners();

    final parking =
    await cacheService.getObject(key: IS_GO_TO_PARKING);

    if (parking != null) {
      isSavePark = true;
      qrParkingModel = QrParkingResponseModel.fromJson(
        Map<String, dynamic>.from(parking),
      );
    } else {
      isSavePark = false;
      qrParkingModel = null;
    }

    isLoading = false;
    notifyListeners();
  }

  /// Reset parking
  Future<void> clearParking() async {
    await cacheService.remove(key: IS_GO_TO_PARKING);
    isSavePark = false;
    qrParkingModel = null;
    notifyListeners();
  }

  int? _extractQrParkingId(String raw) {
    try {
      if (raw.startsWith("{")) {
        final data = jsonDecode(raw);
        return int.tryParse(data['QRParkingID'].toString());
      }
      return int.tryParse(raw);
    } catch (_) {
      return null;
    }
  }
}


