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 '../Basicp2_Repo/Basicp2_repo_screen.dart';

class Basicp2ViewModelScreen extends ChangeNotifier{
  final Basicp2RepoScreen repo = Basicp2RepoScreen();

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

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

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

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

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

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



















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

        // Refresh the list
        await getEntities();


















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

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

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

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

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

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

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

  // Search basicp2
  void searchbasicp2(String query) {
    _searchQuery = query;

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

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




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




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




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




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




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




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




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




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

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

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


















}