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/other_information/org_membership/organization_membership_bloc.dart';
import 'package:unit2/model/utils/agency.dart';
import 'package:unit2/utils/text_container.dart';
import '../../../../../model/utils/category.dart';
import '../../../../../theme-data.dart/box_shadow.dart';
import '../../../../../theme-data.dart/btn-style.dart';
import '../../../../../theme-data.dart/colors.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/formatters.dart';

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

  @override
  State<AddOrgMemberShipScreen> createState() => _AddOrgMemberShipScreenState();
}

bool showAgencyCategory = false;
final agencyFocusNode = FocusNode();

final agencyCategoryFocusNode = FocusNode();
final addAgencyController = TextEditingController();
Agency? selectedAgency;
Category? selectedCategory;
Agency? newAgency;
bool showIsPrivateRadio = false;
bool? isPrivate = false;
final _formKey = GlobalKey<FormBuilderState>();

class _AddOrgMemberShipScreenState extends State<AddOrgMemberShipScreen> {
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<OrganizationMembershipBloc, OrganizationMembershipState>(
      builder: (context, state) {
        if (state is AddOrgMembershipState) {
          return Padding(
            padding: const EdgeInsets.all(24),
            child: Card(
          
              child: SingleChildScrollView(
                child: FormBuilder(
                    key: _formKey,
                    child: Container(
                      padding:
                          const EdgeInsets.symmetric(vertical:24, horizontal: 24),
                      child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                          
                            StatefulBuilder(builder: (context, setState) {
                              //// AGENCY SEARCHFIELD
                              return Column(
                                children: [
                                  SearchField(
                                    inputFormatters: [UpperCaseTextFormatter()],
                      
                                    itemHeight: 100,
                                    suggestions: state.agencies
                                        .map((Agency agency) =>
                                            SearchFieldListItem(agency.name!,
                                                item: agency,
                                                child: ListTile(
                                                  title: Text(
                                                    agency.name!.toUpperCase(),
                                                    overflow: TextOverflow.visible,
                                                  ),
                                                  subtitle: Text(
                                                      agency.privateEntity == true
                                                          ? "Private"
                                                          : agency.privateEntity ==
                                                                  false
                                                              ? "Government"
                                                              : ""),
                                                )))
                                        .toList(),
                                    validator: FormBuilderValidators.required(
                                        errorText: "This field is required"),
                                    focusNode: agencyFocusNode,
                                    searchInputDecoration:
                                        normalTextFieldStyle("Agency *", "")
                                            .copyWith(
                                                suffixIcon: GestureDetector(
                                      child: const Icon(
                                        Icons.arrow_drop_down,
                                      ),
                                      onTap: () => agencyFocusNode.unfocus(),
                                    )),
                                    ////agency suggestion tap
                                    onSuggestionTap: (agency) {
                                      setState(() {
                                        selectedAgency = agency.item;
                                        agencyFocusNode.unfocus();
                                        if (selectedAgency?.category == null) {
                                          showAgencyCategory = true;
                                          showIsPrivateRadio = true;
                                        } else {
                                          showAgencyCategory = false;
                                          showIsPrivateRadio = false;
                                        }
                                      });
                                    },
                                    emptyWidget: Container(
                                      decoration: box1(),
                                      height: 100,
                                      child: Column(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            const SizedBox(
                                              height: 20,
                                            ),
                                            const Text("No result found..."),
                                            const SizedBox(
                                              height: 10,
                                            ),
                                            TextButton(
                                                //// Add agency onpressed
                                                onPressed: () {
                                                  showDialog(
                                                      context: context,
                                                      builder:
                                                          (BuildContext context) {
                                                        return AlertDialog(
                                                          title: const Text(
                                                              "Add Agency?"),
                                                          content: SizedBox(
                                                            height: 130,
                                                            child: Column(
                                                              children: [
                                                                TextFormField(
                                                                  inputFormatters: [
                                                                    UpperCaseTextFormatter()
                                                                  ],
                                                                  controller:
                                                                      addAgencyController,
                                                                  decoration:
                                                                      normalTextFieldStyle(
                                                                          "", ""),
                                                                ),
                                                                const SizedBox(
                                                                  height: 12,
                                                                ),
                                                                SizedBox(
                                                                    width: double
                                                                        .infinity,
                                                                    height: 50,
                                                                    child:
                                                                        ElevatedButton(
                                                                            style: mainBtnStyle(
                                                                                primary,
                                                                                Colors
                                                                                    .transparent,
                                                                                second),
                                                                            //// onpressed
                                                                            onPressed:
                                                                                () {
                                                                              setState(
                                                                                  () {
                                                                                newAgency = Agency(
                                                                                    id: null,
                                                                                    name: addAgencyController.text.toUpperCase(),
                                                                                    category: null,
                                                                                    privateEntity: null);
                                                                                state.agencies.insert(0,
                                                                                    newAgency!);
                                                                                addAgencyController.clear();
                                                                                Navigator.pop(context);
                                                                              });
                                                                            },
                                                                            child: const Text(
                                                                                "Add"))),
                                                              ],
                                                            ),
                                                          ),
                                                        );
                                                      });
                                                },
                                                child: const Text("Add position"))
                                          ]),
                                    ),
                                  ),
                                  const SizedBox(
                                    height: 8,
                                  ),
                                  SizedBox(
                                    child: showAgencyCategory
                                        ? SearchField(
                                            focusNode: agencyCategoryFocusNode,
                                            itemHeight: 70,
                                            suggestions: state.agencyCategories
                                                .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 ...")),
                                            ),
                                            ////agency controller suggestion tap
                                            onSuggestionTap: (agencyCategory) {
                                              setState(() {
                                                selectedCategory =
                                                    agencyCategory.item;
                      
                                                agencyCategoryFocusNode.unfocus();
                                              });
                                            },
                                            searchInputDecoration:
                                                normalTextFieldStyle(
                                                        "Category *", "")
                                                    .copyWith(
                                                        suffixIcon: GestureDetector(
                                              child: const Icon(
                                                Icons.arrow_drop_down,
                                              ),
                                              onTap: () =>
                                                  agencyCategoryFocusNode.unfocus(),
                                            )),
                                            validator:
                                                FormBuilderValidators.required(
                                                    errorText:
                                                        "This field is required"),
                                          )
                                        : 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;
                                                  } else {
                                                    isPrivate = false;
                                                  }
                                                });
                                              },
                      
                                              name: 'isPrivate',
                                              validator:
                                                  FormBuilderValidators.required(
                                                      errorText:
                                                          "This field is required"),
                                              options: ["YES", "NO"]
                                                  .map((lang) =>
                                                      FormBuilderFieldOption(
                                                          value: lang))
                                                  .toList(growable: false),
                                            )
                                          : const SizedBox()),
                                ],
                              );
                            }),
                            ////SHOW CATEGORY AGENCY
                      
                            const SizedBox(
                              height: 24,
                            ),
                            SizedBox(
                              height: 60,
                              width: double.infinity,
                              child: ElevatedButton(
                                  style: mainBtnStyle(
                                      primary, Colors.transparent, second),
                                  onPressed: () {
                                    if (_formKey.currentState!.saveAndValidate()) {
                                      if (selectedAgency?.privateEntity != null) {
                                        newAgency = selectedAgency;
                                      } else {
                                        newAgency = Agency(
                                            id: selectedAgency?.id,
                                            name: selectedAgency!.name,
                                            category: selectedCategory,
                                            privateEntity: isPrivate);
                                      }
                                      final progress = ProgressHUD.of(context);
                                      progress!.showWithText("Loading...");
                                      context
                                          .read<OrganizationMembershipBloc>()
                                          .add(AddOrgMembership(
                                              agency: newAgency!,
                                              profileId: widget.profileId,
                                              token: widget.token));
                                      setState(() {
                                        showAgencyCategory = false;
                                        showIsPrivateRadio = false;
                                      });
                                    }
                                  },
                                  child: const Text(submit)),
                            )
                          ]),
                    )),
              ),
            ),
          );
        }
        return Container();
      },
    );
  }
}
