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 '../Adv3_Repo/Adv3_repo_screen.dart';

class Adv3ViewModelScreen extends ChangeNotifier{
  final Adv3RepoScreen repo = Adv3RepoScreen();

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

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

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

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

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

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













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

        // Refresh the list
        await getEntities();












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

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

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

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

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

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

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

  // Search adv3
  void searchadv3(String query) {
    _searchQuery = query;

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

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






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




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




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




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


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

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

  // Refresh data
  Future<void> refreshData() async {
    await getAllWithPagination(refresh: true);
  }
  late List<Map<String, dynamic>> datagrid_fielddataFuture =
      []; // Data from fetchData

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

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

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







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

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

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

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

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

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

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

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

}