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_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/features/online_store/presentation/providers/online_store_provider.dart';
import 'package:niogu_app/features/online_store/presentation/screens/category_campaign_screen.dart';
import 'package:niogu_app/features/online_store/presentation/screens/product_campaign_screen.dart';
import 'package:sizer/sizer.dart';

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

  @override
  ConsumerState<LinkCampaignScreen> createState() => _LinkCampaignScreenState();
}

class _LinkCampaignScreenState extends ConsumerState<LinkCampaignScreen>
    with SingleTickerProviderStateMixin {
  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() {
    // 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(productCampaignSearchProvider.notifier).state = value;
      } else {
        ref.read(categoryCampaignSearchProvider.notifier).state = value;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final selectedCampaignItemState = ref.watch(
          selectedCampaignItemProvider,
        );
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: AppBarWithTab(
              hintText:
                  "Cari nama ${_tabIndex == 0 ? 'produk' : 'kategori'}...",
              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: "Kategori", height: 10.h),
              ],
            ),
            body: TabBarView(
              controller: _tabController,
              children: const [
                const ProductCampaignScreen(),
                const CategoryCampaignScreen(),
              ],
            ),
            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: ElevatedButton(
                onPressed: selectedCampaignItemState == null
                    ? null
                    : () => context.pop(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 6.5.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                  disabledBackgroundColor: Colors.grey[300],
                ),
                child: Text(
                  "Tautkan Sekarang",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.medium.sp,
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}
