import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gap/gap.dart';
import 'package:tanami_app/core/styles/app_color.dart';
import 'package:tanami_app/features/countrySelection/bloc/GetCountry/get_country_bloc.dart';
import 'package:tanami_app/features/countrySelection/bloc/GetCountry/get_country_event.dart';
import 'package:tanami_app/shared/components/text_widget.dart';

import '../../../../shared/api/api_endpoints.dart';
import '../../bloc/GetCountry/get_country_state.dart';
import '../../bloc/choose_country_bloc.dart';
import '../../bloc/choose_country_event.dart';
import '../../bloc/choose_country_state.dart';

class CountrySelectionList extends StatelessWidget {
  const CountrySelectionList({super.key});

  @override
  Widget build(BuildContext context) {
    final radioBloc = context.read<RadioBloc>();

    return BlocBuilder<RadioBloc, RadioState>(
      builder: (context, state) {
        int selectedIndex = -1;
        if (state is RadioSelectionChanged) {
          selectedIndex = state.selectedIndex;
        }

        return BlocConsumer<GetCountryBlock, GetCountryState>(
            listener: (context, state) {
          if (state is CountryLoaded) {
            const SnackBar(content: Text("Successfully fetch"));
          } else if (state is CountryError) {
            const SnackBar(content: Text("error while fetching data"));
            Future.delayed(const Duration(milliseconds: 3), () {
              context.read<GetCountryBlock>().add(GetCountry());
            });
          } else {
            const SnackBar(content: Text("not fetch"));
          }
        }, builder: (context, state) {
          if (state is CountryLoading) {
            return const Center(
                child: CircularProgressIndicator(
              color: AppColor.primaryColor,
            ));
          } else if (state is CountryLoaded) {
            return ListView.builder(
              itemCount: state.countryModel.data?.length ?? 0,
              itemBuilder: (context, index) {
                var country = state.countryModel.data![index];

                return ListTile(
                  title: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(
                        height: 24.h,
                        width: 24.w,
                        child: ClipRRect(
                          borderRadius:
                              const BorderRadius.all(Radius.circular(100)),
                          child: CachedNetworkImage(
                              maxHeightDiskCache: 200,
                              maxWidthDiskCache: 200,
                              cacheKey: country.countryName,
                              key: UniqueKey(),
                              imageUrl:
                                  "${ApiEndpoints.base}${country.flagIcon}",
                              height: 24.h,
                              width: 24.w,
                              placeholder: (context, url) => SizedBox(
                                    height: 24.h,
                                    width: 24.w,
                                    child: const CircularProgressIndicator(),
                                  ),
                              errorWidget: (context, url, error) =>
                                  const Icon(Icons.error),
                              fit: BoxFit.cover),
                        ),
                      ),
                      /* Image.asset(
                        countryFlag[index],
                        width: 24,
                        height: 24,
                      ), */
                      const Gap(10),
                      TextWidget().text14W500(country.countryName.toString(),
                          clr: AppColor.charcoalColor),
                    ],
                  ),
                  leading: Radio<int>(
                    activeColor: AppColor.radioActiveColor,
                    value: index,
                    groupValue: selectedIndex,
                    onChanged: (int? value) {
                      if (value != null) {
                        radioBloc.add(RadioSelected(value));
                      }
                    },
                  ),
                );
              },
            );
          } else if (state is CountryError) {
            return Center(child: Text(state.message));
          } else {
            return const Center(
                child: Text('Press button to fetch country data'));
          }
        });
      },
    );
  }
}
