import 'package:app_popup_menu/app_popup_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:fluttericon/font_awesome_icons.dart';
import 'package:unit2/bloc/profile/profile_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/model/profile/eligibility.dart';
import 'package:unit2/screens/profile/components/eligibility/add_modal.dart';
import 'package:unit2/screens/profile/components/eligibility/edit_modal.dart';
import 'package:unit2/theme-data.dart/box_shadow.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/Leadings/close_leading.dart';
import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/error_state.dart';
import '../../../bloc/profile/eligibility/eligibility_bloc.dart';
import '../../../utils/alerts.dart';

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

  @override
  Widget build(BuildContext context) {
    String? token;
    int? profileId;

    return WillPopScope(
      onWillPop: () async {
        return true;
      },
      child: Scaffold(
        resizeToAvoidBottomInset: true,
          appBar: AppBar(
            title: context.watch<EligibilityBloc>().state is AddEligibilityState
                ? const Text("Add Eligiblity")
                : context.watch<EligibilityBloc>().state is EditEligibilityState
                    ? const Text("Edit Eligibilty")
                    : const Text(elibilityScreenTitle),
            centerTitle: true,
            backgroundColor: primary,
            actions: (context.watch<EligibilityBloc>().state is EligibilityLoaded)
            
                ? [
                    AddLeading(onPressed: () {
                      context
                          .read<EligibilityBloc>()
                          .add(ShowAddEligibilityForm());
                    })
                  ]
                :(context.watch<EligibilityBloc>().state is AddEligibilityState || context.watch<EligibilityBloc>().state is EditEligibilityState)? [
                    CloseLeading(onPressed: () {
                      context.read<EligibilityBloc>().add(const LoadEligibility());
                    })
                  ]:[],
          ),
          body: BlocBuilder<UserBloc, UserState>(
            builder: (context, state) {
              if (state is UserLoggedIn) {
                token = state.userData!.user!.login!.token;
                profileId =
                    state.userData!.user!.login!.user!.profileId;
                return BlocBuilder<ProfileBloc, ProfileState>(
                  builder: (context, state) {
                    if(state is ProfileLoaded){
                       return ProgressHUD(
                      padding: const EdgeInsets.all(24),
                      indicatorWidget: const SpinKitFadingCircle(
                        color: Colors.white,
                      ),
                      backgroundColor: Colors.black87,
                      child: BlocConsumer<EligibilityBloc, EligibilityState>(
                        listener: (context, state) {
                          if (state is EligibilityLoadingState) {
                            final progress = ProgressHUD.of(context);
                            progress!.showWithText("Please wait...");
                          }
                          if (state is EligibilityLoaded ||
                              state is AddEligibilityState ||
                              state is EditEligibilityState ||
                              state is DeletedState ||
                              state is EligibilityAddedState ||
                              state is EligibilityEditedState ||
                              state is EligibilityErrorState
                              ) {
                            final progress = ProgressHUD.of(context);
                            progress!.dismiss();
                          }
                          ////DELETED STATE
                          if (state is DeletedState) {
                            if (state.success) {
                              successAlert(context, "Deletion Successfull",
                                  "Eligibility has been deleted successfully",
                                  () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                                ));
                              });
                            } else {
                              errorAlert(context, "Deletion Failed",
                                  "Error deleting eligibility", () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                                  ));
                              });
                            }
                          }
                          ////ADDED STATE
                          if (state is EligibilityAddedState) {
                            if (state.response['success']) {
                              successAlert(context, "Adding Successfull!",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                                ));
                              });
                            } else {
                              errorAlert(context, "Adding Failed",
                                  "Something went wrong. Please try again.",
                                  () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                                 ));
                              });
                            }
                          }
                          ////UPDATED STATE
                          if (state is EligibilityEditedState) {
                            if (state.response['success']) {
                              successAlert(context, "Update Successfull!",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                       ));
                              });
                            } else {
                              errorAlert(context, "Update Failed",
                                  "Something went wrong. Please try again.",
                                  () {
                                Navigator.of(context).pop();
                                context.read<EligibilityBloc>().add(const LoadEligibility(
                      ));
                              });
                            }
                          }
                        },
                        builder: (context, state) {
                          return BlocBuilder<EligibilityBloc, EligibilityState>(
                            builder: (context, state) {
                              if (state is EligibilityLoaded) {
                               
                                if (state.eligibilities.isNotEmpty) {
                                  return ListView.builder(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 8, horizontal: 10),
                                      itemCount: state.eligibilities.length,
                                      itemBuilder:
                                          (BuildContext context, int index) {
                                        String title = state
                                            .eligibilities[index]
                                            .eligibility!
                                            .title;
                                        return Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.start,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Container(
                                              width: screenWidth,
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      horizontal: 12,
                                                      vertical: 8),
                                              decoration: box1(),
                                              child: Row(
                                                children: [
                                                  Expanded(
                                                    child: Column(
                                                        mainAxisAlignment:
                                                            MainAxisAlignment
                                                                .start,
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: [
                                                          Text(
                                                            title,
                                                            style: Theme.of(
                                                                    context)
                                                                .textTheme
                                                                .titleMedium!
                                                                .copyWith(
                                                                    fontWeight:
                                                                        FontWeight
                                                                            .w500,color: primary),
                                                          ),
                                                        
                                                          const SizedBox(
                                                            height: 5,
                                                          ),
                                                          Text(
                                                              "$licenseNumber: ${state.eligibilities[index].licenseNumber == null ? 'N/A' : state.eligibilities[index].licenseNumber.toString()}",
                                                              style: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .titleSmall),
                                                          const SizedBox(
                                                            height: 3,
                                                          ),
                                                          Text(
                                                              "Rating : ${state.eligibilities[index].rating ?? 'N/A'}.",
                                                              style: Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .titleSmall)
                                                        ]),
                                                  ),
                                                  AppPopupMenu<int>(
                                                    offset:
                                                        const Offset(-10, -10),
                                                    elevation: 3,
                                                    onSelected: (value) {
                                              
                                                      ////delete eligibilty-= = = = = = = = =>>
                                                      if (value == 2) {
                                                           
                                                        confirmAlert(context,
                                                            () {
                                                                   final progress =
                                                          ProgressHUD.of(
                                                              context);
                                                      progress!.showWithText(
                                                          "Loading...");
                                                          BlocProvider.of<
                                                                      EligibilityBloc>(
                                                                  context)
                                                              .add(DeleteEligibility(
                                                          
                                                                  
                                                                  eligibilityId: state
                                                                      .eligibilities[
                                                                          index]
                                                                      .id!,
                                                                  profileId:
                                                                      profileId.toString(),
                                                                  token:
                                                                      token!));
                                                        }, "Delete?",
                                                            "Confirm Delete?");
                                                      }
                                                      if (value == 1) {
                                                        ////edit eligibilty-= = = = = = = = =>>
                                                                final progress =
                                                          ProgressHUD.of(
                                                              context);
                                                      progress!.showWithText(
                                                          "Loading...");
                                                        EligibityCert
                                                            eligibityCert =
                                                            state.eligibilities[
                                                                index];
                                                        bool overseas = eligibityCert
                                                                    .examAddress!
                                                                    .country!
                                                                    .id
                                                                    .toString() ==
                                                                '175'
                                                            ? false
                                                            : true;
                                                        eligibityCert.overseas =
                                                            overseas;

                                                        eligibityCert.overseas =
                                                            overseas;

                                                        context
                                                            .read<EligibilityBloc>()
                                                            .add(ShowEditEligibilityForm(
                                                                eligibityCert:
                                                                    eligibityCert));
                                                      }
                                                    },
                                                     menuItems: [
                                                  popMenuItem(
                                                      text: "Update",
                                                      value: 1,
                                                      icon: Icons.edit),
                                                  popMenuItem(
                                                      text: "Remove",
                                                      value: 2,
                                                      icon: Icons.delete),
                                                           popMenuItem(
                                                      text: "Attach",
                                                      value: 2,
                                                      icon: Icons.attach_file),
                                              
                                                ],
                                                    icon: const Icon(
                                                      Icons.more_vert,
                                                      color: Colors.grey,
                                                    ),
                                                    tooltip: "Options",
                                                  )
                                                ],
                                              ),
                                            ),
                                            const SizedBox(
                                              height: 5,
                                            )
                                          ],
                                        );
                                      });
                                } else {
                                  return const EmptyData(
                                      message:
                                          "You don't have any eligibilities added. Please click + to add");
                                }
                              }
                              if (state is EditEligibilityState) {
                                return EditEligibilityScreen(
                                  profileId: profileId!,
                                  token: token!,
                                    eligibityCert: state.eligibityCert);
                              }
                              if (state is AddEligibilityState) {
                                return  AddEligibilityScreen(token: token!,profileId: profileId!,);
                              }
                              if (state is EligibilityErrorState) {
                                return SomethingWentWrong(message: state.message, onpressed: (){
                                  context.read<EligibilityBloc>().add(GetEligibilities(token: token!,profileId: profileId!));
                                });
                              }
                              return Container(
                                color: Colors.grey.shade200,
                              );
                            },
                          );
                        },
                      ),
                    );
                  
                    }
                    return Container();
                  }
                );
              }
              return Container();
            },
          )),
    );
  }

  PopupMenuItem<int> popMenuItem({String? text, int? value, IconData? icon}) {
    return PopupMenuItem(
      value: value,
      child: Row(
        children: [
          Icon(
            icon,
          ),
          const SizedBox(
            width: 10,
          ),
          Text(
            text!,
          ),
        ],
      ),
    );
  }
}
