import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:proxibuy/presentation/providers/category/cubit/categories_children_cubit.dart';
import 'package:proxibuy/presentation/providers/category/cubit/categories_cubit.dart';
import 'package:proxibuy/presentation/ui/widgets/default_placeholder.dart';

ValueNotifier<String?> catId = ValueNotifier(null);

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

  @override
  State<CategoriesScreen> createState() => _CategoriesScreenState();
}

class _CategoriesScreenState extends State<CategoriesScreen> {
  final ScrollController _scrollController = ScrollController();
  StreamSubscription? _categoriesSubscription;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      context
          .read<CategoriesChildrenCubit>()
          .getAllChildCategories(catId.value ?? '');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: BlocBuilder<CategoriesCubit, CategoriesState>(
              builder: (context, state) {
                if (state is CategoriesLoaded) {
                  if (state.categories.isEmpty) {
                    return Center(child: Text('Empty'));
                  }
                  return SingleChildScrollView(
                    child: Container(
                      color: Theme.of(context).colorScheme.surface,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          ListView.builder(
                            // controller: _scrollController,
                            itemCount: state.categories.length,
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            itemBuilder: (context, index) {
                              final category = state.categories[index];
                              return InkWell(
                                onTap: () {
                                  context
                                      .read<CategoriesChildrenCubit>()
                                      .resetPagination();
                                  setState(() {
                                    catId.value = category.id;
                                  });
                                  context
                                      .read<CategoriesChildrenCubit>()
                                      .getAllChildCategories(catId.value ?? '');
                                },
                                child: ValueListenableBuilder(
                                    valueListenable: catId,
                                    builder: (context, selectedId, _) {
                                      return Container(
                                        color: selectedId == category.id
                                            ? Theme.of(context)
                                                .scaffoldBackgroundColor
                                            : Theme.of(context)
                                                .colorScheme
                                                .surface,
                                        child: ListTile(
                                          leading: SvgPicture.network(
                                            '${category.url}',
                                            color: Theme.of(context)
                                                .colorScheme
                                                .onSurface,
                                            placeholderBuilder: (context) =>
                                                DefaultPlaceHolder(
                                                    child: Container(
                                              width: 24,
                                              height: 24,
                                              decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  color: Colors.white),
                                            )),
                                            errorBuilder: (context, error,
                                                    stackTrace) =>
                                                Icon(Icons.category_outlined),
                                          ),
                                          title: Text(category.name ?? ''),
                                        ),
                                      );
                                    }),
                              );
                            },
                          ),
                          if (state.isLoading) LinearProgressIndicator()
                        ],
                      ),
                    ),
                  );
                } else if (state is CategoriesChildrenError) {
                  return Center(child: Text(state.errorMessage!));
                } else {
                  return ListView.builder(
                    // controller: _scrollController,
                    itemCount: 20,
                    physics: NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return DefaultPlaceHolder(
                        child: Container(
                          margin: EdgeInsets.symmetric(vertical: 8),
                          color: Colors.white,
                          child: ListTile(
                            leading: Icon(Icons.abc_outlined),
                            title: Text(''),
                          ),
                        ),
                      );
                    },
                  );
                }
              },
            ),
          ),
          VerticalDivider(),
          Expanded(
            flex: 2,
            child:
                BlocBuilder<CategoriesChildrenCubit, CategoriesChildrenState>(
              builder: (context, state) {
                if (state is CategoriesChildrenLoaded) {
                  if (state.categories.isEmpty) {
                    return Center(child: Text('Empty'));
                  }
                  return SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: TextButton(
                              onPressed: () {},
                              child: Text(
                                'See all',
                                style: Theme.of(context)
                                    .textTheme
                                    .labelLarge
                                    ?.copyWith(
                                        color: Theme.of(context).primaryColor),
                              )),
                        ),
                        ListView.builder(
                          // controller: _scrollController,
                          itemCount: state.categories.length,
                          physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (context, index) {
                            if (index >= state.categories.length) {
                              return Center(child: CircularProgressIndicator());
                            }
                            final category = state.categories[index];
                            return ListTile(
                              leading: SvgPicture.network(
                                '${state.categories[index].url}',
                                color: Theme.of(context).colorScheme.onSurface,
                                placeholderBuilder: (context) =>
                                    DefaultPlaceHolder(
                                        child: Container(
                                  width: 24,
                                  height: 24,
                                  decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Colors.white),
                                )),
                                errorBuilder: (context, error, stackTrace) =>
                                    Icon(Icons.category_outlined),
                              ),
                              title: Text(category.name ?? ''),
                            );
                          },
                        ),
                        if (state.isLoading) LinearProgressIndicator()
                      ],
                    ),
                  );
                } else if (state is CategoriesChildrenError) {
                  return Center(child: Text(state.errorMessage!));
                } else {
                  return ListView.builder(
                    // controller: _scrollController,
                    itemCount: 20,
                    physics: NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return DefaultPlaceHolder(
                        child: Container(
                          margin: EdgeInsets.symmetric(vertical: 8),
                          color: Colors.white,
                          child: ListTile(
                            leading: Icon(Icons.abc_outlined),
                            title: Text(''),
                          ),
                        ),
                      );
                    },
                  );
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _categoriesSubscription?.cancel();
    super.dispose();
  }
}
