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/passo/barangay/barangay_bloc.dart';
import 'package:unit2/bloc/passo/bulding/additional_item/additional_item_bloc.dart';
import 'package:unit2/bloc/passo/bulding/additional_items_edit/additional_items_edit_bloc.dart';
import 'package:unit2/bloc/passo/bulding/class_components/class_components_bloc.dart';
import 'package:unit2/bloc/passo/bulding/general_description/general_description_bloc.dart';
import 'package:unit2/bloc/passo/bulding/landref/landref_bloc.dart';
import 'package:unit2/bloc/passo/bulding/location/location_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_appraisal_edit/property_appraisal_edit_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_assessment_edit/property_assessment_edit_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_info/property_info_bloc.dart';
import 'package:unit2/bloc/passo/bulding/structural_material/structural_material_bloc.dart';
import 'package:unit2/bloc/passo/bulding/unit_construct/unit_construct_bloc.dart';
import 'package:unit2/bloc/passo/land/land_appraisal/land_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/land/land_classification/land_classification_bloc.dart';
import 'package:unit2/bloc/passo/land/land_ext/land_ext_bloc.dart';
import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart';
import 'package:unit2/bloc/passo/land/land_property_owner_info/land_property_owner_info_bloc.dart';
import 'package:unit2/bloc/passo/land/land_subclassification/land_subclassification_bloc.dart';
import 'package:unit2/bloc/passo/land/land_trees_improvements/land_trees_improvements_bloc.dart';
import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart';
import 'package:unit2/bloc/passo/land/other_improvements/other_improvements_bloc.dart';
import 'package:unit2/bloc/passo/land/type_of_location/type_of_location_bloc.dart';
import 'package:unit2/bloc/passo/land/type_of_road/type_of_road_bloc.dart';

import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart';
import 'package:unit2/bloc/passo/municipality/municipality_bloc.dart';

import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart';

import 'package:unit2/bloc/user/user_bloc.dart';
import 'package:unit2/model/passo/additional_items.dart';
import 'package:unit2/model/passo/general_description.dart';
import 'package:unit2/model/passo/land_ref.dart';
import 'package:unit2/model/passo/property_appraisal.dart';
import 'package:unit2/model/passo/property_appraisal_edit.dart';
import 'package:unit2/model/passo/property_assessment_edit.dart';
import 'package:unit2/model/passo/property_info.dart';
import 'package:unit2/model/passo/structural_materials_ii.dart';
import 'package:unit2/model/passo/structureMaterial.dart';
import 'package:unit2/model/profile/basic_information/primary-information.dart';
import 'package:unit2/screens/passo/Building/add_building.dart';
import 'package:unit2/screens/passo/Building/edit_building.dart';
import 'package:unit2/screens/passo/Land/add_land.dart';
import 'package:unit2/screens/passo/Test%20Envi/multi_dropdown.dart';
import 'package:unit2/screens/passo/Test%20Envi/speed_dial.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/global_context.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

import '../../model/passo/bldg_loc.dart';
import '../../utils/alerts.dart';

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

  @override
  Widget build(BuildContext context) {
    int? profileId;
    String? token;
    Profile profile;

    void deleteItem(int itemId) {
      context.read<PropertyInfoBloc>().add(DeleteBuildingFaas(id: itemId));
    }

    return Scaffold(
      body: ProgressHUD(
          backgroundColor: Colors.black87,
          indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
          child: BlocBuilder<UserBloc, UserState>(builder: (context, state) {
            if (state is UserLoggedIn) {
              profileId = state.userData!.user!.login!.user!.profileId;
              token = state.userData!.user!.login!.token!;
              profile = state.userData!.employeeInfo!.profile!;
              return BlocConsumer<PropertyInfoBloc, PropertyInfoState>(
                listener: (
                  context,
                  state,
                ) {
                  if (state is PropertyInfoLoading) {
                    final progress = ProgressHUD.of(context);
                    progress!.showWithText("Please wait...");
                  }
                  if (state is PropertyInfoLoaded) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                  }
                  if (state is PropertyInfoErrorState) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                  }
                },
                builder: (context, state) {
                  if (state is PropertyInfoLoaded) {
                    List<PropertyInfo> propertyList = state.property_info;
                    return Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      child: Column(
                        children: [
                          Expanded(
                            child: ListView.builder(
                              shrinkWrap: true,
                              itemCount: propertyList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return _listCard(propertyList[index], context,
                                    index, deleteItem);
                              },
                            ),
                          ),
                        ],
                      ),
                    );
                  }
                  if (state is PropertyInfoErrorState) {
                    return SomethingWentWrong(
                      message: onError,
                      onpressed: () {
                        context
                            .read<PropertyInfoBloc>()
                            .add(LoadPropertyInfo());
                      },
                    );
                  }
                  if (state is BuildingFaasDeletedState) {
                    if (state.success) {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        successAlert(context, "Deletion Successful",
                            "Building FAAS Data has been deleted successfully",
                            () {
                          Navigator.of(context).pop();
                          context
                              .read<PropertyInfoBloc>()
                              .add(const LoadPropertyInfo());
                        });
                      });
                    }
                  }
                  return Container();
                },
              );
            }
            return Container();
          })),
      floatingActionButton: SpeedDial(

//provide here features of your parent FAB
          icon: Icons.add,
          backgroundColor: primary,
          heroTag: null,
          useRotationAnimation: true,
          activeIcon: Icons.close,
          animationCurve: Curves.elasticInOut,
          children: [
            SpeedDialChild(
                child: const Icon(
                  Icons.maps_home_work_rounded,
                  color: primary,
                ),
                label: 'Building & Other Structure',
                onTap: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (BuildContext context) {
                    return MultiBlocProvider(providers: [
                      BlocProvider(
                        create: (context) =>
                            PropertyInfoBloc()..add(LoadPropertyInfo()),
                      ),
                      BlocProvider(
                        create: (context) =>
                            ClassComponentsBloc()..add(LoadClassComponents()),
                      ),
                      BlocProvider(
                        create: (context) =>
                            UnitConstructBloc()..add(LoadUnitConstruct()),
                      ),
                      BlocProvider(
                        create: (context) =>
                            AdditionalItemBloc()..add(LoadAdditionalItems()),
                      ),
                      BlocProvider(
                        create: (context) => PropertyAppraisalBloc()
                          ..add(LoadPropertyAppraisal(
                              appraisal: PropertyAppraisal())),
                      ),
                      BlocProvider(
                          create: (context) => PropertyAssessmentBloc()
                            ..add(LoadPropertyAssessment())),
                      BlocProvider(
                          create: (context) =>
                              SignatoriesBloc()..add(LoadSignatories())),
                      BlocProvider(
                          create: (context) =>
                              MunicipalityBloc()..add(LoadMunicipality())),
                      BlocProvider(
                          create: (context) =>
                              BarangayBloc()..add(LoadBarangay(id: '01'))),
                      BlocProvider(
                          create: (context) =>
                              MemorandaBloc()..add(LoadMemoranda())),
                    ], child: AddBuilding());
                  }));
                }),
            SpeedDialChild(
              child: const Icon(
                Icons.forest_rounded,
                color: primary,
              ),
              label: 'Land/Other Improvements',
              onTap: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (BuildContext context) {
                  return MultiBlocProvider(providers: [
                    BlocProvider(
                        create: (context) =>
                            LandPropertyOwnerInfoBloc()..add(LoadLand())),
                    BlocProvider(
                        create: (context) => LandClassificationBloc()
                          ..add(LoadLandClassification())),
                    BlocProvider(
                        create: (context) => LandSubClassificationBloc()
                          ..add(LoadLandSubClassification(
                              cityCode: "1", classCode: 1))),
                    BlocProvider(
                        create: (context) =>
                            LandAppraisalBloc()..add(LoadLandAppraisal())),
                    BlocProvider(
                        create: (context) =>
                            MunicipalityBloc()..add(LoadMunicipality())),
                    BlocProvider(
                        create: (context) =>
                            BarangayBloc()..add(LoadBarangay(id: '01'))),
                    BlocProvider(
                        create: (context) => OtherImprovementsBloc()
                          ..add(LoadOtherImprovement())),
                    BlocProvider(
                        create: (context) => LandTreesImprovementsBloc()
                          ..add(LoadLandTreesImprovements())),
                    BlocProvider(
                        create: (context) => LandValueAdjustmentsBloc()
                          ..add(LoadLandValueAdjustments())),
                    BlocProvider(
                        create: (context) =>
                            TypeOfLocationBloc()..add(LoadTypeOfLocation())),
                    BlocProvider(
                        create: (context) =>
                            TypeOfRoadBloc()..add(LoadTypeOfRoad())),
                    BlocProvider(
                        create: (context) => LandPropertyAssessmentBloc()
                          ..add(LoadLandPropertyAssessment())),
                    BlocProvider(
                        create: (context) =>
                            SignatoriesBloc()..add(LoadSignatories())),
                    BlocProvider(
                        create: (context) => LandExtBloc()..add(LoadLandExt())),
                    BlocProvider(
                        create: (context) =>
                            MemorandaBloc()..add(LoadMemoranda())),
                  ], child: AddLand());
                }));
              },
            ),
            SpeedDialChild(
              child: const Icon(
                Icons.precision_manufacturing_rounded,
                color: primary,
              ),
              label: 'Machinery',
              onTap: () {},
            ),
            // SpeedDialChild(
            //   child: const Icon(
            //     Icons.report_problem_rounded,
            //     color: primary,
            //   ),
            //   label: 'Testing Screen',
            //   onTap: () {
            //     Navigator.of(context)
            //         .push(MaterialPageRoute(builder: (ctx) => Multi_Select()));
            //   },
            // ),
          ]),
    );
  }
}

Card _listCard(PropertyInfo property_info, context, index, deleteItem) {
  return Card(
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(10),
      //set border radius more than 50% of height and width to make circle
    ),
    margin: const EdgeInsets.all(5.0),
    elevation: 5,
    shadowColor: Colors.grey,
    child: Padding(
      padding: const EdgeInsets.all(15.0),
      child: InkWell(
        onTap: () async {
          Navigator.push(context,
              MaterialPageRoute(builder: (BuildContext context) {
            return MultiBlocProvider(
              providers: [
                BlocProvider(
                  create: (context) =>
                      PropertyInfoBloc()..add(LoadPropertyInfo()),
                ),
                BlocProvider(
                  create: (context) =>
                      UnitConstructBloc()..add(LoadUnitConstruct()),
                ),
                BlocProvider(
                  create: (context) =>
                      ClassComponentsBloc()..add(LoadClassComponents()),
                ),
                BlocProvider(
                    create: (context) =>
                        SignatoriesBloc()..add(LoadSignatories())),
                BlocProvider(
                  create: (context) => LocationBloc()
                    ..add(
                        LoadLocation(bldgloc: BldgLoc(), id: property_info.id)),
                ),
                BlocProvider(
                  create: (context) => LandrefBloc()
                    ..add(
                        LoadLandref(landRef: LandRef(), id: property_info.id)),
                ),
                BlocProvider(
                  create: (context) => GeneralDescriptionBloc()
                    ..add(LoadGenDesc(
                        gendesc: GeneralDesc(), id: property_info.id)),
                ),
                BlocProvider(
                  create: (context) => AdditionalItemsEditBloc()
                    ..add(LoadAdditionalItemsEdit(
                        items: const <AdditionalItems>[],
                        id: property_info.id)),
                ),
                BlocProvider(
                  create: (context) => PropertyAssessmentEditBloc()
                    ..add(LoadPropertyAssessmentEdit(
                        assessmentsEdit: PropertyAssessmentEdit(),
                        id: property_info.id)),
                ),
                BlocProvider(
                  create: (context) => PropertyAppraisalEditBloc()
                    ..add(LoadPropertyAppraisalEdit(
                        appraisalEdit: PropertyAppraisalEdit(),
                        id: property_info.id)),
                ),
                BlocProvider(
                    create: (context) =>
                        MunicipalityBloc()..add(LoadMunicipality())),
                BlocProvider(
                    create: (context) =>
                        BarangayBloc()..add(LoadBarangay(id: '01'))),
                BlocProvider(
                    create: (context) => MemorandaBloc()..add(LoadMemoranda())),
                BlocProvider(
                    create: (context) => StructuralMaterialBloc()
                      ..add(LoadStructuralMaterial(
                          structure: StructureMaterials(),
                          id: property_info.id))),
              ],
              child: EditBuilding(
                index: index,
                faas: property_info,
                title: 'Bldg & Structure Edit',
              ),
            );
          }));
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              width: 40, // Adjust this to your desired size
              height: 40, // Adjust this to your desired size
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: primary, // Border color
                  width: 2, // Border width
                ),
              ),
              child: Icon(
                Icons.maps_home_work_rounded,
                color: primary, // Icon color
              ),
            ),
            SizedBox(
              width: 20,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${property_info.owner}',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                    textAlign: TextAlign.left,
                  ),
                  SizedBox(height: 5),
                  Text(
                    '${property_info.tdn}',
                    style: TextStyle(
                      fontSize: 13,
                    ),
                    textAlign: TextAlign.left,
                  ),
                ],
              ),
            ),
            IconButton(
              onPressed: () {
                deleteItem(property_info.id);
              },
              icon: const Icon(Icons.delete_rounded),
              color: primary,
            ),
          ],
        ),
      ),
    ),
  );
}
