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 '../Testbug_Repo/Testbug_repo_screen.dart';

class TestbugViewModelScreen extends ChangeNotifier{
  final TestbugRepoScreen repo = TestbugRepoScreen();

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

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

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

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

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

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



// Variable to store image files
  List<Map<String, dynamic>> _fileupload_fieldsFiles = [];

















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

    try {


  // Always source image selections from EntityFieldStore for simplicity
      final List<UploadItem> storefilefileupload_fields = EntityFieldStore.instance
              .get<List<UploadItem>>('fileupload_fields') ??
          <UploadItem>[];

      _fileupload_fieldsFiles = storefilefileupload_fields
          .map((u) => {'path': u.fileName, 'bytes': u.bytes})
          .toList();


      entity.remove('fileupload_fields');


















      final response = await repo.createEntity(entity);

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

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


// Upload File if available
        if (_fileupload_fieldsFiles.isNotEmpty) {
          await _uploadfileupload_fields(responseId, _fileupload_fieldsFiles);
          _fileupload_fieldsFiles.clear(); // Clear after upload
        }

















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

        // Refresh the list
        await getEntities();


        EntityFieldStore.instance.remove('fileupload_fields');


















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

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

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

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

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

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

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

  // Search testbug
  void searchtestbug(String query) {
    _searchQuery = query;

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

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





 


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

 

 


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

 




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






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




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




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




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





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


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

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

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







  // Helper method to upload multiple image files
  Future<void> _uploadfileupload_fields(
      String responseId, List<dynamic> Files) async {
    try {
      for (var File in Files) {
        if (File is Map<String, dynamic> &&
            File.containsKey('path')) {
          String filePath = File['path'];
          Uint8List fileBytes = File['bytes'];

          // Upload each image file
          await uploadfileupload_fields(
              responseId, 'Testbug', filePath, fileBytes);
        }
      }
    } catch (error) {
      print('Error uploading files: $error');
      ToastMessageUtil.showToast(
          message: "Failed to upload images", toastType: ToastType.error);
    }
  }

// Modify the uploadfileupload_fieldsimage function
  Future<void> uploadfileupload_fields(String ref, String refTableNmae,
      String selectedFilePath, Uint8List imageTimageBytes) async {
    try {

      final Uint8List fileBytes = imageTimageBytes!;
      final mimeType = fileupload_fieldslookupMimeType(selectedFilePath);

      FormData formData = FormData.fromMap({
        'file': MultipartFile.fromBytes(
          fileBytes,
          filename: selectedFilePath
              .split('/')
              .last, // Get the file name from the path
          contentType: MediaType.parse(mimeType!),
        ),
      });


      await repo.fileupload_fieldsUpload(ref, refTableNmae, formData).then((value) {
        ToastMessageUtil.showToast(
            message: "File uploaded successfully",
            toastType: ToastType.success);
      }).onError(
        (error, stackTrace) {
          print("error--$error");
          ToastMessageUtil.showToast(
              message: "Failed to upload file", toastType: ToastType.error);
        },
      );
    } catch (error) {
      print('Error occurred during form submission: $error');
    }
  }

// Modify the lookupMimeType function if needed
  String fileupload_fieldslookupMimeType(String filePath) {
    final ext = filePath.split('.').last;
    switch (ext) {
      case 'jpg':
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'pdf':
        return 'application/pdf';
      // Add more cases for other file types as needed
      default:
        return 'application/octet-stream'; // Default MIME type
    }
  }







  late List<Map<String, dynamic>> datagrid_fieldvdataFuture =
      []; // Data from fetchData

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}