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 '../../Provider/product_provider.dart';
import '../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../model/product_model.dart';

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

  @override
  State<LowStockReport> createState() => _LowStockReportState();
}

class _LowStockReportState extends State<LowStockReport> {
  String? productName;
  final NumberFormat myFormat = NumberFormat.decimalPattern('en_US');

  // Pagination state
  final ScrollController _scrollController = ScrollController();
  final 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(
          'Low Stock',
          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) {
                // ✅ Filter only low stock products
                List<ProductModel> lowStockProducts = product.where((p) {
                  final stock = num.tryParse(p.productStock) ?? 0;
                  return stock <= p.lowerStockAlert;
                }).toList();

                // ✅ Apply search filter if needed
                if (productName != null && productName!.isNotEmpty) {
                  lowStockProducts = lowStockProducts.where((p) {
                    return p.productName.toUpperCase().contains(productName!.toUpperCase());
                  }).toList();
                }

                // ✅ Take only currently visible items
                final displayedList = lowStockProducts.take(_currentMax).toList();

                return Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      TextFormField(
                        onChanged: (value) {
                          setState(() {
                            productName = value;
                            _currentMax = _itemsPerPage; // reset pagination
                          });
                        },
                        keyboardType: TextInputType.name,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(horizontal: 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: 20),
                      Expanded(
                        child: lowStockProducts.isNotEmpty
                            ? SingleChildScrollView(
                                controller: _scrollController,
                                scrollDirection: Axis.vertical,
                                child: SingleChildScrollView(
                                  scrollDirection: Axis.horizontal,
                                  child: DataTable(
                                    headingRowColor: WidgetStateColor.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,
                                        ),
                                      ),
                                      DataColumn(
                                        label: Text(
                                          lang.S.of(context).sales,
                                        ),
                                      ),
                                    ],
                                    rows: List.generate(
                                      displayedList.length,
                                      (index) {
                                        final item = displayedList[index];
                                        final stock = num.tryParse(item.productStock) ?? 0;
                                        return DataRow(
                                          cells: [
                                            DataCell(
                                              Text(
                                                item.productName,
                                                style: GoogleFonts.poppins(
                                                  color: Colors.red,
                                                  fontSize: 16.0,
                                                ),
                                              ),
                                            ),
                                            DataCell(
                                              Text(
                                                myFormat.format(stock),
                                                style: GoogleFonts.poppins(color: Colors.red),
                                              ),
                                            ),
                                            DataCell(
                                              Text(
                                                item.warehouseName,
                                                style: GoogleFonts.poppins(color: Colors.red),
                                              ),
                                            ),
                                            DataCell(
                                              Text(
                                                '$currency${myFormat.format(int.tryParse(item.productPurchasePrice) ?? 0)}',
                                                style: GoogleFonts.poppins(color: Colors.red),
                                              ),
                                            ),
                                            DataCell(
                                              Text(
                                                '$currency ${myFormat.format(int.tryParse(item.productSalePrice) ?? 0)}',
                                                style: GoogleFonts.poppins(color: Colors.red),
                                              ),
                                            ),
                                          ],
                                        );
                                      },
                                    ),
                                  ),
                                ),
                              )
                            : const Center(
                                child: Padding(
                                  padding: EdgeInsets.only(top: 60),
                                  child: EmptyScreenWidget(),
                                ),
                              ),
                      ),
                      if (_isLoadingMore)
                        const Padding(
                          padding: EdgeInsets.symmetric(vertical: 20),
                          child: CircularProgressIndicator(),
                        ),
                    ],
                  ),
                );
              },
              error: (e, stack) => Center(child: Text("Error: $e")),
              loading: () => const Center(child: CircularProgressIndicator()),
            ),
          );
        },
      ),
    );
  }
}
