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: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/add_leading.dart';
import 'package:unit2/widgets/empty_data.dart';

import '../../../utils/alerts.dart';

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

  @override
  Widget build(BuildContext context) {
    String? token;
    String? profileId;
    return Scaffold(
        appBar: AppBar(
          title: const Text(elibilityScreenTitle),
          centerTitle: true,
          backgroundColor: primary,
          actions: [
            AddLeading(onPressed: () {
              context.read<ProfileBloc>().add(ShowAddEligibilityForm());
            })
          ],
        ),
        body: BlocBuilder<UserBloc, UserState>(
          builder: (context, state) {
            if (state is UserLoggedIn) {
              token = state.userData!.user!.login!.token;
              profileId =
                  state.userData!.user!.login!.user!.profileId.toString();
              return ProgressHUD(
                child: BlocConsumer<ProfileBloc, ProfileState>(
                  listener: (context, state) {
                    if (state is EditEligibilityState) {
                      final progress = ProgressHUD.of(context);
                      progress!.dismiss();
                    }
                    if (state is ProfileLoading) {
                      final progress = ProgressHUD.of(context);
                      progress!.showWithText("Loading");
                    }
                    if (state is EligibilityLoaded ||
                        state is AddEligibilityState ||
                        state is ProfileErrorState) {
                      final progress = ProgressHUD.of(context);
                      progress!.dismiss();
                    }
                    if (state is DeletedState) {
                      if (state.success) {
                        successAlert(context, "Deletion Successfull",
                            "Eligibility has been deleted successfully", () {
                          context.read<ProfileBloc>().add(LoadEligibility(
                              eligibilities: state.eligibilities));
                        });
                      } else {
                        errorAlert(context, "Deletion Failed",
                            "Error deleting eligibility", () {
                          Navigator.of(context).pop();
                          context.read<ProfileBloc>().add(LoadEligibility(
                              eligibilities: state.eligibilities));
                        });
                      }
                    }
                    if (state is EligibilityAddedState) {
                      if (state.response['success']) {
                        Navigator.of(context).pop();
                        successAlert(context, "Adding Successfull!",
                            state.response['message'], () {
                          context.read<ProfileBloc>().add(LoadEligibility(
                              eligibilities: state.eligibilities));
                        });
                      } else {
                        errorAlert(context, "Adding Failed",
                            "Something went wrong. Please try again.", () {
                          Navigator.of(context).pop();
                          context.read<ProfileBloc>().add(LoadEligibility(
                              eligibilities: state.eligibilities));
                        });
                      }
                    }
                  },
                  builder: (context, state) {
                    return BlocBuilder<ProfileBloc, ProfileState>(
                      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),
                                                    ),
                                                    const Divider(),
                                                    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) {
                                                if (value == 2) {
                                                  confirmAlert(context, () {
                                                    BlocProvider.of<
                                                                ProfileBloc>(
                                                            context)
                                                        .add(DeleteEligibility(
                                                            eligibilities: state
                                                                .eligibilities,
                                                            eligibilityId: state
                                                                .eligibilities[
                                                                    index]
                                                                .id!,
                                                            profileId:
                                                                profileId!,
                                                            token: token!));
                                                  }, "Delete?",
                                                      "Confirm Delete?");
                                                }
                                                if (value == 1) {
                                                  EligibityCert eligibityCert =
                                                      state
                                                          .eligibilities[index];
                                                  bool overseas = eligibityCert
                                                              .examAddress!
                                                              .country!
                                                              .id
                                                              .toString() ==
                                                          '175'
                                                      ? false
                                                      : true;
                                                  eligibityCert.overseas =
                                                      overseas;
                                                  final progress =
                                                      ProgressHUD.of(context);
                                                  eligibityCert.overseas =
                                                      overseas;
                                                  progress!.showWithText(
                                                      "Loading...");
                                                  context
                                                      .read<ProfileBloc>()
                                                      .add(EditEligibility(
                                                          eligibityCert:
                                                              eligibityCert));
                                                }
                                              },
                                              menuItems: [
                                                popMenuItem(
                                                    text: "Edit",
                                                    value: 1,
                                                    icon: Icons.edit),
                                                popMenuItem(
                                                    text: "Delete",
                                                    value: 2,
                                                    icon: Icons.delete),
                                                popMenuItem(
                                                    text: "Attachment",
                                                    value: 3,
                                                    icon: FontAwesome.attach)
                                              ],
                                              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(
                              eligibityCert: state.eligibityCert);
                        }
                        if (state is AddEligibilityState) {
                          return const AddEligibilityScreen();
                        }
                        if (state is ProfileErrorState) {
                          return Center(
                            child: Text(state.mesage),
                          );
                        }
                        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!,
          ),
        ],
      ),
    );
  }
}
