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/class_components/class_components_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_appraisal/property_appraisal_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_assessment/property_assessment_bloc.dart';
import 'package:unit2/bloc/passo/bulding/property_info/property_info_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_boundaries_edit/land_boundaries_edit_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_ext_bloc/land_ext_edit_bloc.dart';
import 'package:unit2/bloc/passo/land/land_location_edit/land_location_edit_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/land_appr.dart';
import 'package:unit2/model/passo/land_ext.dart';
import 'package:unit2/model/passo/land_property_assessment.dart';
import 'package:unit2/model/passo/land_property_boundaries.dart';
import 'package:unit2/model/passo/land_property_loc.dart';
import 'package:unit2/model/passo/land_property_owner.dart';
import 'package:unit2/model/passo/land_value_adjustment.dart';
import 'package:unit2/model/passo/other_improvements.dart';
import 'package:unit2/model/passo/property_appraisal.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/Land/add_land.dart';
import 'package:unit2/screens/passo/Land/edit_land.dart';
import 'package:unit2/theme-data.dart/colors.dart';
import 'package:unit2/utils/alerts.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/error_state.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

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

  @override
  Widget build(BuildContext context) {
    void deleteItem(int itemId) {
      context.read<LandPropertyOwnerInfoBloc>().add(DeleteLandFaas(id: itemId));
    }

    void triggerBlocEvent() {
      final myBloc = BlocProvider.of<PropertyInfoBloc>(context);
      myBloc.add(LoadPropertyInfo());
    }

    int? profileId;
    String? token;
    Profile profile;
    return Scaffold(
      body: ProgressHUD(
          padding: const EdgeInsets.only(left: 24, right: 24),
          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<LandPropertyOwnerInfoBloc,
                  LandPropertyOwnerInfoState>(
                listener: (
                  context,
                  state,
                ) {
                  if (state is LandLoading) {
                    final progress = ProgressHUD.of(context);
                    progress!.showWithText("Please wait...");
                  }
                  if (state is LandLoaded || state is LandErrorState) {
                    final progress = ProgressHUD.of(context);
                    progress?.dismiss();
                  }
                },
                builder: (context, state) {
                  if (state is LandLoaded) {
                    if (state.land.isNotEmpty) {
                      List<LandPropertyOwner> propertyList = state.land;
                      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);
                                },
                              ),
                            ),
                          ],
                        ),
                      );
                    } else {
                      return const EmptyData(
                          message:
                              "You don't have any land faas added. Please click + to add");
                    }
                  }
                  if (state is LandErrorState) {
                    return SomethingWentWrong(
                      message: onError,
                      onpressed: () {
                        context
                            .read<LandPropertyOwnerInfoBloc>()
                            .add(const LoadLand());
                      },
                    );
                  }

                  if (state is LandFaasDeletedState) {
                    if (state.success) {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        successAlert(context, "Deletion Successful",
                            "Land FAAS Data has been deleted successfully", () {
                          Navigator.of(context).pop();
                          context
                              .read<LandPropertyOwnerInfoBloc>()
                              .add(const LoadLand());
                        });
                      });
                    }
                  }
                  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(triggerBlocEvent));
                  }));
                }),
            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(LandPropertyOwner 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) =>
                        LandPropertyOwnerInfoBloc()..add(LoadLand())),
                BlocProvider(
                    create: (context) => LandLocationEditBloc()
                      ..add(LoadLandLocationEdit(
                          land_loc_edit: LandPropertyLoc(),
                          id: property_info.id))),
                BlocProvider(
                    create: (context) => LandExtEditBloc()
                      ..add(LoadLandExtEdit(
                          land_ext_edit: LandExt(), id: property_info.id))),
                BlocProvider(
                    create: (context) => LandBoundariesEditBloc()
                      ..add(LoadLandBoundariesEdit(
                          land_boundaries_edit: LandPropertyBoundaries(),
                          id: property_info.id))),
                BlocProvider(
                    create: (context) => LandAppraisalBloc()
                      ..add(LoadLandAppraisalEdit(
                          land_appr: const <LandAppr>[],
                          id: property_info.id!))),
                BlocProvider(
                    create: (context) => LandClassificationBloc()
                      ..add(LoadLandClassification())),
                BlocProvider(
                    create: (context) => LandSubClassificationBloc()
                      ..add(LoadLandSubClassification(
                          cityCode: "1", classCode: 1))),
                BlocProvider(
                    create: (context) => OtherImprovementsBloc()
                      ..add(LoadOtherImprovementEdit(
                          other_imps: const <OtherImprovements>[],
                          ids: property_info.id!))),
                BlocProvider(
                    create: (context) =>
                        TypeOfLocationBloc()..add(LoadTypeOfLocation())),
                BlocProvider(
                    create: (context) =>
                        TypeOfRoadBloc()..add(LoadTypeOfRoad())),
                BlocProvider(
                    create: (context) => LandPropertyAssessmentBloc()
                      ..add(LoadLandPropertyAssessmentEdit(
                          assessment: <LandPropertyAssessment>[],
                          id: property_info.id!))),
                BlocProvider(
                    create: (context) => LandTreesImprovementsBloc()
                      ..add(LoadLandTreesImprovements())),
                BlocProvider(
                    create: (context) => LandExtBloc()..add(LoadLandExt())),
                BlocProvider(
                    create: (context) => LandValueAdjustmentsBloc()
                      ..add(LoadLandValueAdjustmentsEdit(
                          val_adj: <ValueAdjustments>[],
                          id: property_info.id!))),
                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: EditLand(
                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.forest_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,
            ),
          ],
        ),
      ),
    ),
  );
}
