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/enums/item_type.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/screens/display_product_screen.dart';
import 'package:niogu_app/features/stock_in/presentation/screens/display_raw_material_screen.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';
import 'package:niogu_app/core/constants/app_font_size.dart';

class DisplayItemScreen extends ConsumerStatefulWidget {
  final SelectedItemType type;
  final VoidCallback? onPressed;

  const DisplayItemScreen({
    super.key,
    required this.type,
    required this.onPressed,
  });

  @override
  ConsumerState<DisplayItemScreen> createState() => _DisplayItemScreenState();
}

class _DisplayItemScreenState extends ConsumerState<DisplayItemScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  final FocusNode _searchFocusNode = FocusNode();

  Color _searchIconColor = Colors.grey;

  Timer? _debounce;

  int _tabIndex = 0;

  Map<String, SelectedItem> _initialItems = {};

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

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

    _tabController.addListener(_handleTabSelection);

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

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _initialItems = ref.read(selectedItemProvider(widget.type));
    });
  }

  @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;
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final selectedItemState = ref
            .watch(selectedItemProvider(widget.type))
            .values
            .where((item) {
              return item.type == widget.type;
            })
            .toList();

        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;

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

            context.pop();

            WidgetsBinding.instance.addPostFrameCallback((_) {
              ref
                  .read(selectedItemProvider(widget.type).notifier)
                  .restore(_initialItems);
            });
          },
          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: [
                  DisplayProductScreen(type: widget.type),
                  DisplayRawMaterialScreen(type: widget.type),
                ],
              ),

              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: [
                    if (selectedProductCount > 0 ||
                        selectedRawMaterialCount > 0)
                      Padding(
                        padding: EdgeInsets.only(bottom: 1.5.h),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            if (selectedProductCount > 0)
                              SummaryTag(
                                text: "$selectedProductCount Produk",
                                color: Colors.blue,
                              ),
                            if (selectedProductCount > 0 &&
                                selectedRawMaterialCount > 0)
                              SizedBox(width: 2.w),
                            if (selectedRawMaterialCount > 0)
                              SummaryTag(
                                text: "$selectedRawMaterialCount Bahan Baku",
                                color: Colors.orange,
                              ),
                          ],
                        ),
                      ),

                    SizedBox(
                      width: double.infinity,
                      height: 6.h,
                      child: ElevatedButton(
                        onPressed: selectedItemState.isEmpty
                            ? null
                            : () {
                                context.pop();
                                widget.onPressed?.call();
                              },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          disabledBackgroundColor: Colors.grey[300],
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(2.5.w),
                          ),
                          elevation: 0,
                        ),
                        child: Text(
                          "Pilih Barang (${selectedProductCount + selectedRawMaterialCount})",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: AppFontSize.medium.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
