import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import '../../Components/locale/l10n/app_locale.dart';
import '../../main.dart';
import '../../presentation/home_page/bloc/hero_list_bloc.dart';
import '../../widgets/hero_card.dart';
import '../../presentation/home_page/bloc/hero_search_bloc.dart';

class HeroListScreen extends StatelessWidget {
  const HeroListScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final locale = AppLocale.of(context)!; // Получаем текущую локализацию

    return Scaffold(
      appBar: AppBar(
        title: Text(locale.heroListTitle),
        actions: [
          IconButton(
            icon: const Icon(Icons.language),
            onPressed: () {
              // Переключение локали
              context.read<LocaleNotifier>().toggleLocale();
            },
          ),
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              onChanged: (query) {
                // Обновляем поиск при вводе текста
                context.read<HeroSearchBloc>().add(SearchHeroes(query));
              },
              decoration: InputDecoration(
                hintText: locale.search,
                prefixIcon: const Icon(Icons.search),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
        ),
      ),
      body: BlocBuilder<HeroSearchBloc, HeroSearchState>(
        builder: (context, searchState) {
          if (searchState is HeroSearchLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (searchState is HeroSearchLoaded) {
            return RefreshIndicator(
              onRefresh: () async {
                // Обновляем список героев
                context.read<HeroListBloc>().add(FetchHeroes());
              },
              child: ListView.builder(
                itemCount: searchState.heroes.length,
                itemBuilder: (context, index) {
                  return HeroCard(hero: searchState.heroes[index]);
                },
              ),
            );
          } else if (searchState is HeroSearchError) {
            return Center(child: Text('Error: ${searchState.message}'));
          } else if (searchState is HeroSearchInitial) {
            return BlocBuilder<HeroListBloc, HeroListState>(
              builder: (context, listState) {
                if (listState is HeroListLoading) {
                  return const Center(child: CircularProgressIndicator());
                } else if (listState is HeroListLoaded) {
                  return RefreshIndicator(
                    onRefresh: () async {
                      // Выполняем новый запрос к API
                      context.read<HeroListBloc>().add(FetchHeroes());
                    },
                    child: ListView.builder(
                      itemCount: listState.heroes.length,
                      itemBuilder: (context, index) {
                        return HeroCard(hero: listState.heroes[index]);
                      },
                    ),
                  );
                } else if (listState is HeroListError) {
                  return Center(child: Text('Error: ${listState.message}'));
                }
                return Center(child: Text(locale.noHeroesAvailable));
              },
            );
          }
          return Center(child: Text(locale.noHeroesFound));
        },
      ),
    );
  }
}
