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 '../Products_Repo/Products_repo_screen.dart';

class ProductsViewModelScreen extends ChangeNotifier{
  final ProductsRepoScreen repo = ProductsRepoScreen();

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

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

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

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

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

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









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



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

    try {








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

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


      entity.remove('product_images');




      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 images if available
        if (_product_imagesimageFiles.isNotEmpty) {
          await _uploadproduct_images(responseId, _product_imagesimageFiles);
          _product_imagesimageFiles.clear(); // Clear after upload
        }



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

        // Refresh the list
        await getEntities();








        EntityFieldStore.instance.remove('product_images');




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

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

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

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

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

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

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

  // Search products
  void searchproducts(String query) {
    _searchQuery = query;

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






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


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

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

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






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

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

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

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



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

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

// Modify the uploadproduct_imagesimage function
  Future<void> uploadproduct_images(String ref, String refTableNmae,
      String selectedFilePath, Uint8List image_timageBytes) async {
    try {

      final Uint8List fileBytes = image_timageBytes!;
      final mimeType = product_imageslookupMimeType(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.product_imagesUpload(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 product_imageslookupMimeType(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
    }
  }

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

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

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

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

}