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 '../Custom_setting_Repo/Custom_setting_repo_screen.dart';

class Custom_settingViewModelScreen extends ChangeNotifier{
  final Custom_settingRepoScreen repo = Custom_settingRepoScreen();

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

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

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

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

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

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



















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

        // Refresh the list
        await getEntities();


















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

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

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

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

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

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

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

  // Search custom_setting
  void searchcustom_setting(String query) {
    _searchQuery = query;

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




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




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




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




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




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


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

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

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


















}