import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:responsive_grid/responsive_grid.dart';
import 'package:salespro_admin/Screen/currency/currency_provider.dart';
import 'package:salespro_admin/generated/l10n.dart' as lang;
import 'package:provider/provider.dart' as pro;
import '../../Provider/product_provider.dart';
import '../../commas.dart';
import '../../model/product_model.dart';
import '../Widgets/Constant Data/constant.dart';
import '../Widgets/Constant Data/export_button.dart';

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

  @override
  State<LowStockScreen> createState() => _LowStockScreenState();
}

class _LowStockScreenState extends State<LowStockScreen> {
  ScrollController mainScroll = ScrollController();
  String searchItem = '';
  final _horizontalScroll = ScrollController();
  int _stockReportPerPage = 10; // Default number of items to display
  int _currentPage = 1;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: kDarkWhite,
      body: SingleChildScrollView(
        child: Consumer(
          builder: (context, ref, __) {
            AsyncValue<List<ProductModel>> stockData = ref.watch(productProvider);
            final currencyProvider=pro.Provider.of<CurrencyProvider>(context);
            final globalCurrency=currencyProvider.currency ?? '\$';
            return stockData.when(data: (report) {
              // Filter only low stock products
              List<ProductModel> lowStockProducts = report.where((element) => int.parse(element.productStock) <= element.lowerStockAlert).toList();

              List<ProductModel> filteredProducts = [];
              for (var element in lowStockProducts) {
                if (element.productName.removeAllWhiteSpace().toLowerCase().contains(searchItem.removeAllWhiteSpace().toLowerCase())) {
                  filteredProducts.add(element);
                }
              }

              final pages = (filteredProducts.length / _stockReportPerPage).ceil();
              final startIndex = (_currentPage - 1) * _stockReportPerPage;
              final endIndex = _stockReportPerPage == -1 ? filteredProducts.length : startIndex + _stockReportPerPage;
              final paginatedList = filteredProducts.sublist(
                startIndex,
                endIndex > filteredProducts.length ? filteredProducts.length : endIndex,
              );

              return SingleChildScrollView(
                padding: EdgeInsets.all(10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: double.infinity,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.0),
                        color: kWhite,
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Text(
                              'Low Stock',
                              style: theme.textTheme.titleLarge?.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                          const Divider(
                            thickness: 1.0,
                            color: kNeutral300,
                            height: 1,
                          ),
                          ResponsiveGridRow(rowSegments: 100, children: [
                            ResponsiveGridCol(
                              xs: screenWidth < 360
                                  ? 45
                                  : screenWidth > 430
                                      ? 35
                                      : 40,
                              md: screenWidth < 768
                                  ? 24
                                  : screenWidth < 950
                                      ? 20
                                      : 15,
                              lg: screenWidth < 1700 ? 14 : 10,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: Container(
                                  alignment: Alignment.center,
                                  height: 48,
                                  padding: const EdgeInsets.all(6),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8.0),
                                    border: Border.all(color: kThemeOutlineColor),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Flexible(
                                          child: Text(
                                        'Show-',
                                        style: theme.textTheme.bodyLarge,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      )),
                                      DropdownButton<int>(
                                        isDense: true,
                                        padding: EdgeInsets.zero,
                                        underline: const SizedBox(),
                                        value: _stockReportPerPage,
                                        icon: const Icon(
                                          Icons.keyboard_arrow_down,
                                          color: Colors.black,
                                        ),
                                        items: [10, 20, 50, 100, -1].map<DropdownMenuItem<int>>((int value) {
                                          return DropdownMenuItem<int>(
                                            value: value,
                                            child: Text(
                                              value == -1 ? "All" : value.toString(),
                                              style: theme.textTheme.bodyLarge,
                                            ),
                                          );
                                        }).toList(),
                                        onChanged: (int? newValue) {
                                          setState(() {
                                            if (newValue == -1) {
                                              _stockReportPerPage = -1;
                                            } else {
                                              _stockReportPerPage = newValue ?? 10;
                                            }
                                            _currentPage = 1;
                                          });
                                        },
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            ResponsiveGridCol(
                              xs: 100,
                              md: 60,
                              lg: 35,
                              child: Padding(
                                padding: const EdgeInsets.all(10.0),
                                child: TextFormField(
                                  showCursor: true,
                                  cursorColor: kTitleColor,
                                  onChanged: (value) {
                                    setState(() {
                                      searchItem = value;
                                    });
                                  },
                                  keyboardType: TextInputType.name,
                                  decoration: InputDecoration(
                                    contentPadding: const EdgeInsets.all(10.0),
                                    hintText: (lang.S.of(context).searchByName),
                                    border: InputBorder.none,
                                    suffixIcon: const Icon(
                                      FeatherIcons.search,
                                      color: kTitleColor,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ]),
                          filteredProducts.isNotEmpty
                              ? Column(
                                  children: [
                                    LayoutBuilder(
                                      builder: (BuildContext context, BoxConstraints constraints) {
                                        return Scrollbar(
                                          controller: _horizontalScroll,
                                          thumbVisibility: true,
                                          radius: const Radius.circular(8),
                                          thickness: 8,
                                          child: SingleChildScrollView(
                                            scrollDirection: Axis.horizontal,
                                            controller: _horizontalScroll,
                                            child: Theme(
                                              data: ThemeData(
                                                dividerColor: kNeutral300,
                                                textTheme: theme.textTheme,
                                              ),
                                              child: ConstrainedBox(
                                                constraints: BoxConstraints(
                                                  minWidth: constraints.maxWidth,
                                                  minHeight: MediaQuery.of(context).size.height - 317,
                                                ),
                                                child: DataTable(
                                                  border: const TableBorder(
                                                    horizontalInside: BorderSide(
                                                      width: 1,
                                                      color: kNeutral300,
                                                    ),
                                                  ),
                                                  dataRowColor: const WidgetStatePropertyAll(Colors.white),
                                                  headingRowColor: WidgetStateProperty.all(const Color(0xFFF8F3FF)),
                                                  showBottomBorder: true,
                                                  dividerThickness: 1.0,
                                                  headingTextStyle: theme.textTheme.titleMedium,
                                                  columns: [
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).SL,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).PRODUCTNAME,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).CATEGORY,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).PRICE,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).QTY,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).warehouse,
                                                      ),
                                                    ),
                                                    DataColumn(
                                                      label: Text(
                                                        lang.S.of(context).TOTALVALUE,
                                                      ),
                                                    ),
                                                  ],
                                                  rows: List.generate(
                                                    paginatedList.length,
                                                    (index) {
                                                      final product = paginatedList[index];
                                                      final isLowStock = int.parse(product.productStock) <= product.lowerStockAlert;

                                                      return DataRow(
                                                        cells: [
                                                          DataCell(Text(
                                                            "${startIndex + index + 1}",
                                                          )),
                                                          DataCell(
                                                            Text(
                                                              product.productName,
                                                            ),
                                                          ),
                                                          DataCell(Text(
                                                            product.productCategory,
                                                          )),
                                                          DataCell(Text(
                                                            '$globalCurrency${myFormat.format(double.tryParse(product.productSalePrice) ?? 0)}',
                                                          )),
                                                          DataCell(
                                                            Text(
                                                              product.productStock,
                                                              style: theme.textTheme.bodyMedium?.copyWith(
                                                                color: kErrorColor,
                                                              ),
                                                            ),
                                                          ),
                                                          DataCell(Text(
                                                            product.warehouseName,
                                                          )),
                                                          DataCell(
                                                            Text(
                                                              '$globalCurrency${myFormat.format(double.tryParse((product.productSalePrice.toInt() * product.productStock.toInt()).toString()) ?? 0)}',
                                                            ),
                                                          ),
                                                        ],
                                                      );
                                                    },
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                        );
                                      },
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(10.0),
                                      child: Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Flexible(
                                            child: Text(
                                              '${lang.S.of(context).showing} ${((_currentPage - 1) * _stockReportPerPage + 1).toString()} to ${((_currentPage - 1) * _stockReportPerPage + _stockReportPerPage).clamp(0, filteredProducts.length)} of ${filteredProducts.length} entries',
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                          Row(
                                            children: [
                                              InkWell(
                                                overlayColor: WidgetStateProperty.all<Color>(Colors.grey),
                                                hoverColor: Colors.grey,
                                                onTap: _currentPage > 1 ? () => setState(() => _currentPage--) : null,
                                                child: Container(
                                                  height: 32,
                                                  width: 90,
                                                  decoration: BoxDecoration(
                                                    border: Border.all(color: kBorderColorTextField),
                                                    borderRadius: const BorderRadius.only(
                                                      bottomLeft: Radius.circular(4.0),
                                                      topLeft: Radius.circular(4.0),
                                                    ),
                                                  ),
                                                  child: Center(
                                                    child: Text(lang.S.of(context).previous),
                                                  ),
                                                ),
                                              ),
                                              Container(
                                                height: 32,
                                                width: 32,
                                                decoration: BoxDecoration(
                                                  border: Border.all(color: kBorderColorTextField),
                                                  color: kMainColor,
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    '$_currentPage',
                                                    style: const TextStyle(color: Colors.white),
                                                  ),
                                                ),
                                              ),
                                              Container(
                                                height: 32,
                                                width: 32,
                                                decoration: BoxDecoration(
                                                  border: Border.all(color: kBorderColorTextField),
                                                  color: Colors.transparent,
                                                ),
                                                child: Center(
                                                  child: Text(
                                                    '$pages',
                                                  ),
                                                ),
                                              ),
                                              InkWell(
                                                hoverColor: Colors.blue.withValues(alpha: 0.1),
                                                overlayColor: WidgetStateProperty.all<Color>(Colors.blue),
                                                onTap: _currentPage * _stockReportPerPage < filteredProducts.length ? () => setState(() => _currentPage++) : null,
                                                child: Container(
                                                  height: 32,
                                                  width: 90,
                                                  decoration: BoxDecoration(
                                                    border: Border.all(color: kBorderColorTextField),
                                                    borderRadius: const BorderRadius.only(
                                                      bottomRight: Radius.circular(4.0),
                                                      topRight: Radius.circular(4.0),
                                                    ),
                                                  ),
                                                  child: const Center(child: Text('Next')),
                                                ),
                                              ),
                                            ],
                                          )
                                        ],
                                      ),
                                    ),
                                  ],
                                )
                              : EmptyWidget(title: lang.S.of(context).noReportFound)
                        ],
                      ),
                    )
                  ],
                ),
              );
            }, error: (e, stack) {
              return Center(
                child: Text(e.toString()),
              );
            }, loading: () {
              return const Center(
                child: CircularProgressIndicator(),
              );
            });
          },
        ),
      ),
    );
  }
}
