import 'package:app_popup_menu/app_popup_menu.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:flutter_spinkit/flutter_spinkit.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:searchfield/searchfield.dart';
import 'package:unit2/bloc/rbac/rbac_operations/role/role_bloc.dart';
import 'package:unit2/bloc/rbac/rbac_operations/station/station_bloc.dart';
import 'package:unit2/model/rbac/rbac_station.dart';
import 'package:unit2/screens/superadmin/role/shared_pop_up_menu.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/error_state.dart';
import '../../../model/utils/agency.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/alerts.dart';
import '../../../utils/formatters.dart';
import '../../../utils/global.dart';
import '../../../widgets/empty_data.dart';

class RbacStationScreen extends StatelessWidget {
  final int id;
  const RbacStationScreen({super.key, required this.id});

  @override
  Widget build(BuildContext context) {
    final agencyFocusNode = FocusNode();
    List<RbacStation> stations = [];
    final formKey = GlobalKey<FormBuilderState>();
    Agency selectedAgency;
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: primary,
        title: const Text("Station Screen"),
        actions: [
          AddLeading(onPressed: () {
            BuildContext parent = context;
            showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: const Text("Add New Station"),
                    content: FormBuilder(
                      key: formKey,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          FormBuilderTextField(
                            name: "object_name",
                            decoration: normalTextFieldStyle(
                                "Role name *", "Role name "),
                            validator: FormBuilderValidators.required(
                                errorText: "This field is required"),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          FormBuilderTextField(
                            name: "slug",
                            decoration: normalTextFieldStyle("Slug ", "Slug"),
                          ),
                          const SizedBox(
                            height: 8,
                          ),
                          FormBuilderTextField(
                            validator: FormBuilderValidators.maxLength(50,
                                errorText: "Max characters only 50"),
                            name: "shorthand",
                            decoration:
                                normalTextFieldStyle("Shorthand ", "Shorthand"),
                          ),
                          const SizedBox(
                            height: 12,
                          ),
                          SizedBox(
                              width: double.infinity,
                              height: 50,
                              child: ElevatedButton(
                                  style: mainBtnStyle(
                                      primary, Colors.transparent, second),
                                  onPressed: () {
                                    if (formKey.currentState!
                                        .saveAndValidate()) {
                                      String name = formKey
                                          .currentState!.value['object_name'];
                                      String? slug =
                                          formKey.currentState!.value['slug'];
                                      String? short = formKey
                                          .currentState!.value['shorthand'];
                                      parent.read<RoleBloc>().add(AddRbacRole(
                                          id: id,
                                          name: name,
                                          shorthand: short,
                                          slug: slug));
                                      Navigator.pop(context);
                                    }
                                  },
                                  child: const Text("Add"))),
                        ],
                      ),
                    ),
                  );
                });
          })
        ],
      ),
      body: ProgressHUD(
        padding: const EdgeInsets.all(24),
        backgroundColor: Colors.black87,
        indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
        child: BlocConsumer<StationBloc, StationState>(
          listener: (context, state) {},
          builder: (context, state) {
            final parent = context;
            if (state is StationLoadedState) {
              stations = state.stations;
              if (state.stations.isNotEmpty) {
                return Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8),
                      child: SearchField(
                          inputFormatters: [UpperCaseTextFormatter()],
                          itemHeight: 70,
                          focusNode: agencyFocusNode,
                          suggestions: state.agencies
                              .map((Agency agency) =>
                                  SearchFieldListItem(agency.name!,
                                      item: agency,
                                      child: ListTile(
                                        title: Text(
                                          agency.name!,
                                          overflow: TextOverflow.visible,
                                        ),
                                      )))
                              .toList(),
                          searchInputDecoration:
                              normalTextFieldStyle("Filter", "").copyWith(
                                  prefixIcon: const Icon(Icons.filter_list),
                                  suffixIcon: IconButton(
                                    icon: const Icon(Icons.arrow_drop_down),
                                    onPressed: () {
                                      agencyFocusNode.unfocus();
                                    },
                                  )),
                          onSuggestionTap: (agency) {
                            agencyFocusNode.unfocus();
                            selectedAgency = agency.item!;
                            parent.read<StationBloc>().add(
                                FilterStation(agencyId: selectedAgency.id!));
                          },
                          validator: (agency) {
                            if (agency!.isEmpty) {
                              return "This field is required";
                            }
                            return null;
                          },
                          emptyWidget: const Center(
                            child: Text("No result found..."),
                          )),
                    ),
                    Expanded(
                      child: ListView.builder(
                          padding: const EdgeInsets.symmetric(
                              vertical: 8, horizontal: 10),
                          itemCount: state.stations.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Column(
                              children: [
                                Container(
                                  width: screenWidth,
                                  decoration: box1(),
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 12, vertical: 8),
                                  child: Row(
                                    children: [
                                      Expanded(
                                          child: Row(
                                        children: [
                                          CircleAvatar(
                                            child: Text('${index + 1}'),
                                          ),
                                          const SizedBox(
                                            width: 12,
                                          ),
                                          Flexible(
                                            child: Text(
                                                state.stations[index]
                                                    .stationName!,
                                                style: Theme.of(context)
                                                    .textTheme
                                                    .titleMedium!
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w500,
                                                        color: primary)),
                                          ),
                                        ],
                                      )),
                                    ],
                                  ),
                                ),
                                const SizedBox(
                                  height: 3,
                                )
                              ],
                            );
                          }),
                    ),
                  ],
                );
              } else {
                return Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(8),
                      child: SearchField(
                  
                          inputFormatters: [UpperCaseTextFormatter()],
                          itemHeight: 70,
                          focusNode: agencyFocusNode,
                          suggestions: state.agencies
                              .map((Agency agency) =>
                                  SearchFieldListItem(agency.name!,
                                      item: agency,
                                      child: ListTile(
                                        title: Text(
                                          agency.name!,
                                          overflow: TextOverflow.visible,
                                        ),
                                      )))
                              .toList(),
                          searchInputDecoration:
                              normalTextFieldStyle("Filter", "").copyWith(
                                  prefixIcon: const Icon(Icons.filter_list),
                                  suffixIcon: IconButton(
                                    icon: const Icon(Icons.arrow_drop_down),
                                    onPressed: () {
                                      agencyFocusNode.unfocus();
                                    },
                                  )),
                          onSuggestionTap: (agency) {
                            agencyFocusNode.unfocus();
                            selectedAgency = agency.item!;
                            parent.read<StationBloc>().add(
                                FilterStation(agencyId: selectedAgency.id!));
                          },
                          validator: (agency) {
                            if (agency!.isEmpty) {
                              return "This field is required";
                            }
                            return null;
                          },
                          emptyWidget: const Center(
                            child: Text("No result found..."),
                          )),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    const EmptyData(
                        message:
                            "No Station available. Please click + to add."),
                  ],
                );
              }
            }
            if (state is StationErrorState) {
              return SomethingWentWrong(
                  message: state.message,
                  onpressed: () {
                    context.read<RoleBloc>().add(GetRoles());
                  });
            }
            if (state is StationLoadingState) {
              return CircularProgressIndicator();
            }
            return Container();
          },
        ),
      ),
    );
  }
}
