import 'package:first_project/Components/extensions/context_x.dart';
import 'package:first_project/data/repositories/anime_repository.dart';
import 'package:first_project/data/repositories/mock_repository.dart';
import 'package:first_project/domain/models/card.dart';
import 'package:first_project/presentation/common/svg_objects.dart';
import 'package:first_project/presentation/home_page/bloc/bloc.dart';
import 'package:first_project/presentation/home_page/bloc/events.dart';
import 'package:first_project/presentation/home_page/bloc/state.dart';
import 'package:first_project/presentation/like_bloc/like_bloc.dart';
import 'package:first_project/presentation/like_bloc/like_event.dart';
import 'package:first_project/presentation/like_bloc/like_state.dart';
import 'package:first_project/presentation/locale_bloc/locale_events.dart';
import 'package:first_project/presentation/locale_bloc/locale_state.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'package:first_project/Components/utils/debounce.dart';

import '../locale_bloc/locale_bloc.dart';

part 'card.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
          'Hello',
          style: Theme.of(context).textTheme.bodyMedium,
        ),
        backgroundColor: Colors.purple,
        duration: const Duration(seconds: 1),
      ));
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.purple,
        title: Text(widget.title),
      ),
      body: const _Body(),
    );
  }
}

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

  @override
  State<_Body> createState() => _BodyState();
}

class _BodyState extends State<_Body> {
  final searchController = TextEditingController();
  final scrollController = ScrollController();

  @override
  void initState() {
    SvgObjects.init();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<HomeBloc>().add(const HomeLoadDataEvent());
      context.read<LikeBloc>().add(const LoadLikesEvent());
    });

    scrollController.addListener(_onNextPageListener);

    super.initState();
  }

  void _onNextPageListener() {
    if (scrollController.offset >
        scrollController.position.maxScrollExtent - 50) {
      final bloc = context.read<HomeBloc>();
      if (!bloc.state.isPaginationLoading) {
        bloc.add(HomeLoadDataEvent(
          search: searchController.text,
          nextPage: bloc.state.data?.nextPage,
        ));
      }
    }
  }

  @override
  void dispose() {
    searchController.dispose();
    scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<HomeBloc, HomeState>(
        builder: (context, state) => state.error != null
            ? Text(
                state.error ?? '',
                style: Theme.of(context)
                    .textTheme
                    .headlineSmall
                    ?.copyWith(color: Colors.red),
              )
            : state.isLoading
                ? const CircularProgressIndicator()
                : Column(children: [
                    Row(children: [
                      Expanded(
                        flex: 4,
                        child: Padding(
                          padding: const EdgeInsets.all(8),
                          child: CupertinoSearchTextField(
                            controller: searchController,
                            placeholder: context.locale.search,
                            onChanged: (search) {
                              Debouce.run(() => context
                                  .read<HomeBloc>()
                                  .add(HomeLoadDataEvent(search: search)));
                            },
                          ),
                        ),
                      ),
                      GestureDetector(
                          onTap: () => context
                              .read<LocaleBloc>()
                              .add(const ChangeLocaleEvent()),
                          child: SizedBox.square(
                            dimension: 50,
                            child: Padding(
                              padding: const EdgeInsets.only(right: 15),
                              child: BlocBuilder<LocaleBloc, LocaleState>(
                                builder: (context, state) {
                                  return state.currentLocale.languageCode ==
                                          'ru'
                                      ? const SvgRu()
                                      : const SvgGb();
                                },
                              ),
                            ),
                          )),
                    ]),
                    BlocBuilder<LikeBloc, LikeState>(
                        builder: (context, likeState) {
                      return Expanded(
                        child: RefreshIndicator(
                          onRefresh: _onRefresh,
                          child: ListView.builder(
                              controller: scrollController,
                              padding: EdgeInsets.zero,
                              itemCount: state.data?.data?.length ?? 0,
                              itemBuilder: (context, index) {
                                final data = state.data?.data?[index];
                                return data != null
                                    ? _Card.fromData(
                                        data,
                                        isLiked: likeState.likedIds?.contains(data.id) == true,
                                        onLike: _onLike,
                                        onTap: () =>
                                            _navToDetails(context, data),
                                      )
                                    : const SizedBox.shrink();
                              }),
                        ),
                      );
                    }),
                    BlocBuilder<HomeBloc, HomeState>(
                      builder: (context, state) => state.isPaginationLoading
                          ? const CircularProgressIndicator()
                          : const SizedBox.shrink(),
                    )
                  ]));
  }

  void _navToDetails(BuildContext context, CardData data) {
    Navigator.push(
      context,
      CupertinoPageRoute(builder: (context) => DetailsPage(data)),
    );
  }

  void _onLike(String? id, String title, bool isLiked) {
    if (id != null)
      {
        context.read<LikeBloc>().add(ChangeLikeEvent(id));
        _showLiked(context, title, !isLiked);
      }
  }

  void _showLiked(BuildContext context, String title, bool isLiked) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
          '$title ${isLiked ? context.locale.liked : context.locale.disliked}',
          style: Theme.of(context).textTheme.bodyMedium,
        ),
        backgroundColor: Colors.purple,
        duration: const Duration(seconds: 1),
      ));
    });
  }

  Future<void> _onRefresh() {
    context
        .read<HomeBloc>()
        .add(HomeLoadDataEvent(search: searchController.text));
    return Future.value(null);
  }
}
