import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:niogu_app/core/components/app_bar_with_tab.dart';
import 'package:niogu_app/features/report/stock_report/presentation/providers/stock_report_provider.dart';
import 'package:niogu_app/features/report/stock_report/presentation/screens/stock_report_screen.dart';
import 'package:niogu_app/features/report/transaction/presentation/providers/transaction_report_provider.dart';
import 'package:niogu_app/features/report/transaction/presentation/screens/transaction_report_screen.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<ReportScreen> createState() => _ReportScreenState();
}

class _ReportScreenState extends ConsumerState<ReportScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  final FocusNode _searchFocusNode = FocusNode();

  Color _searchIconColor = Colors.grey;

  Timer? _debounce;

  int _tabIndex = 0;

  @override
  void initState() {
    // TODO: implement 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() {
    // TODO: implement 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), () {
      if (_tabIndex == 0) {
        ref.read(transactionReportSearchProvider.notifier).state = value;
      } else {
        ref.read(stockReportSearchProvider.notifier).state = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            resizeToAvoidBottomInset: false,
            appBar: AppBarWithTab(
              hintText:
                  "Cari ${_tabIndex == 0 ? 'nomor transaksi' : 'nama barang'}...",
              searchIconColor: _searchIconColor,
              showSwitchOutlet: false,
              searchFocusNode: _searchFocusNode,
              tabController: _tabController,
              onTap: (value) {
                setState(() {
                  _tabIndex = value;
                });
              },
              onSearchChanged: (value) => _onSearchChanged(value),
              tabs: [
                Tab(text: "Transaksi", height: 10.h),
                Tab(text: "Arus Stok", height: 10.h),
              ],
            ),
            body: TabBarView(
              controller: _tabController,
              children: const [
                const TransactionReportScreen(),
                const StockReportScreen(),
              ],
            ),
          ),
        );
      },
    );
  }
}
