import 'dart:developer';

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

import '../../../../../../application/category/category_loader/category_loader_bloc.dart';
import '../../../../../../application/product/product_loader/product_loader_bloc.dart';
import '../../../../../../common/theme/theme.dart';
import '../../../../../../domain/category/category.dart';
import '../../../../../components/card/error_card.dart';
import '../../../../../components/card/product_card.dart';
import '../../../../../components/loader/loader_with_text.dart';
import 'category_tabbar.dart';
import 'home_title.dart';

class HomeLeftPanel extends StatefulWidget {
  const HomeLeftPanel({super.key});

  @override
  State<HomeLeftPanel> createState() => _HomeLeftPanelState();
}

class _HomeLeftPanelState extends State<HomeLeftPanel> {
  final searchController = TextEditingController();
  final ScrollController scrollController = ScrollController();
  String searchQuery = '';

  bool _handleScrollNotification(
    ScrollNotification notification,
    String? categoryId,
  ) {
    if (notification is ScrollEndNotification &&
        scrollController.position.extentAfter == 0) {
      log('📄 Loading more products...');
      context.read<ProductLoaderBloc>().add(
        const ProductLoaderEvent.loadMore(),
      );
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CategoryLoaderBloc, CategoryLoaderState>(
      builder: (context, state) {
        if (state.isLoadingMore) {
          return const Center(child: LoaderWithText());
        }
        return state.failureOptionCategory.fold(
          () => _buildContent(context, state.categories),
          (f) => f.maybeMap(
            orElse: () => ErrorCard(
              title: 'Error Kategori',
              message: 'Terjadi kesalahan saat memuat kategori',
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
            dynamicErrorMessage: (value) => ErrorCard(
              title: 'Error Kategori',
              message: value.erroMessage,
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
            localStorageError: (value) => ErrorCard(
              title: 'Error Kategori',
              message: value.erroMessage,
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
            serverError: (value) => ErrorCard(
              title: 'Error Kategori',
              message: 'Terjadi kesalahan saat memuat kategori',
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
            unexpectedError: (value) => ErrorCard(
              title: 'Error Kategori',
              message: 'Terjadi kesalahan saat memuat kategori',
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
            empty: (value) => ErrorCard(
              title: 'Error Kategori',
              message: 'Kategori kosong',
              onTap: () => context.read<CategoryLoaderBloc>().add(
                const CategoryLoaderEvent.getCategories(),
              ),
            ),
          ),
        );
      },
    );
  }

  Column _buildContent(BuildContext context, List<Category> categories) {
    return Column(
      children: [
        HomeTitle(
          controller: searchController,
          onChanged: (value) {
            setState(() {
              searchQuery = value;
            });

            // Fast local search
            Future.delayed(const Duration(milliseconds: 200), () {
              if (value == searchController.text) {
                log('🔍 Local search: "$value"');
                context.read<ProductLoaderBloc>().add(
                  ProductLoaderEvent.searchProduct(query: value),
                );
              }
            });
          },
        ),
        Expanded(
          child: BlocBuilder<ProductLoaderBloc, ProductLoaderState>(
            builder: (context, state) {
              return CategoryTabBar(
                key: ValueKey(categories.length),
                categories: categories,
                tabViews: categories.map((category) {
                  return SizedBox(
                    child: state.failureOptionProduct.fold(
                      () => _buildProductGrid(
                        state.products,
                        state.hasReachedMax,
                        state.isLoadingMore,
                        state.categoryId,
                        state.page,
                      ),
                      (f) => f.maybeMap(
                        orElse: () => ErrorCard(
                          title: 'Error Produk',
                          message: 'Terjadi kesalahan saat memuat produk',
                          onTap: () => context.read<ProductLoaderBloc>().add(
                            const ProductLoaderEvent.getProduct(),
                          ),
                        ),
                      ),
                    ),
                  );
                }).toList(),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildProductGrid(
    List products,
    bool hasReachedMax,
    bool isLoadingMore,
    String? categoryId,
    int currentPage,
  ) {
    return Column(
      children: [
        if (products.isNotEmpty)
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 0,
            ).copyWith(bottom: 6),
            child: Row(
              children: [
                Text(
                  '${products.length} produk ditemukan',
                  style: AppStyle.sm.copyWith(color: AppColor.textSecondary),
                ),
                const Spacer(),
                if (isLoadingMore)
                  const SizedBox(
                    width: 12,
                    height: 12,
                    child: SpinKitFadingCircle(
                      color: AppColor.primary,
                      size: 12,
                    ),
                  ),
              ],
            ),
          ),

        Expanded(
          child: NotificationListener<ScrollNotification>(
            onNotification: (notification) =>
                _handleScrollNotification(notification, categoryId),
            child: GridView.builder(
              itemCount: products.length,
              controller: scrollController,
              padding: const EdgeInsets.all(16),
              cacheExtent: 200.0,
              gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 180,
                mainAxisSpacing: 30,
                crossAxisSpacing: 30,
                childAspectRatio: 180 / 240,
              ),
              itemBuilder: (context, index) =>
                  ProductCard(product: products[index]),
            ),
          ),
        ),

        if (hasReachedMax && products.isNotEmpty)
          Container(
            padding: const EdgeInsets.all(8),
            child: Text(
              'Semua produk telah dimuat',
              style: AppStyle.sm.copyWith(
                color: Colors.grey.shade500,
                fontSize: 11,
              ),
            ),
          ),
      ],
    );
  }
}
