import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../../application/product/product_loader/product_loader_bloc.dart';
import '../../../../../../common/theme/theme.dart';
import '../../../../../../domain/category/category.dart';

class CategoryTabBar extends StatefulWidget {
  final List<Category> categories;
  final List<Widget> tabViews;
  const CategoryTabBar({
    super.key,
    required this.categories,
    required this.tabViews,
  });

  @override
  State<CategoryTabBar> createState() => _CategoryTabBarState();
}

class _CategoryTabBarState extends State<CategoryTabBar>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  String? selectedCategoryId;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: widget.categories.length,
      vsync: this,
    );

    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        if (_tabController.index == 0) {
          context.read<ProductLoaderBloc>().add(
            const ProductLoaderEvent.getProduct(),
          );
        } else {
          selectedCategoryId = widget.categories[_tabController.index].id;
          context.read<ProductLoaderBloc>().add(
            ProductLoaderEvent.getProduct(categoryId: selectedCategoryId),
          );
        }
      }
    });
  }

  @override
  void didUpdateWidget(CategoryTabBar oldWidget) {
    super.didUpdateWidget(oldWidget);

    // ✅ Update TabController when categories length changes
    if (oldWidget.categories.length != widget.categories.length) {
      _tabController.dispose();
      _tabController = TabController(
        length: widget.categories.length,
        vsync: this,
        initialIndex: 0, // Reset to first tab
      );

      _tabController.addListener(() {
        if (_tabController.indexIsChanging) {
          if (_tabController.index == 0) {
            context.read<ProductLoaderBloc>().add(
              const ProductLoaderEvent.getProduct(),
            );
          } else {
            selectedCategoryId = widget.categories[_tabController.index].id;
            context.read<ProductLoaderBloc>().add(
              ProductLoaderEvent.getProduct(categoryId: selectedCategoryId),
            );
          }
        }
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Material(
          elevation: 0,
          color: Colors.white,
          borderOnForeground: false,
          child: Padding(
            padding: const EdgeInsets.symmetric(vertical: 16),
            child: TabBar(
              controller: _tabController,
              isScrollable: true,
              tabAlignment: TabAlignment.start,
              labelColor: AppColor.primary,
              labelStyle: const TextStyle(fontWeight: FontWeight.bold),
              dividerColor: AppColor.primary,
              unselectedLabelColor: AppColor.primary,
              indicatorSize: TabBarIndicatorSize.label,
              indicatorWeight: 4,
              indicatorColor: AppColor.primary,
              tabs: widget.categories
                  .map(
                    (category) => Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Tab(text: category.name),
                    ),
                  )
                  .toList(),
            ),
          ),
        ),
        Expanded(
          // ✅ ini bagian penting
          child: TabBarView(
            controller: _tabController,
            children: widget.tabViews,
          ),
        ),
      ],
    );
  }
}
