import 'dart:io';
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:intl/intl.dart';
import 'package:unit2/bloc/profile/profile_bloc.dart';
import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/screens/profile/components/work_history/add_modal.dart';
import 'package:unit2/screens/profile/components/work_history/edit_modal.dart';
import 'package:unit2/theme-data.dart/box_shadow.dart';
import 'package:unit2/theme-data.dart/colors.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/workHistory/workHistory_bloc.dart';
import '../../../model/profile/work_history.dart';
import '../../../utils/alerts.dart';
import '../../../utils/global.dart';

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

  @override
  Widget build(BuildContext context) {
    DateFormat dteFormat2 = DateFormat.yMMMMd('en_US');
    String? token;
    int profileId;
    return Scaffold(
        appBar: AppBar(
          title: context.watch<WorkHistoryBloc>().state is AddWorkHistoryState
              ? const FittedBox(child: Text("Add Work History"))
              : context.watch<WorkHistoryBloc>().state is EditWorkHistoryState
                  ? const FittedBox(
                      child: Text("Edit Work History"),
                    )
                  : const Text(workHistoryScreenTitle),
          backgroundColor: primary,
          centerTitle: true,
          actions: context.watch<WorkHistoryBloc>().state is WorkHistoryLoaded
              ? [
                  AddLeading(onPressed: () {
                    context
                        .read<WorkHistoryBloc>()
                        .add(ShowAddWorkHistoryForm());
                  })
                ]
              : (context.watch<WorkHistoryBloc>().state
                          is AddWorkHistoryState ||
                      context.watch<WorkHistoryBloc>().state
                          is EditWorkHistoryState)
                  ? [
                      CloseLeading(onPressed: () {
                        context
                            .read<WorkHistoryBloc>()
                            .add(LoadWorkHistories());
                      })
                    ]
                  : [],
        ),
        body:
            //UserBloc
            ProgressHUD(
          padding: const EdgeInsets.all(24),
          backgroundColor: Colors.black87,
          indicatorWidget: const SpinKitFadingCircle(
            color: Colors.white,
          ),
          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) {
                    //ProfileBloc
                    if (state is ProfileLoaded) {
                      //WorkHistoryBloc
                      return BlocConsumer<WorkHistoryBloc, WorkHistoryState>(
                        listener: (context, state) {
                          if (state is WorkHistoryLoadingState) {
                            final progress = ProgressHUD.of(context);
                            progress!.showWithText("Please wait...");
                          }
                          if (state is WorkHistoryLoaded ||
                              state is WorkHistoryErrorState ||
                              state is AddWorkHistoryState ||
                              state is WorkHistoryAddedState ||
                              state is EditWorkHistoryState) {
                            final progress = ProgressHUD.of(context);
                            progress!.dismiss();
                          }
                          //DELETED STATE
                          if (state is DeletedState) {
                            if (state.success) {
                              successAlert(context, "Deletion Successfull",
                                  "Work has been deleted successfully", () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            } else {
                              errorAlert(context, "Deletion Failed",
                                  "Error deleting Work History", () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            }
                          }
                          ////ADDED STATE
                          if (state is WorkHistoryAddedState) {
                            if (state.response['success']) {
                              successAlert(context, "Adding Successfull!",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            } else {
                              errorAlert(context, "Adding Failed",
                                  "Something went wrong. Please try again.",
                                  () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            }
                          }
                          //// EDITED STATE
                          if (state is WorkHistoryEditedState) {
                            if (state.response['success']) {
                              successAlert(context, "Update Successfull!",
                                  state.response['message'], () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            } else {
                              errorAlert(context, "Update Failed",
                                  "Something went wrong. Please try again.",
                                  () {
                                Navigator.of(context).pop();
                                context
                                    .read<WorkHistoryBloc>()
                                    .add(LoadWorkHistories());
                              });
                            }
                          }
                        },
                        builder: (context, state) {
                          if (state is WorkHistoryLoaded) {
                            if (state.workExperiences.isNotEmpty) {
                              return ListView.builder(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 8, horizontal: 10),
                                  itemCount: state.workExperiences.length,
                                  itemBuilder:
                                      (BuildContext context, int index) {
                                    String position = state
                                        .workExperiences[index]
                                        .position!
                                        .title!;
                                    String agency = state
                                        .workExperiences[index].agency!.name!;
                                    String from = dteFormat2.format(
                                        state.workExperiences[index].fromDate!);
                                    String? to =
                                        state.workExperiences[index].toDate ==
                                                null
                                            ? present.toUpperCase()
                                            : dteFormat2.format(state
                                                .workExperiences[index]
                                                .toDate!);
                                    return Column(
                                      children: [
                                        Container(
                                          width: screenWidth,
                                          decoration: box1(),
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 12, vertical: 8),
                                          child: Row(children: [
                                            Expanded(
                                                child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.start,
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  position,
                                                  style: Theme.of(context)
                                                      .textTheme
                                                      .titleMedium!
                                                      .copyWith(
                                                          fontWeight:
                                                              FontWeight.w600,
                                                          color: primary),
                                                ),
                                                const SizedBox(
                                                  height: 8,
                                                ),
                                                Text(
                                                  agency,
                                                  style: Theme.of(context)
                                                      .textTheme
                                                      .titleSmall!
                                                      .copyWith(
                                                          fontWeight:
                                                              FontWeight.w500),
                                                ),
                                                const SizedBox(
                                                  height: 5,
                                                ),
                                                Text(
                                                  "$from - $to ",
                                                  style: Theme.of(context)
                                                      .textTheme
                                                      .labelMedium,
                                                ),
                                              ],
                                            )),
                                            AppPopupMenu<int>(
                                              offset: const Offset(-10, -10),
                                              elevation: 3,
                                              onSelected: (value) {
                                                ////delete workhistory-= = = = = = = = =>>
                                                if (value == 2) {
                                                  confirmAlert(context, () {
                                                    final progress =
                                                        ProgressHUD.of(context);
                                                    progress!.showWithText(
                                                        "Loading...");
                                                    BlocProvider.of<
                                                                WorkHistoryBloc>(
                                                            context)
                                                        .add(DeleteWorkHistory(
                                                      profileId: profileId,
                                                      token: token!,
                                                      workHistory:
                                                          state.workExperiences[
                                                              index],
                                                    ));
                                                  }, "Delete?",
                                                      "Confirm Delete?");
                                                }
                                                if (value == 1) {
                                                  ////edit eligibilty-= = = = = = = = =>>
                                                  final progress =
                                                      ProgressHUD.of(context);
                                                  progress!.showWithText(
                                                      "Loading...");
                                                  WorkHistory workHistory =
                                                      state.workExperiences[
                                                          index];
                                                  context
                                                      .read<WorkHistoryBloc>()
                                                      .add(
                                                          ShowEditWorkHistoryForm(
                                                              workHistory:
                                                                  workHistory));
                                                }
                                              },
                                         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 work experience added. Please click + to add");
                            }
                          }
                          if (state is AddWorkHistoryState) {
                            return AddWorkHistoryScreen(
                              profileId: profileId,
                              token: token!,
                            );
                          }
                          if (state is EditWorkHistoryState) {
                            return EditWorkHistoryScreen(
                              profileId: profileId,
                              token: token!,
                            );
                          }
                          if (state is WorkHistoryErrorState) {
                            return SomethingWentWrong(
                                message: state.message,
                                onpressed: () {
                                  context.read<WorkHistoryBloc>().add(
                                      GetWorkHistories(
                                          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!,
        ),
      ],
    ),
  );
}
