import 'package:base_project/data/response/status.dart';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:http_parser/http_parser.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import '../../../../BuilderField/shared/utils/entity_field_store.dart';
import 'package:flutter/material.dart';
import '../Rides_Repo/Rides_repo_screen.dart';

class RidesViewModelScreen extends ChangeNotifier{
  final RidesRepoScreen repo = RidesRepoScreen();

 
  // State variables
  List<Map<String, dynamic>> _ridesList = [];
  List<Map<String, dynamic>> _filteredList = [];
  bool _isLoading = false;
  String _errorMessage = '';
  int _currentPage = 0;
  int _pageSize = 10;
  bool _hasMoreData = true;
  String _searchQuery = '';

  // Getters
  List<Map<String, dynamic>> get ridesList => _ridesList;
  List<Map<String, dynamic>> get filteredList => _filteredList;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  bool get hasMoreData => _hasMoreData;
  String get searchQuery => _searchQuery;

  // Set loading state
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  // Set error message
  void _setError(String error) {
    _errorMessage = error;
    notifyListeners();
  }

  // Clear error
  void clearError() {
    _errorMessage = '';
    notifyListeners();
  }

  // Get rides list
  Future<void> getEntities() async {
    _setLoading(true);
    _setError('');

    try {
      final response = await repo.getEntities();

      if (response.status == Status.SUCCESS) {
        _ridesList = response.data ?? [];
        _filteredList = List.from(_ridesList);
        _currentPage = 0;
        _hasMoreData = true;
      } else {
        _setError(response.message ?? 'Failed to fetch rides list');
      }
    } catch (e) {
      _setError('Failed to fetch rides list: $e');
    } finally {
      _setLoading(false);
    }
  }

  // Get rides list with pagination
  Future<void> getAllWithPagination({bool refresh = false}) async {
    if (refresh) {
      _currentPage = 0;
      _ridesList.clear();
      _filteredList.clear();
      _hasMoreData = true;
    }

    if (!_hasMoreData || _isLoading) return;

    _setLoading(true);
    _setError('');

    try {
      final response = await repo.getAllWithPagination(_currentPage, _pageSize);

      if (response.status == Status.SUCCESS) {
        final newItems = response.data ?? [];

        if (refresh) {
          _ridesList = newItems;
        } else {
          _ridesList.addAll(newItems);
        }

        _filteredList = List.from(_ridesList);
        _currentPage++;

        // Check if we have more data
        _hasMoreData = newItems.length == _pageSize;
      } else {
        _setError(response.message ?? 'Failed to fetch Rides list');
      }
    } catch (e) {
      _setError('Failed to fetch rides list: $e');
    } finally {
      _setLoading(false);
    }
  }



















  // Create Rides
  Future<bool> createEntity(Map<String, dynamic> entity) async {
    _setLoading(true);
    _setError('');

    try {


















      final response = await repo.createEntity(entity);

      if (response.status == Status.SUCCESS) {
// Get the response ID for image upload

        final responseId = response.data!['id'].toString();


















        ToastMessageUtil.showToast(
          message: 'rides created successfully',
          toastType: ToastType.success,
        );

        // Refresh the list
        await getEntities();


















        return true;
      } else {
        _setError(response.message ?? 'Failed to create Rides');
        ToastMessageUtil.showToast(
          message: response.message ?? 'Failed to create Rides',
          toastType: ToastType.error,
        );
        return false;
      }
    } catch (e) {
      _setError('Failed to create rides: $e');
      ToastMessageUtil.showToast(
        message: 'Failed to create Rides: $e',
        toastType: ToastType.error,
      );
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // Update rides
  Future<bool> updateEntity(int id, Map<String, dynamic> entity) async {
    _setLoading(true);
    _setError('');

    try {
      final response = await repo.updateEntity(id, entity);

      if (response.status == Status.SUCCESS) {
        ToastMessageUtil.showToast(
          message: 'Rides updated successfully',
          toastType: ToastType.success,
        );

        // Update the item in the list
        final index = _ridesList.indexWhere((item) => item['id'] == id);
        if (index != -1) {
          _ridesList[index] = response.data!;
          _filteredList = List.from(_ridesList);
          notifyListeners();
        }
        return true;
      } else {
        _setError(response.message ?? 'Failed to update Rides');
        ToastMessageUtil.showToast(
          message: response.message ?? 'Failed to update Rides',
          toastType: ToastType.error,
        );
        return false;
      }
    } catch (e) {
      _setError('Failed to update rides: $e');
      ToastMessageUtil.showToast(
        message: 'Failed to update Rides: $e',
        toastType: ToastType.error,
      );
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // Delete rides
  Future<bool> deleteEntity(int id) async {
    _setLoading(true);
    _setError('');

    try {
      final response = await repo.deleteEntity(id);

      if (response.status == Status.SUCCESS) {
        ToastMessageUtil.showToast(
          message: 'Rides deleted successfully',
          toastType: ToastType.success,
        );

        // Remove the item from the list
        _ridesList.removeWhere((item) => item['id'] == id);
        _filteredList = List.from(_ridesList);
        notifyListeners();
        return true;
      } else {
        _setError(response.message ?? 'Failed to delete Rides');
        ToastMessageUtil.showToast(
          message: response.message ?? 'Failed to delete Rides',
          toastType: ToastType.error,
        );
        return false;
      }
    } catch (e) {
      _setError('Failed to delete rides: $e');
      ToastMessageUtil.showToast(
        message: 'Failed to delete Rides: $e',
        toastType: ToastType.error,
      );
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // Search rides
  void searchrides(String query) {
    _searchQuery = query;

    if (query.isEmpty) {
      _filteredList = List.from(_ridesList);
    } else {
      _filteredList = _ridesList.where((item) {
        return

             
(item['name']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




             
(item['description']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||


(item['active']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




             
(item['pick_up']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||


(item['return_to_same_location']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




             
(item['return_address']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




             
(item['product']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




             
(item['vehicle_add_on']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||


(item['iscompleted']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) 


;
      }).toList();
    }
    notifyListeners();
  }

  // Clear search
  void clearSearch() {
    _searchQuery = '';
    _filteredList = List.from(_ridesList);
    notifyListeners();
  }

  // Refresh data
  Future<void> refreshData() async {
    await getAllWithPagination(refresh: true);
  }






List<Map<String, dynamic>> pick_upItems = [];

 Future<List<Map<String, dynamic>>>   getpick_up() async {

      try {
     final value = await repo.getpick_up();
        pick_upItems =  (value as List)
            .map((item) => item as Map<String, dynamic>)
            .toList();

   return pick_upItems;
    } catch (e) {
      throw Exception('Failed to get all: $e');
    }
  }



List<Map<String, dynamic>> return_addressItems = [];

 Future<List<Map<String, dynamic>>>   getreturn_address() async {

      try {
     final value = await repo.getreturn_address();
        return_addressItems =  (value as List)
            .map((item) => item as Map<String, dynamic>)
            .toList();

   return return_addressItems;
    } catch (e) {
      throw Exception('Failed to get all: $e');
    }
  }

List<Map<String, dynamic>> productItems = [];

 Future<List<Map<String, dynamic>>>   getproduct() async {

      try {
     final value = await repo.getproduct();
        productItems =  (value as List)
            .map((item) => item as Map<String, dynamic>)
            .toList();

   return productItems;
    } catch (e) {
      throw Exception('Failed to get all: $e');
    }
  }

List<Map<String, dynamic>> vehicle_add_onItems = [];

 Future<List<Map<String, dynamic>>>   getvehicle_add_on() async {

      try {
     final value = await repo.getvehicle_add_on();
        vehicle_add_onItems =  (value as List)
            .map((item) => item as Map<String, dynamic>)
            .toList();

   return vehicle_add_onItems;
    } catch (e) {
      throw Exception('Failed to get all: $e');
    }
  }



}