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:unit2/bloc/profile/primary_information/address/address_bloc.dart';
import 'package:unit2/bloc/profile/profile_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/screens/profile/components/basic_information/address/add_modal.dart';
import 'package:unit2/screens/profile/components/basic_information/address/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/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 '../../../../utils/alerts.dart';

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

  @override
  Widget build(BuildContext context) {
    int? profileId;
    String? token;
    return Scaffold(
        appBar: AppBar(
          title: context.watch<AddressBloc>().state is AddAddressState?const Text("Add Address"):context.watch<AddressBloc>().state is EditAddressState?const Text("Edit Address"):const Text("Addresses"),
          centerTitle: true,
          backgroundColor: primary,
          actions:(context.watch<AddressBloc>().state is AddressLoadedState)?[
            AddLeading(onPressed: () {
              context.read<AddressBloc>().add(ShowAddAddressForm());
            })
          ]:(context.watch<AddressBloc>().state is AddAddressState || context.watch<AddressBloc>().state is EditAddressState)?[
            CloseLeading(onPressed:() {
              context.read<AddressBloc>().add(LoadAddress());
            })
          ]:[]
        ),
        body: ProgressHUD(
          padding: const EdgeInsets.all(24),
          indicatorWidget: const SpinKitFadingCircle(
            color: Colors.white,
          ),
          backgroundColor: Colors.black87,
          child: 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 BlocConsumer<AddressBloc, AddressState>(
                        listener: (context, state) {
                          if (state is AddressLoadingState) {
                            final progress = ProgressHUD.of(context);
                            progress!.showWithText("Please wait...");
                          }
                          if (state is AddressLoadedState ||
                              state is AddressErrorState ||
                              state is AddAddressState ||
                              state is EditAddressState ||
                              state is AddressAddedState || state is EditAddressState || state is AddressUpdatedState) {
                            final progress = ProgressHUD.of(context);
                            progress!.dismiss();
                          }
                          ////Added State
                          if (state is AddressAddedState) {
                            if (state.response['success']) {
                              successAlert(context, "Adding Successfull!",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            } else {
                              errorAlert(context, "Adding Failed",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            }
                          }
                             ////updated State
                          if (state is AddressUpdatedState) {
                            if (state.response['success']) {
                              successAlert(context, "Update Successfull!",
                                 state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            } else {
                              errorAlert(context, "Update Failed",
                                   state.response['message'], () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            }
                          }
                          //// Deleted
                          if (state is AddressDeletedState) {
                            if (state.success) {
                              successAlert(context, "Delete Successfull",
                                  "Address has been deleted successfully", () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            } else {
                              errorAlert(context, "Deletion Failed",
                                  "Error deleting Address", () {
                                Navigator.of(context).pop();
                                context.read<AddressBloc>().add(LoadAddress());
                              });
                            }
                          }
                        },
                        builder: (context, state) {
                          if (state is AddressLoadedState) {
                            bool overseas;
                            String? cityMunicipality;
                            String? province;
                            String? region;
                            String? barangay;
                            if (state.addresses.isNotEmpty) {
                              return ListView.builder(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 8, horizontal: 10),
                                  itemCount: state.addresses.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    String? subdivision =
                                        state.addresses[index].details ?? '';
                                    String? category = state.addresses[index]
                                        .address?.category?.name??'';
                               
                                    if (state.addresses[index].address?.cityMunicipality != null) {
                                      barangay = state.addresses[index].address!
                                                  .barangay !=
                                              null
                                          ? '${state.addresses[index].address!.barangay!.description!.toUpperCase()},'
                                          : '';
                                      cityMunicipality = state
                                          .addresses[index]
                                          .address!
                                          .cityMunicipality!
                                          .description!;
                                      province = state
                                          .addresses[index]
                                          .address!
                                          .cityMunicipality!
                                          .province!
                                          .description!;
                                      region = state
                                          .addresses[index]
                                          .address!
                                          .cityMunicipality!
                                          .province!
                                          .region!
                                          .description!;
                                      overseas = false;
                                    } else {
                                      overseas = true;
                                    }

                                    return Column(
                                      children: [
                                        Column(
                                          children: [
                                            Container(
                                              width: screenWidth,
                                              decoration: box1(),
                                              padding:
                                                  const EdgeInsets.fromLTRB(
                                                      8, 16, 0, 16),
                                              child: Row(children: [
                                                Expanded(
                                                    child: Column(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    SizedBox(
                                                      width: screenWidth,
                                                      child: Row(
                                                        
                                                        children: [
                                                          Flexible(
                                                            child: Text(
                                                              subdivision,
                                                              style:
                                                                  Theme.of(context)
                                                                      .textTheme
                                                                      .titleMedium!.copyWith(color: primary,fontWeight: FontWeight.w600),
                                                            ),
                                                          ),
                                                           SizedBox(
                                                           width: subdivision.isEmpty? 0: 24,
                                                          ),
                                                          Flexible(
                                                            child: Text(
                                                              category,
                                                              style:
                                                                  Theme.of(context)
                                                                      .textTheme
                                                                      .bodySmall,
                                                            ),
                                                          )
                                                        ],
                                                      ),
                                                    ),
                                            
                                                    const SizedBox(
                                                      height: 8,
                                                    ),
                                                    Container(
                                                        child: overseas
                                                            ? Text(
                                                                "COUNTRY: ${state.addresses[index].address?.country?.name?.toUpperCase()}",
                                                                textAlign:
                                                                    TextAlign
                                                                        .start,
                                                                style: Theme.of(
                                                                        context)
                                                                    .textTheme
                                                                    .titleSmall,
                                                              )
                                                            : Text(
                                                                "$barangay $cityMunicipality, $province, $region",
                                                                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...");
                                                             context
                                                          .read<AddressBloc>()
                                                          .add(DeleteAddress(
                                                              id: state
                                                                  .addresses[
                                                                      index]
                                                                  .id!,
                                                              profileId: profileId
                                                                  .toString(),
                                                              token: token!));
                                                      }, "Delete?",
                                                          "Confirm Delete?");
                                                     
                                                    }
                                                    if (value == 1) {
                                                      bool overseas;
                                                      ////edit eligibilty-= = = = = = = = =>>
                                                      final progress =
                                                          ProgressHUD.of(
                                                              context);
                                                      progress!.showWithText(
                                                          "Loading...");

                                                      if (state
                                                              .addresses[index]
                                                              .address
                                                              ?.cityMunicipality ==
                                                          null) {
                                                        overseas = true;
                                                      } else {
                                                        overseas = false;
                                                      }
                                                      context
                                                          .read<AddressBloc>()
                                                          .add(ShowEditAddressForm(
                                                              overseas:
                                                                  overseas,
                                                              address: state
                                                                      .addresses[
                                                                  index]));
                                                    }
                                                  },
                                                  menuItems: [
                                                    popMenuItem(
                                                        text: "Update",
                                                        value: 1,
                                                        icon: Icons.edit),
                                                    popMenuItem(
                                                        text: "Remove",
                                                        value: 2,
                                                        icon: Icons.delete),
                                             
                                                  ],
                                                  icon: const Icon(
                                                    Icons.more_vert,
                                                    color: Colors.grey,
                                                  ),
                                                  tooltip: "Options",
                                                )
                                              ]),
                                            ),
                                          ],
                                        ),
                                        const SizedBox(
                                          height: 5,
                                        ),
                                      ],
                                    );
                                  });
                            } else {
                              return const EmptyData(
                                  message:
                                      "You don't have address added. Please click + to add.");
                            }
                          }
                          if (state is AddressErrorState) {
                            return SomethingWentWrong(
                                message: state.message, onpressed: () {context.read<AddressBloc>().add(LoadAddress());});
                          }
                          if (state is AddAddressState) {
                            return AddAddressScreen(
                                profileId: profileId!, token: token!);
                          }
                          if (state is EditAddressState) {
                            return EditAddressScreen(
                                profileId: profileId!, token: token!);
                          }
                          return Container();
                        },
                      );
                    }
                    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!,
          ),
        ],
      ),
    );
  }
}
