import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/app_bar_with_tab.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/enums/stock_card_type.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/features/stock_check/domain/entities/selected_checked_item.dart';
import 'package:niogu_app/features/stock_check/presentation/providers/stock_check_provider.dart';
import 'package:niogu_app/features/stock_check/presentation/screens/product_stock_check_screen.dart';
import 'package:niogu_app/features/stock_check/presentation/screens/raw_material_stock_check_screen.dart';
import 'package:niogu_app/features/stock_check/presentation/widgets/stock_adjustmen_confirmation.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in.dart';
import 'package:niogu_app/features/stock_in/presentation/provider/stock_in_provider.dart';
import 'package:niogu_app/features/stock_in/presentation/widgets/summary_tag.dart';
import 'package:sizer/sizer.dart';
import 'package:niogu_app/core/constants/app_color.dart';

class StockCheckScreen extends ConsumerStatefulWidget {
  const StockCheckScreen({super.key});

  @override
  ConsumerState<StockCheckScreen> createState() => _StockCheckScreenState();
}

class _StockCheckScreenState extends ConsumerState<StockCheckScreen>
    with SingleTickerProviderStateMixin {
  final GlobalKey<ProductStockCheckScreenState> _productKey = GlobalKey();

  final GlobalKey<RawMaterialStockCheckScreenState> _rawMaterialKey =
      GlobalKey();

  late TabController _tabController;

  final FocusNode _searchFocusNode = FocusNode();

  Color _searchIconColor = Colors.grey;

  Timer? _debounce;

  int _tabIndex = 0;

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

    _tabController = TabController(length: 2, vsync: this);

    _tabController.addListener(_handleTabSelection);

    _searchFocusNode.addListener(() {
      setState(() {
        _searchIconColor = _searchFocusNode.hasFocus
            ? Colors.black
            : Colors.grey;
      });
    });
  }

  @override
  void dispose() {
    _searchFocusNode.dispose();
    _tabController.removeListener(_handleTabSelection);
    _tabController.dispose();
    _debounce?.cancel();
    super.dispose();
  }

  void _handleTabSelection() {
    if (_tabController.index != _tabIndex) {
      setState(() {
        _tabIndex = _tabController.index;
      });
    }
  }

  void _onSearchChanged(String value) {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(const Duration(milliseconds: 800), () {
      ref.read(itemSearchProvider.notifier).state = value;
    });
  }

  void _showConfirmDialog() {
    final selectedItemState = ref.read(selectedCheckedItemProvider);
    showDialog(
      context: context,
      builder: (_) => StockAdjustmenConfirmation(
        totalItems: selectedItemState.length,
        onCancel: () => context.pop(),
        onConfirm: () async {
          final selectedItems = selectedItemState.values.where((item) {
            return item.differenceType != DifferenceType.suitable &&
                item.quantity != item.remainingStock;
          }).toList();

          final selectedProducts = selectedItemState.values.where((item) {
            return item.itemType == ItemType.product_variant;
          }).toList();

          final selectedRawMaterials = selectedItemState.values.where((item) {
            return item.itemType == ItemType.raw_material;
          }).toList();

          final items = selectedItems.map((item) {
            final stockCardType = item.differenceType == DifferenceType.more
                ? StockCardType.adjustment_in
                : StockCardType.adjustment_out;

            final double updateStock = item.remainingStock + item.quantity;

            final double currentStock = updateStock;

            return UpdateStockItem(
              outletInventoryId: item.id,
              stockCardType: stockCardType,
              remainingStock: item.remainingStock,
              qtyChange: item.quantity,
              updateStock: updateStock,
              currentStock: currentStock,
              costPrice: item.costPrice,
              purchasePrice: item.purchasePrice,
              notes: item.note,
            );
          }).toList();

          try {
            await Future.delayed(const Duration(milliseconds: 400));

            await ref
                .read(stockCheckedControllerProvider.notifier)
                .updateStockItem(items);

            if (!mounted) return;

            CustomSnackbar.showSuccess(
              context,
              "Stok barang berhasil diperbarui",
            );

            if (selectedProducts.isNotEmpty) {
              _productKey.currentState?.clear();
            }

            if (selectedRawMaterials.isNotEmpty) {
              _rawMaterialKey.currentState?.clear();
            }

            ref.invalidate(selectedCheckedItemProvider);
          } catch (e, st) {
            LogMessage.log.e(e.toString(), error: e, stackTrace: st);
            CustomSnackbar.showError(context, "Ups, terjadi kesalahan");
          } finally {
            if (mounted) {
              context.pop();
            }
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final selectedItemState = ref.watch(selectedCheckedItemProvider).values;

        final selectedProducts = selectedItemState.where((item) {
          return item.itemType == ItemType.product_variant;
        }).toList();

        final int selectedProductCount = selectedProducts.length;

        final selectedRawMaterials = selectedItemState.where((item) {
          return item.itemType == ItemType.raw_material;
        }).toList();

        final int selectedRawMaterialCount = selectedRawMaterials.length;

        final stockCheckedControllerState = ref.watch(
          stockCheckedControllerProvider,
        );

        return PopScope(
          canPop: false,
          onPopInvokedWithResult: (didPop, result) {
            if (didPop) return;

            context.pop();
          },
          child: SafeArea(
            top: false,
            bottom: true,
            right: false,
            left: false,
            child: Scaffold(
              backgroundColor: const Color(0xFFF9FAFB),
              appBar: AppBarWithTab(
                hintText:
                    "Cari nama ${_tabIndex == 0 ? 'produk' : 'bahan baku'}...",
                searchIconColor: _searchIconColor,
                canPop: true,
                onPop: () => context.pop(),
                showNotifIcon: false,
                searchFocusNode: _searchFocusNode,
                tabController: _tabController,
                onTap: (value) {
                  setState(() {
                    _tabIndex = value;
                  });
                },
                onSearchChanged: (value) => _onSearchChanged(value),
                tabs: [
                  Tab(text: "Produk", height: 10.h),
                  Tab(text: "Bahan Baku", height: 10.h),
                ],
              ),
              body: TabBarView(
                controller: _tabController,
                children: [
                  ProductStockCheckScreen(key: _productKey),
                  RawMaterialStockCheckScreen(key: _rawMaterialKey),
                ],
              ),
              bottomNavigationBar: Container(
                padding: EdgeInsets.all(5.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 10,
                      offset: const Offset(0, -5),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "Barang Dicek:",
                          style: TextStyle(
                            color: Colors.grey[600],
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            SummaryTag(
                              text: "$selectedProductCount Produk",
                              color: Colors.blue,
                            ),

                            SizedBox(width: 2.w),
                            SummaryTag(
                              text: "$selectedRawMaterialCount Bahan Baku",
                              color: Colors.orange,
                            ),
                          ],
                        ),
                      ],
                    ),
                    SizedBox(height: 1.5.h),

                    SizedBox(
                      width: double.infinity,
                      height: 6.5.h,
                      child: ElevatedButton(
                        onPressed: stockCheckedControllerState.isLoading
                            ? null
                            : _tabIndex == 0 && selectedProducts.isEmpty
                            ? null
                            : _tabIndex == 1 && selectedRawMaterials.isEmpty
                            ? null
                            : _showConfirmDialog,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                          disabledBackgroundColor: Colors.grey[300],
                        ),
                        child: Text(
                          "Simpan Penyesuaian Stok",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: AppFontSize.medium.sp,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
