import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:provider/provider.dart' as pro;
import 'package:salespro_admin/generated/l10n.dart' as lang;

import '../../Provider/product_provider.dart';
import '../../model/product_model.dart';
import '../Widgets/Constant Data/constant.dart';
import '../currency/currency_provider.dart';

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

  @override
  State<DashboardStockWidget> createState() => _DashboardStockWidgetState();
}

class _DashboardStockWidgetState extends State<DashboardStockWidget> {
  final ScrollController _scrollController = ScrollController();

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

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    final currencyProvider = pro.Provider.of<CurrencyProvider>(context);
    final globalCurrency = currencyProvider.currency ?? '\$';

    return Consumer(
      builder: (_, ref, __) {
        final productAsync = ref.watch(productProvider);

        return productAsync.when(
          data: (products) {
            // Calculate totals
            double totalSaleValue = 0;
            double totalPurchaseValue = 0;
            int totalItems = 0;
            final lowStockItems = <ProductModel>[];

            for (final product in products) {
              final stock = int.tryParse(product.productStock) ?? 0;
              final salePrice = double.tryParse(product.productSalePrice) ?? 0;
              final purchasePrice = double.tryParse(product.productPurchasePrice) ?? 0;

              totalSaleValue += salePrice * stock;
              totalPurchaseValue += purchasePrice * stock;
              totalItems += stock;

              if (stock <= product.lowerStockAlert) {
                lowStockItems.add(product);
              }
            }

            return Container(
              height: 400,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0),
                color: whiteColor,
                boxShadow: [
                  BoxShadow(
                    color: kBorderColorTextField.withOpacity(0.7),
                    blurRadius: 4,
                    blurStyle: BlurStyle.inner,
                    spreadRadius: 1,
                    offset: const Offset(0, 1),
                  )
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Stock Value Section
                  Padding(
                    padding: const EdgeInsets.all(14.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          lang.S.of(context).lowStock,
                          style: textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.w600,
                            fontSize: 18,
                          ),
                        ),
                        // Low Stock Section
                        TextButton(
                          style: const ButtonStyle(
                            visualDensity: VisualDensity(horizontal: -4, vertical: -4),
                            padding: WidgetStatePropertyAll(EdgeInsets.zero),
                          ),
                          onPressed: () => context.go('/low-stock'),
                          child: Row(
                            children: [
                              Text(
                                lang.S.of(context).viewAll,
                                style: kTextStyle.copyWith(color: kMainColor),
                              ),
                              const Icon(
                                Icons.keyboard_arrow_right,
                                color: kMainColor,
                                size: 20,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  const Divider(
                    thickness: 1,
                    color: kNeutral300,
                    height: 1.0,
                  ),

                  // Low Stock List
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(16.0, 0.0, 16.0, 16.0),
                      child: Scrollbar(
                        controller: _scrollController,
                        thumbVisibility: true,
                        trackVisibility: true,
                        thickness: 4.0,
                        child: lowStockItems.isEmpty
                            ? Center(
                                child: Padding(
                                  padding: const EdgeInsets.all(16.0),
                                  child: Text(
                                    lang.S.of(context).stockIsMoreThenLowLimit,
                                    style: kTextStyle.copyWith(
                                      color: kGreyTextColor,
                                    ),
                                  ),
                                ),
                              )
                            : ListView.builder(
                                controller: _scrollController,
                                padding: EdgeInsets.zero,
                                itemCount: min(lowStockItems.length, 9),
                                itemBuilder: (context, index) {
                                  final product = lowStockItems[index];
                                  return Padding(
                                    padding: const EdgeInsets.symmetric(
                                      vertical: 8.0,
                                    ),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text(
                                          product.productName,
                                          style: textTheme.bodyMedium?.copyWith(
                                            color: kNeutral600,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                        Text(
                                          product.productStock,
                                          style: textTheme.bodyMedium?.copyWith(
                                            color: kErrorColor,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
          error: (error, stack) => Center(
            child: Text(
              e.toString(),
              style: kTextStyle.copyWith(color: kErrorColor),
            ),
          ),
          loading: () => const Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    );
  }
}
