import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../Provider/product_provider.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../model/product_model.dart';

class StockList extends StatefulWidget {
  const StockList({super.key});

  @override
  _StockListState createState() => _StockListState();
}

class _StockListState extends State<StockList> {
  num totalStock = 0;
  double totalSalePrice = 0;
  double totalParPrice = 0;
  String? productName;
  int count = 0;

  final NumberFormat myFormat = NumberFormat.decimalPattern('en_US');

  final ScrollController _scrollController = ScrollController();
  int _itemsPerPage = 10;
  int _currentMax = 10;
  bool _isLoadingMore = false;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent &&
          !_isLoadingMore) {
        _loadMore();
      }
    });
  }

  void _loadMore() {
    setState(() {
      _isLoadingMore = true;
    });

    Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        _currentMax += _itemsPerPage;
        _isLoadingMore = false;
      });
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: kMainColor,
      appBar: AppBar(
        title: Text(
          lang.S.of(context).currentStock,
          style: GoogleFonts.poppins(color: Colors.white),
        ),
        iconTheme: const IconThemeData(color: Colors.white),
        centerTitle: true,
        backgroundColor: kMainColor,
        elevation: 0.0,
      ),
      body: Consumer(builder: (context, ref, __) {
        final providerData = ref.watch(productProvider);

        return Container(
          alignment: Alignment.topCenter,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(30),
              topLeft: Radius.circular(30),
            ),
          ),
          child: providerData.when(
            data: (product) {
              if (count == 0) {
                count++;
                for (var element in product) {
                  totalStock += num.tryParse(element.productStock) ?? 0;
                  totalSalePrice += ((num.tryParse(element.productStock) ?? 0) *
                      element.productSalePrice.toInt());
                  totalParPrice += ((num.tryParse(element.productStock) ?? 0) *
                      element.productSalePrice.toInt());
                }
              }

              List<ProductModel> filteredProduct = product.where((element) {
                return productName == null ||
                    productName!.isEmpty ||
                    element.productName.toUpperCase().contains(productName!.toUpperCase());
              }).toList();

              final displayedList = filteredProduct.take(_currentMax).toList();

              return product.isNotEmpty
                  ? SingleChildScrollView(
                      controller: _scrollController,
                      child: Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Column(
                          children: [
                            _buildSummaryCard(context),
                            AppTextField(
                              textFieldType: TextFieldType.NAME,
                              onChanged: (value) {
                                setState(() {
                                  productName = value;
                                  _currentMax = _itemsPerPage;
                                });
                              },
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.only(left: 8.0, right: 8.0),
                                floatingLabelBehavior: FloatingLabelBehavior.never,
                                labelText: lang.S.of(context).productName,
                                hintText: lang.S.of(context).enterProductName,
                                prefixIcon: const Icon(Icons.search),
                                border: const OutlineInputBorder(),
                              ),
                            ),
                            const SizedBox(height: 10),
                            displayedList.isNotEmpty
                                ? SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: DataTable(
                                      headingRowColor: MaterialStateColor.resolveWith(
                                          (states) => kMainColor.withValues(alpha: 0.2)),
                                      border: TableBorder.all(
                                          color: kBorderColorTextField, width: 0.5),
                                      columns: <DataColumn>[
                                        DataColumn(
                                          label: Text(
                                            lang.S.of(context).product,
                                          ),
                                        ),
                                        DataColumn(
                                          label: Text(
                                            lang.S.of(context).qty,
                                          ),
                                        ),
                                        DataColumn(
                                          label: Text(
                                            lang.S.of(context).warehouse,
                                          ),
                                        ),
                                        DataColumn(
                                          label: Text(
                                            lang.S.of(context).purchase,
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 2,
                                          ),
                                        ),
                                        DataColumn(
                                          label: Text(
                                            lang.S.of(context).sales,
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 2,
                                          ),
                                        ),
                                      ],
                                      rows: List.generate(
                                        displayedList.length,
                                        (index) {
                                          final item = displayedList[index];
                                          final stock = num.tryParse(item.productStock) ?? 0;
                                          final isLowStock = stock <= item.lowerStockAlert;

                                          return DataRow(
                                            cells: [
                                              DataCell(Text(
                                                item.productName,
                                                style: GoogleFonts.poppins(
                                                  color: isLowStock ? Colors.red : Colors.black,
                                                  fontSize: 16.0,
                                                ),
                                              )),
                                              DataCell(Text(
                                                myFormat.format(stock),
                                                style: GoogleFonts.poppins(
                                                  color: isLowStock ? Colors.red : Colors.black,
                                                ),
                                              )),
                                              DataCell(Text(
                                                item.warehouseName,
                                                style: GoogleFonts.poppins(
                                                  color: isLowStock ? Colors.red : Colors.black,
                                                ),
                                              )),
                                              DataCell(Text(
                                                '$currency${myFormat.format(int.tryParse(item.productPurchasePrice) ?? 0)}',
                                                style: GoogleFonts.poppins(
                                                  color: isLowStock ? Colors.red : Colors.black,
                                                ),
                                              )),
                                              DataCell(Text(
                                                '$currency ${myFormat.format(int.tryParse(item.productSalePrice) ?? 0)}',
                                                style: GoogleFonts.poppins(
                                                  color: isLowStock ? Colors.red : Colors.black,
                                                ),
                                              )),
                                            ],
                                          );
                                        },
                                      ),
                                    ),
                                  )
                                : const Padding(
                                    padding: EdgeInsets.only(top: 60),
                                    child: EmptyScreenWidget(),
                                  ),
                            if (_isLoadingMore)
                              const Padding(
                                padding: EdgeInsets.symmetric(vertical: 20),
                                child: CircularProgressIndicator(),
                              ),
                          ],
                        ),
                      ),
                    )
                  : const Center(
                      child: Padding(
                        padding: EdgeInsets.only(top: 60),
                        child: EmptyScreenWidget(),
                      ),
                    );
            },
            error: (e, _) => Center(child: Text(e.toString())),
            loading: () => const Center(child: CircularProgressIndicator()),
          ),
        );
      }),
    );
  }

  Widget _buildSummaryCard(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Container(
        height: 100,
        width: double.infinity,
        decoration: BoxDecoration(
          color: kMainColor.withValues(alpha: 0.1),
          border: Border.all(width: 1, color: kMainColor),
          borderRadius: const BorderRadius.all(Radius.circular(15)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _summaryItem(myFormat.format(totalStock), lang.S.of(context).totalStock,
                color: Colors.green),
            Container(width: 1, height: 60, color: kMainColor),
            _summaryItem(
                '$currency ${myFormat.format(totalParPrice)}', lang.S.of(context).totalPrice,
                color: Colors.orange),
          ],
        ),
      ),
    );
  }

  Widget _summaryItem(String value, String label, {Color? color}) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          value,
          style: TextStyle(color: color, fontSize: 20),
        ),
        const SizedBox(height: 10),
        Text(
          label,
          style: const TextStyle(color: Colors.black, fontSize: 16),
        ),
      ],
    );
  }
}

// class StockList extends StatefulWidget {
//   const StockList({super.key});
//
//   @override
//   // ignore: library_private_types_in_public_api
//   _StockListState createState() => _StockListState();
// }
//
// class _StockListState extends State<StockList> {
//   num totalStock = 0;
//   double totalSalePrice = 0;
//   double totalParPrice = 0;
//   String? productName;
//   int count = 0;
//
//   @override
//   void initState() {
//     super.initState();
//   }
//
//   NumberFormat decimalFormat = NumberFormat.decimalPattern('en_US');
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       backgroundColor: kMainColor,
//       appBar: AppBar(
//         title: Text(
//           lang.S.of(context).currentStock,
//           style: GoogleFonts.poppins(
//             color: Colors.white,
//           ),
//         ),
//         iconTheme: const IconThemeData(color: Colors.white),
//         centerTitle: true,
//         backgroundColor: kMainColor,
//         elevation: 0.0,
//       ),
//       body: Consumer(builder: (context, ref, __) {
//         final providerData = ref.watch(productProvider);
//         final wareHouseList = ref.watch(warehouseProvider);
//         return Container(
//           alignment: Alignment.topCenter,
//           decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30))),
//           child: SingleChildScrollView(
//             child: Padding(
//               padding: const EdgeInsets.all(10.0),
//               child: Column(
//                 children: [
//                   Column(
//                     children: [
//                       providerData.when(data: (product) {
//                         if (count == 0) {
//                           count++;
//                           for (var element in product) {
//                             totalStock = totalStock + (num.tryParse(element.productStock) ?? 0);
//                             totalSalePrice = totalSalePrice + ((num.tryParse(element.productStock) ?? 0) * element.productSalePrice.toInt());
//                             totalParPrice = totalParPrice + ((num.tryParse(element.productStock) ?? 0) * element.productSalePrice.toInt());
//                           }
//                         }
//                         List<ProductModel> filteredProduct = product.where((element) {
//                           return productName == null || productName!.isEmpty || element.productName.toUpperCase().contains(productName!.toUpperCase());
//                         }).toList();
//                         return product.isNotEmpty
//                             ? Column(
//                                 children: [
//                                   Padding(
//                                     padding: const EdgeInsets.all(20.0),
//                                     child: Container(
//                                       height: 100,
//                                       width: double.infinity,
//                                       decoration: BoxDecoration(
//                                           color: kMainColor.withValues(alpha: 0.1),
//                                           border: Border.all(width: 1, color: kMainColor),
//                                           borderRadius: const BorderRadius.all(Radius.circular(15))),
//                                       child: Row(
//                                         mainAxisAlignment: MainAxisAlignment.spaceAround,
//                                         children: [
//                                           Column(
//                                             mainAxisAlignment: MainAxisAlignment.center,
//                                             crossAxisAlignment: CrossAxisAlignment.center,
//                                             children: [
//                                               Text(
//                                                 myFormat.format(totalStock),
//                                                 style: const TextStyle(
//                                                   color: Colors.green,
//                                                   fontSize: 20,
//                                                 ),
//                                               ),
//                                               const SizedBox(height: 10),
//                                               Text(
//                                                 lang.S.of(context).totalStock,
//                                                 style: const TextStyle(
//                                                   color: Colors.black,
//                                                   fontSize: 16,
//                                                 ),
//                                               ),
//                                             ],
//                                           ),
//                                           Container(
//                                             width: 1,
//                                             height: 60,
//                                             color: kMainColor,
//                                           ),
//                                           Column(
//                                             mainAxisAlignment: MainAxisAlignment.center,
//                                             crossAxisAlignment: CrossAxisAlignment.center,
//                                             children: [
//                                               Text(
//                                                 '$currency ${myFormat.format(totalParPrice)}',
//                                                 style: const TextStyle(
//                                                   color: Colors.orange,
//                                                   fontSize: 20,
//                                                 ),
//                                               ),
//                                               const SizedBox(height: 10),
//                                               Text(
//                                                 lang.S.of(context).totalPrice,
//                                                 style: const TextStyle(
//                                                   color: Colors.black,
//                                                   fontSize: 16,
//                                                 ),
//                                               ),
//                                             ],
//                                           ),
//                                         ],
//                                       ),
//                                     ),
//                                   ),
//                                   AppTextField(
//                                     textFieldType: TextFieldType.NAME,
//                                     onChanged: (value) {
//                                       setState(() {
//                                         productName = value;
//                                       });
//                                     },
//                                     decoration: InputDecoration(
//                                       contentPadding: const EdgeInsets.only(left: 8.0, right: 8.0),
//                                       floatingLabelBehavior: FloatingLabelBehavior.never,
//                                       labelText: lang.S.of(context).productName,
//                                       hintText: lang.S.of(context).enterProductName,
//                                       prefixIcon: const Icon(Icons.search),
//                                       border: const OutlineInputBorder(),
//                                     ),
//                                   ),
//                                   const SizedBox(height: 10),
//                                   filteredProduct.isNotEmpty
//                                       ? SingleChildScrollView(
//                                           scrollDirection: Axis.horizontal,
//                                           child: DataTable(
//                                             headingRowColor: MaterialStateColor.resolveWith((states) => kMainColor.withValues(alpha: 0.2)),
//                                             border: TableBorder.all(color: kBorderColorTextField, width: 0.5),
//                                             columns: <DataColumn>[
//                                               DataColumn(
//                                                 label: Text(
//                                                   lang.S.of(context).product,
//                                                 ),
//                                               ),
//                                               DataColumn(
//                                                 label: Text(
//                                                   lang.S.of(context).qty,
//                                                 ),
//                                               ),
//                                               DataColumn(
//                                                 label: Text(
//                                                   lang.S.of(context).warehouse,
//                                                   //'Warehouse',
//                                                 ),
//                                               ),
//                                               DataColumn(
//                                                 label: Text(
//                                                   lang.S.of(context).purchase,
//                                                   overflow: TextOverflow.ellipsis,
//                                                   maxLines: 2,
//                                                 ),
//                                               ),
//                                               DataColumn(
//                                                 label: Text(
//                                                   lang.S.of(context).sales,
//                                                   overflow: TextOverflow.ellipsis,
//                                                   maxLines: 2,
//                                                 ),
//                                               ),
//                                             ],
//                                             rows: List.generate(
//                                               product.length,
//                                               (index) => DataRow(
//                                                 cells: [
//                                                   DataCell(Padding(
//                                                     padding: product.last == product[index] ? const EdgeInsets.only(top: 4) : const EdgeInsets.only(top: 4),
//                                                     child: Text(
//                                                       product[index].productName,
//                                                       textAlign: TextAlign.start,
//                                                       style: GoogleFonts.poppins(
//                                                         color: (num.tryParse(product[index].productStock) ?? 0) <= product[index].lowerStockAlert ? Colors.red : Colors.black,
//                                                         fontSize: 16.0,
//                                                       ),
//                                                     ),
//                                                   )),
//                                                   DataCell(
//                                                     Text(
//                                                       myFormat.format(num.tryParse(product[index].productStock) ?? 0),
//                                                       style: GoogleFonts.poppins(
//                                                         color: (num.tryParse(product[index].productStock) ?? 0) <= product[index].lowerStockAlert ? Colors.red : Colors.black,
//                                                       ),
//                                                     ),
//                                                   ),
//                                                   DataCell(
//                                                     Text(
//                                                       product[index].warehouseName,
//                                                       style: GoogleFonts.poppins(
//                                                         color: (num.tryParse(product[index].productStock) ?? 0) <= product[index].lowerStockAlert ? Colors.red : Colors.black,
//                                                       ),
//                                                     ),
//                                                   ),
//                                                   DataCell(
//                                                     Text(
//                                                       '$currency${myFormat.format(int.tryParse(product[index].productPurchasePrice) ?? 0)}',
//                                                       style: GoogleFonts.poppins(
//                                                         color: (num.tryParse(product[index].productStock) ?? 0) <= product[index].lowerStockAlert ? Colors.red : Colors.black,
//                                                       ),
//                                                     ),
//                                                   ),
//                                                   DataCell(Text(
//                                                     '$currency ${myFormat.format(int.tryParse(product[index].productSalePrice) ?? 0)}',
//                                                     style: GoogleFonts.poppins(
//                                                       color: (num.tryParse(product[index].productStock) ?? 0) <= product[index].lowerStockAlert ? Colors.red : Colors.black,
//                                                     ),
//                                                   )),
//                                                 ],
//                                               ),
//                                             ),
//                                           ),
//                                         )
//                                       : const Center(
//                                           child: Padding(
//                                             padding: EdgeInsets.only(top: 60),
//                                             child: EmptyScreenWidget(),
//                                           ),
//                                         ),
//                                 ],
//                               )
//                             : const Center(
//                                 child: Padding(
//                                 padding: EdgeInsets.only(top: 60),
//                                 child: EmptyScreenWidget(),
//                               ));
//                       }, error: (e, stack) {
//                         return Text(e.toString());
//                       }, loading: () {
//                         return const Center(child: CircularProgressIndicator());
//                       }),
//                     ],
//                   ),
//                 ],
//               ),
//             ),
//           ),
//         );
//       }),
//     );
//   }
// }
