import 'package:date_time_picker/date_time_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:fluttericon/font_awesome_icons.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:searchfield/searchfield.dart';
import 'package:unit2/bloc/profile/workHistory/workHistory_bloc.dart';
import 'package:unit2/model/profile/work_history.dart';
import 'package:unit2/model/utils/agency.dart';
import 'package:unit2/model/utils/agency_position.dart';
import 'package:unit2/model/utils/category.dart';
import 'package:unit2/theme-data.dart/box_shadow.dart';
import 'package:unit2/theme-data.dart/btn-style.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/global.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/utils/validators.dart';
import '../../../../model/utils/position.dart';
import '../../../../utils/formatters.dart';
import '../../shared/add_for_empty_search.dart';

class AddWorkHistoryScreen extends StatefulWidget {
  final int profileId;
  final String token;
  const AddWorkHistoryScreen(
      {super.key, required this.profileId, required this.token});

  @override
  State<AddWorkHistoryScreen> createState() => _AddWorkHistoryScreenState();
}

class _AddWorkHistoryScreenState extends State<AddWorkHistoryScreen> {
  final addAgencyController = TextEditingController();
  final addPositionController = TextEditingController();
  final toDateController = TextEditingController();
  final fromDateController = TextEditingController();
  final _formKey = GlobalKey<FormBuilderState>();
  Position? selectedPosition;
  Agency? selectedAgency;
  AppoinemtStatus? selectedStatus;
  Category? selectedAgencyCategory;
  String? salary;
  String? salaryGrade;
  String? salaryGradeStep;
  bool showAgency = false;
  bool showSalaryGradeAndSalaryStep = false;
  bool? isPrivate = false;
  bool showIsPrivateRadio = false;
  bool currentlyEmployed = false;
  final agencyFocusNode = FocusNode();
  final positionFocusNode = FocusNode();
  final appointmentStatusNode = FocusNode();
  final agencyCategoryFocusNode = FocusNode();
  DateTime? from;
  DateTime? to;
  @override
  void dispose() {
    addPositionController.dispose();
    addAgencyController.dispose();
    toDateController.dispose();
    fromDateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<WorkHistoryBloc, WorkHistoryState>(
        listener: (context, state) {
      if (state is AddWorkHistoryState) {
        final progress = ProgressHUD.of(context);
        progress!.dismiss();
      }
    }, builder: (context, state) {
      if (state is AddWorkHistoryState) {
        return FormBuilder(
          key: _formKey,
          child: SizedBox(
            height: blockSizeVertical * 90,
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 32, horizontal: 28),
              child: Column(
                children: [
                  Flexible(
                    child: ListView(
                      children: [
                        ////POSITIONS
                        StatefulBuilder(builder: (context, setState) {
                          return SearchField(
                            inputFormatters: [UpperCaseTextFormatter()],
                            itemHeight: 100,
                            suggestionsDecoration: box1(),
                            suggestions: state.agencyPositions
                                .map((Position position) => SearchFieldListItem(
                                    position.title!,
                                    item: position,
                                    child: Padding(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 10),
                                        child: ListTile(
                                          title: Text(
                                            position.title!,
                                            overflow: TextOverflow.visible,
                                          ),
                                        ))))
                                .toList(),
                            focusNode: positionFocusNode,
                            searchInputDecoration:
                                normalTextFieldStyle("Position *", "").copyWith(
                                    suffixIcon: IconButton(
                              icon: const Icon(Icons.arrow_drop_down),
                              onPressed: () {
                                positionFocusNode.unfocus();
                              },
                            )),
                            onSuggestionTap: (position) {
                              setState(() {
                                selectedPosition = position.item;
                                positionFocusNode.unfocus();
                              });
                            },
                            ////EMPTY WIDGET
                            emptyWidget: EmptyWidget(
                                title: "Add Position",
                                controller: addPositionController,
                                onpressed: () {
                                  setState(() {
                                    Position newAgencyPosition = Position(
                                        id: null,
                                        title: addPositionController.text
                                            .toUpperCase());

                                    state.agencyPositions
                                        .insert(0, newAgencyPosition);
                                    selectedPosition = newAgencyPosition;
                                    addPositionController.text = "";
                                    Navigator.pop(context);
                                  });
                                }),
                            validator: (position) {
                              if (position!.isEmpty) {
                                return "This field is required";
                              }
                              return null;
                            },
                          );
                        }),
                        const SizedBox(
                          height: 12,
                        ),
                        ////APPOINTMENT STATUS'
                        SearchField(
                            inputFormatters: [UpperCaseTextFormatter()],
                            suggestions: state.appointmentStatus
                                .map((AppoinemtStatus status) =>
                                    SearchFieldListItem(status.label,
                                        item: status,
                                        child: Padding(
                                            padding: const EdgeInsets.all(8),
                                            child: Text(status.label))))
                                .toList(),
                            focusNode: appointmentStatusNode,
                            validator: (value) {
                              if (value!.isEmpty) {
                                return "This field is required";
                              }
                              return null;
                            },
                            onSuggestionTap: (status) {
                              selectedStatus = status.item;
                       
                              appointmentStatusNode.unfocus();
                            },
                            searchInputDecoration:
                                normalTextFieldStyle("Appointment Status", "")
                                    .copyWith(
                                        suffixIcon: IconButton(
                              icon: const Icon(Icons.arrow_drop_down),
                              onPressed: () {
                                appointmentStatusNode.unfocus();
                              },
                            ))),

                        const SizedBox(
                          height: 12,
                        ),
                        ////AGENCY
                        StatefulBuilder(builder: (context, setState) {
                          return Column(
                            children: [
                              SearchField(
                                  inputFormatters: [UpperCaseTextFormatter()],
                                  itemHeight: 100,
                                  focusNode: agencyFocusNode,
                                  suggestions: state.agencies
                                      .map((Agency agency) =>
                                          SearchFieldListItem(agency.name!,
                                              item: agency,
                                              child: ListTile(
                                                title: Text(
                                                  agency.name!,
                                                  overflow:
                                                      TextOverflow.visible,
                                                ),
                                                subtitle: Text(agency
                                                            .privateEntity ==
                                                        true
                                                    ? "Private"
                                                    : agency.privateEntity ==
                                                            false
                                                        ? "Government"
                                                        : ""),
                                              )))
                                      .toList(),
                                  searchInputDecoration:
                                      normalTextFieldStyle("Agency *", "")
                                          .copyWith(
                                              suffixIcon: IconButton(
                                    icon: const Icon(Icons.arrow_drop_down),
                                    onPressed: () {
                                      agencyFocusNode.unfocus();
                                    },
                                  )),
                                  onSuggestionTap: (agency) {
                                    setState(() {
                                      selectedAgency = agency.item;

                                      if (selectedAgency!.privateEntity ==
                                          null) {
                                        showIsPrivateRadio = true;
                                      } else {
                                        showIsPrivateRadio = false;
                                      }
                                      if (selectedAgency!.privateEntity ==
                                          true) {
                                        showSalaryGradeAndSalaryStep = false;
                                      }
                                      if (selectedAgency!.privateEntity ==
                                          false) {
                                        showSalaryGradeAndSalaryStep = true;
                                      }
                                      agencyFocusNode.unfocus();
                                    });
                                  },
                                  validator: (agency) {
                                    if (agency!.isEmpty) {
                                      return "This field is required";
                                    }
                                    return null;
                                  },
                                  emptyWidget: EmptyWidget(
                                      controller: addAgencyController,
                                      onpressed: () {
                                        setState(() {
                                          Agency newAgency = Agency(
                                              id: null,
                                              name: addAgencyController.text
                                                  .toUpperCase(),
                                              category: null,
                                              privateEntity: null);

                                          state.agencies.insert(0, newAgency);
                                          selectedAgency = newAgency;
                                          addAgencyController.text = "";
                                          showAgency = true;

                                          showIsPrivateRadio = true;

                                          Navigator.pop(context);
                                        });
                                      },
                                      title: "Add Agency")),

                              SizedBox(
                                height: showAgency ? 12 : 0,
                              ),
                              ////SHOW CATEGORY AGENCY
                              SizedBox(
                                child: showAgency
                                    ? SearchField(
                                        focusNode: agencyCategoryFocusNode,
                                        itemHeight: 70,
                                        suggestions: state.agencyCategory
                                            .map((Category category) =>
                                                SearchFieldListItem(
                                                    category.name!,
                                                    item: category,
                                                    child: ListTile(
                                                      title:
                                                          Text(category.name!),
                                                      subtitle: Text(category
                                                          .industryClass!
                                                          .name!),
                                                    )))
                                            .toList(),
                                        emptyWidget: Container(
                                          height: 100,
                                          decoration: box1(),
                                          child: const Center(
                                              child:
                                                  Text("No result found ...")),
                                        ),
                                        onSuggestionTap: (agencyCategory) {
                                          setState(() {
                                            selectedAgencyCategory =
                                                agencyCategory.item;
                                            agencyCategoryFocusNode.unfocus();
                                            selectedAgency = Agency(
                                                id: null,
                                                name: selectedAgency!.name,
                                                category:
                                                    selectedAgencyCategory,
                                                privateEntity: null);
                                          });
                                        },
                                        searchInputDecoration:
                                            normalTextFieldStyle(
                                                    "Category *", "")
                                                .copyWith(
                                                    suffixIcon: IconButton(
                                          icon:
                                              const Icon(Icons.arrow_drop_down),
                                          onPressed: () {
                                            agencyCategoryFocusNode.unfocus();
                                          },
                                        )),
                                        validator: (value) {
                                          if (value!.isEmpty) {
                                            return "This field is required";
                                          }
                                          return null;
                                        },
                                      )
                                    : const SizedBox(),
                              ),

                              ////PRVIATE SECTOR
                              SizedBox(
                                  child: showIsPrivateRadio
                                      ? FormBuilderRadioGroup(
                                          decoration: InputDecoration(
                                            border: InputBorder.none,
                                            label: Row(
                                              children: [
                                                Text(
                                                  "Is this private sector? ",
                                                  style: Theme.of(context)
                                                      .textTheme
                                                      .headlineSmall!
                                                      .copyWith(fontSize: 24),
                                                ),
                                                const Icon(
                                                    FontAwesome.help_circled)
                                              ],
                                            ),
                                          ),

                                          ////onvhange private sector
                                          onChanged: (value) {
                                            setState(() {
                                              if (value.toString() == "YES") {
                                                isPrivate = true;
                                                showSalaryGradeAndSalaryStep =
                                                    false;
                                              } else {
                                                isPrivate = false;
                                                showSalaryGradeAndSalaryStep =
                                                    true;
                                              }
                                              selectedAgency = Agency(
                                                  id: null,
                                                  name: selectedAgency!.name,
                                                  category:
                                                      selectedAgencyCategory,
                                                  privateEntity: value == "YES"
                                                      ? true
                                                      : false);
                                              agencyFocusNode.unfocus();
                                              agencyCategoryFocusNode.unfocus();
                                            });
                                          },

                                          name: 'isPrivate',
                                          validator:
                                              FormBuilderValidators.required(),
                                          options: ["YES", "NO"]
                                              .map((lang) =>
                                                  FormBuilderFieldOption(
                                                      value: lang))
                                              .toList(growable: false),
                                        )
                                      : const SizedBox()),
                              SizedBox(
                                height: showSalaryGradeAndSalaryStep ? 12 : 0,
                              ),
                              ////SALARY GRADE AND SALARY GRADE STEP
                              SizedBox(
                                  child: showSalaryGradeAndSalaryStep
                                      ? Column(
                                          children: [
                                            Row(
                                              children: [
                                                Flexible(
                                                  flex: 1,
                                                  child: FormBuilderTextField(
                                                    name: 'salary_grade',
                                                    keyboardType:
                                                        TextInputType.number,
                                                    decoration:
                                                        normalTextFieldStyle(
                                                            "Salary Grade (SG)",
                                                            "0"),
                                                    onChanged: (value) {
                                                      salaryGrade = value;
                                                    },
                                                    validator:
                                                        FormBuilderValidators
                                                            .compose([
                                                      FormBuilderValidators.integer(
                                                          radix: 10,
                                                          errorText:
                                                              "Please enter a number"),
                                                      FormBuilderValidators.numeric(
                                                          errorText:
                                                              "Please enter a number")
                                                    ]),
                                                    autovalidateMode:
                                                        AutovalidateMode
                                                            .onUserInteraction,
                                                  ),
                                                ),
                                                const SizedBox(
                                                  width: 12,
                                                ),
                                                Flexible(
                                                  flex: 1,
                                                  child: FormBuilderTextField(
                                                    name: 'salary_step',
                                                    keyboardType:
                                                        TextInputType.number,
                                                    decoration:
                                                        normalTextFieldStyle(
                                                            "SG Step (SG)",
                                                            "0"),
                                                    validator:
                                                        FormBuilderValidators
                                                            .compose([
                                                      FormBuilderValidators.integer(
                                                          radix: 10,
                                                          errorText:
                                                              "Please enter a number"),
                                                      FormBuilderValidators.numeric(
                                                          errorText:
                                                              "Please enter a number")
                                                    ]),
                                                    autovalidateMode:
                                                        AutovalidateMode
                                                            .onUserInteraction,
                                                    onChanged: (value) {
                                                      setState(() {
                                                        salaryGradeStep = value;
                                                      });
                                                    },
                                                  ),
                                                )
                                              ],
                                            )
                                          ],
                                        )
                                      : null),
                            ],
                          );
                        }),
                        const SizedBox(
                          height: 12,
                        ),
                        ////MONTHLY SALARY
                        FormBuilderTextField(
                          onChanged: (value) {
                            setState(() {
                              salary = value;
                            });
                          },
                          validator: numericRequired,
                          name: "salary",
                          decoration:
                              normalTextFieldStyle("Monthly Salary *", "")
                                  .copyWith(prefix: const Text("₱ ")),
                        ),

                        const SizedBox(
                          height: 12,
                        ),
                        StatefulBuilder(builder: (context, setState) {
                          return Column(
                            children: [
                              ////CURRENTLY EMPLOYED
                              FormBuilderSwitch(
                                initialValue: currentlyEmployed,
                                activeColor: second,
                                onChanged: (value) {
                                  setState(() {
                                    if (value == true) {
                                      currentlyEmployed = true;
                                      toDateController.text = "PRESENT";
                                    } else {
                                      currentlyEmployed = false;
                                      toDateController.text = "";
                                    }
                                  });
                                },
                                decoration: normalTextFieldStyle("", ''),
                                name: 'overseas',
                                title: const Text("Currently Employed?"),
                              ),
                              const SizedBox(
                                height: 12,
                              ),
                              SizedBox(
                                width: screenWidth,
                                child: Row(
                                  children: [
                                    //// FROM DATE
                                    Flexible(
                                        flex: 1,
                                        child: DateTimePicker(
                                          validator:
                                              FormBuilderValidators.required(
                                                  errorText:
                                                      "This field is required"),
                                          use24HourFormat: false,
                                          icon: const Icon(Icons.date_range),
                                          controller: fromDateController,
                                          firstDate: DateTime(1990),
                                          lastDate: DateTime(2100),
                                          selectableDayPredicate: (date) {
                                            if (to != null &&
                                                to!.microsecondsSinceEpoch <=
                                                    date.microsecondsSinceEpoch) {
                                              return false;
                                            }
                                            return true;
                                          },
                                          timeHintText:
                                              "Date of Examination/Conferment",
                                          decoration: normalTextFieldStyle(
                                                  "From *", "From *")
                                              .copyWith(
                                                  prefixIcon: const Icon(
                                            Icons.date_range,
                                            color: Colors.black87,
                                          )),
                                          onChanged: (value) {
                                            setState(() {
                                              from = DateTime.parse(value);
                                            });
                                          },
                                          initialDate: to == null
                                              ? DateTime.now()
                                              : to!.subtract(
                                                  const Duration(days: 1)),
                                        )),
                                    const SizedBox(
                                      width: 12,
                                    ),
                                    //// TO DATE
                                    Flexible(
                                      flex: 1,
                                      child: currentlyEmployed
                                          ? TextFormField(
                                              enabled: false,
                                              initialValue: "PRESENT",
                                              style: const TextStyle(
                                                  color: Colors.black45),
                                              decoration:
                                                  normalTextFieldStyle("", "")
                                                      .copyWith(),
                                            )
                                          : DateTimePicker(
                                              validator: FormBuilderValidators
                                                  .required(
                                                      errorText:
                                                          "This field is required"),
                                              controller: toDateController,
                                              firstDate: DateTime(1990),
                                              lastDate: DateTime(2100),
                                              selectableDayPredicate: (date) {
                                                if (from != null &&
                                                    from!.microsecondsSinceEpoch >=
                                                        date.microsecondsSinceEpoch) {
                                                  return false;
                                                }
                                                return true;
                                              },
                                                onChanged: (value) {
                                          setState(() {
                                            to =
                                                DateTime.parse(value);
                                          });
                                        },
                                              initialDate: from == null
                                                  ? DateTime.now()
                                                  : from!.add(
                                                      const Duration(days: 1)),
                                              decoration: normalTextFieldStyle(
                                                      "To *", "To *")
                                                  .copyWith(
                                                      prefixIcon: const Icon(
                                                        Icons.date_range,
                                                        color: Colors.black87,
                                                      ),
                                                      prefixText:
                                                          currentlyEmployed
                                                              ? "PRESENT"
                                                              : ""),
                                            ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          );
                        }),
                      ],
                    ),
                  ),
                  ////SUBMIT BUTTON
                  SizedBox(
                    width: double.infinity,
                    height: 60,
                    child: ElevatedButton(
                        style:
                            mainBtnStyle(primary, Colors.transparent, second),
                        onPressed: () {
                          print(selectedStatus?.value);
                          if (_formKey.currentState!.validate()) {
                            final progress = ProgressHUD.of(context);
                            progress!.showWithText("Loading...");
                            WorkHistory workHistory = WorkHistory(
                                position: selectedPosition,
                                id: null,
                                agency: selectedAgency,
                                fromDate: fromDateController.text.isEmpty
                                    ? null
                                    : DateTime.parse(fromDateController.text),
                                toDate: toDateController.text.isEmpty ||
                                        toDateController.text.toUpperCase() ==
                                            "PRESENT"
                                    ? null
                                    : DateTime.parse(toDateController.text),
                                salaryGrade: salaryGrade == null
                                    ? null
                                    : int.parse(salaryGrade!),
                                sgStep: salaryGradeStep == null
                                    ? null
                                    : int.parse(salaryGradeStep!),
                                monthlySalary: double.parse(salary!),
                                appointmentStatus: selectedStatus!.value);
                            context.read<WorkHistoryBloc>().add(AddWorkHostory(
                                workHistory: workHistory,
                                profileId: widget.profileId,
                                token: widget.token,
                                isPrivate: selectedAgency!.privateEntity!));
                          }
                        },
                        child: const Text(submit)),
                  ),
                ],
              ),
            ),
          ),
        );
      }
      return Container();
    });
  }
}
