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 '../Vehicle_add_on_Repo/Vehicle_add_on_repo_screen.dart';

class Vehicle_add_onViewModelScreen extends ChangeNotifier{
  final Vehicle_add_onRepoScreen repo = Vehicle_add_onRepoScreen();

 
  // State variables
  List<Map<String, dynamic>> _vehicle_add_onList = [];
  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 vehicle_add_onList => _vehicle_add_onList;
  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 vehicle_add_on list
  Future<void> getEntities() async {
    _setLoading(true);
    _setError('');

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

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

  // Get vehicle_add_on list with pagination
  Future<void> getAllWithPagination({bool refresh = false}) async {
    if (refresh) {
      _currentPage = 0;
      _vehicle_add_onList.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) {
          _vehicle_add_onList = newItems;
        } else {
          _vehicle_add_onList.addAll(newItems);
        }

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

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













  // Create Vehicle_add_on
  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: 'vehicle_add_on created successfully',
          toastType: ToastType.success,
        );

        // Refresh the list
        await getEntities();












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

  // Update vehicle_add_on
  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: 'Vehicle_add_on updated successfully',
          toastType: ToastType.success,
        );

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

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

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

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

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

  // Search vehicle_add_on
  void searchvehicle_add_on(String query) {
    _searchQuery = query;

    if (query.isEmpty) {
      _filteredList = List.from(_vehicle_add_onList);
    } else {
      _filteredList = _vehicle_add_onList.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['icon']?.toString().toLowerCase().contains(query.toLowerCase()) ??false) ||




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




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


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

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

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












}