import 'package:cheminova/controller/product_stock_service.dart';
import 'package:cheminova/controller/update_stock_controller.dart';
import 'package:cheminova/controller/update_stock_service.dart';
import 'package:cheminova/models/product_model.dart';
import 'package:cheminova/models/product_stock_model.dart';
import 'package:cheminova/screens/opening%20Inventory/inventory_management_screen.dart';
import 'package:cheminova/widgets/input_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../utils/show_snackbar.dart';

// class InventoryUpdateStockScreen extends StatefulWidget {
//   final ProductStockModel product;
//
//   const InventoryUpdateStockScreen({
//     super.key,
//     required this.product,
//   });
//
//   @override
//   State<InventoryUpdateStockScreen> createState() => _InventoryUpdateStockScreenState();
// }
//
// class _InventoryUpdateStockScreenState extends State<InventoryUpdateStockScreen> {
//   final _textController = TextEditingController();
//
//   final UpdateStockController _updateStockController = Get.put(UpdateStockController());
//
//   void _onUpdateStock() async {
//     try {
//       // Parse the new stock quantity from the text controller
//       int? newStockQuantity = int.tryParse(_textController.text.trim());
//
//       // Check if the parsed quantity is valid
//       if (newStockQuantity == null || newStockQuantity < 0) {
//         showSnackbar("Please enter a valid stock quantity.");
//         return;
//       }
//
//       // Create a list of ProductStockModel instances with updated stock
//       List<ProductStockModel> productStockList = [
//         ProductStockModel(
//           productid: widget.product.productid,
//           name: widget.product.name,
//           sku: widget.product.sku,
//           stock: newStockQuantity, // Update stock with new quantity
//         ),
//       ];
//
//       // Call the updateStock function
//       final update = await _updateStockController.updateProductStock(productStockList);
//
//       // Optionally, show a confirmation message or navigate to another screen
//       showSnackbar("Stock updated successfully");
//     } catch (e) {
//       print("Error updating stock: $e");
//       showSnackbar("Error updating stock. Please try again.");
//     }
//   }
//
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       extendBodyBehindAppBar: true,
//       appBar: AppBar(
//         centerTitle: true,
//         backgroundColor: Colors.transparent,
//         elevation: 0,
//         leading: GestureDetector(
//           onTap: () {},
//           child: Padding(
//             padding: const EdgeInsets.all(16.0),
//             child: SvgPicture.asset(
//               'assets/svg/menu.svg',
//             ),
//           ),
//         ),
//         actions: [
//           GestureDetector(
//             onTap: () => Get.back(),
//             child: Padding(
//               padding: const EdgeInsets.all(8.0),
//               child: SvgPicture.asset(
//                 'assets/svg/back_arrow.svg',
//               ),
//             ),
//           ),
//         ],
//         title: const Text(
//           "Update Inventory",
//         ),
//       ),
//       body: Stack(
//         fit: StackFit.expand,
//         children: [
//           Image.asset(
//             'assets/images/image_1.png',
//             fit: BoxFit.cover,
//           ),
//           SafeArea(
//             child: Column(
//               mainAxisAlignment: MainAxisAlignment.start,
//               children: [
//                 SizedBox(
//                   height: Get.height * 0.02,
//                 ),
//                 Card(
//                   margin: const EdgeInsets.symmetric(horizontal: 16),
//                   shape: RoundedRectangleBorder(
//                     borderRadius: BorderRadius.circular(19),
//                     side: const BorderSide(color: Color(0xFFFDFDFD)),
//                   ),
//                   color: const Color(0xFFB4D1E5).withOpacity(0.9),
//                   child: Padding(
//                     padding: const EdgeInsets.all(12.0),
//                     child: Column(
//                       mainAxisSize: MainAxisSize.min,
//                       crossAxisAlignment: CrossAxisAlignment.start,
//                       children: [
//
//                         Card(
//                           child: SizedBox(
//                             width: Get.width,
//                             child: Padding(
//                               padding: const EdgeInsets.all(12),
//                               child: Row(
//
//                                 children: [
//                                   Text(
//                                     "Product Name:",
//                                     style: GoogleFonts.roboto(
//                                       fontSize: Get.width * 0.04,
//                                       fontWeight: FontWeight.w700,
//                                     ),
//                                   ),
//                                   Text("${widget.product.name}"),
//                                 ],
//                               ),
//                             ),
//                           ),
//                         ),
//
//                         InputField(
//                           hintText: "Enter New Stock Quantity:",
//                           labelText: "Enter New Stock Quantity:",
//                           controller: _textController,
//                         ),
//                         // InputField(
//                         //   hintText: "Reason for Update: Restock",
//                         //   labelText: "Reason for Update: Restock",
//                         //   controller: _textController,
//                         // )
//                       ],
//                     ),
//                   ),
//                 ),
//                 SizedBox(height: Get.height * 0.04),
//                 SizedBox(
//                   width: Get.width * 0.9,
//                   height: Get.height * 0.06,
//                   child: ElevatedButton(
//                     onPressed: () {
//
//                       _onUpdateStock();
//                     },
//                     style: ElevatedButton.styleFrom(
//                       foregroundColor: Colors.white,
//                       backgroundColor: const Color(0xFF00784C),
//                       shape: RoundedRectangleBorder(
//                         borderRadius: BorderRadius.circular(10),
//                       ),
//                     ),
//                     child: Text(
//                       "Update Stock Quantity",
//                       style: GoogleFonts.roboto(
//                         fontSize: Get.width * 0.05,
//                         fontWeight: FontWeight.w600,
//                       ),
//                     ),
//                   ),
//                 ),
//               ],
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';

import '../../controller/update_stock_controller.dart';
import '../../models/product_stock_model.dart';
import 'package:flutter/material.dart';

import '../../utils/show_snackbar.dart';
import '../../widgets/input_field.dart';
import 'inventory_management_screen.dart';

class InventoryUpdateStockScreen extends StatefulWidget {
  final List<ProductStockModel> products;
  final String selectedProductId;

  const InventoryUpdateStockScreen({
    super.key,
    required this.products,
    required this.selectedProductId,
  });

  @override
  State<InventoryUpdateStockScreen> createState() => _InventoryUpdateStockScreenState();
}

class _InventoryUpdateStockScreenState extends State<InventoryUpdateStockScreen> {
  late TextEditingController _textController;
  final UpdateStockController _updateStockController = Get.put(UpdateStockController());

  @override
  void initState() {
    super.initState();
    // Initialize text controller with the stock of the selected product
    final selectedProduct = widget.products.firstWhere((product) => product.productid == widget.selectedProductId);
    _textController = TextEditingController(text: selectedProduct.stock.toString());
  }

  void _onUpdateStock() async {
    try {
      int? newStockQuantity = int.tryParse(_textController.text.trim());

      if (newStockQuantity == null || newStockQuantity < 0) {
        showSnackbar("Please enter a valid stock quantity.");
        return;
      }

      // Update only the stock for the selected product while keeping others the same
      List<ProductStockModel> updatedProductStockList = widget.products.map((product) {
        if (product.productid == widget.selectedProductId) {
          return ProductStockModel(
            productid: product.productid,
            name: product.name,
            sku: product.sku,
            stock: newStockQuantity,
            openingInventory: newStockQuantity,
          );
        } else {
          return product;
        }
      }).toList();

      // Call the updateStock function with the updated list
      final update = await _updateStockController.updateProductStock(updatedProductStockList);

      showSnackbar("Opening Inventory for ${widget.selectedProductId} updated successfully");
      Get.to(OpeningInventoryManagementScreen());
    } catch (e) {
      print("Error updating stock: $e");
      showSnackbar("Error updating stock. Please try again.");
    }
  }

  @override
  Widget build(BuildContext context) {
    final selectedProduct = widget.products.firstWhere((product) => product.productid == widget.selectedProductId);

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {},
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: SvgPicture.asset(
              'assets/svg/menu.svg',
            ),
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: SvgPicture.asset(
                'assets/svg/back_arrow.svg',
              ),
            ),
          ),
        ],
        title: const Text(
          "Update Inventory",
        ),
      ),
      body: Stack(
        fit: StackFit.expand,
        children: [
          Image.asset(
            'assets/images/image_1.png',
            fit: BoxFit.cover,
          ),
          SafeArea(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(height: Get.height * 0.02),
                Text(
                  "Product Name: ${selectedProduct.name}",
                  style: GoogleFonts.roboto(
                    fontSize: Get.width * 0.04,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                InputField(
                  hintText: "Enter New Opening Inventory Quantity:",
                  labelText: "Enter New Opening Inventory Quantity:",
                  controller: _textController,
                ),
                SizedBox(height: 8),
                ElevatedButton(
                  onPressed: _onUpdateStock,
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white,
                    backgroundColor: const Color(0xFF00784C),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  child: Text(
                    "Update Inventory Quantity",
                    style: GoogleFonts.roboto(
                      fontSize: Get.width * 0.05,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}