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:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/type_of_location/type_of_location_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/type_of_road/type_of_road_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/land/land_property_appraisal/land_property_appraisal_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/land/value_adjustment/value_adjustment_bloc.dart';

import '../../../../../model/passo/land_appr.dart';
import '../../../../../model/passo/type_of_location.dart';
import '../../../../../model/passo/type_of_road.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../utils/text_container.dart';
import '../../../../../widgets/error_state.dart';

class AddLandValueAdjustmentEditOfflineModal extends StatefulWidget {
  // final List<UnitConstruct> unit;
  // final List<ClassComponents> options;
  // final int tempId;

  // AddLandAppraisalModal(this.unit, this.options, this.tempId);

  @override
  _AddLandValueAdjustmentEditOfflineModal createState() =>
      _AddLandValueAdjustmentEditOfflineModal();
}

class _AddLandValueAdjustmentEditOfflineModal
    extends State<AddLandValueAdjustmentEditOfflineModal> {
  final focus = FocusNode();
  bool isPainted = false;
  bool isSecondHand = false;
  TextEditingController textEditingController = TextEditingController();
  double _unitBase = 0;
  int _areaValue = 0;
  final double _depValue = 0;
  double _unitValue = 0;
  String _subClassDesc = "";
  int _classId = 0;
  String _structureType = "";
  int _notPaintedUnitVal = 0;
  int _secondHandUnitVal = 0;
  String cityCode = '';
  String cityDesc = '';
  int classCode = 1;
  String _classDesc = '';
  String _treeType = "";
  bool _nonfruitBearing = false;
  bool _fruitBearing = false;
  int qty = 0;
  int pr_qty = 0;
  int nonpr_qty = 0;
  double _roadTypeDeduction = 0;
  double _locTypeRoad = 0;
  double _locTypePob = 0;
  String _roadType = '';
  String _distance = '';
  String _locRdDistance = '';
  String _locPobDistance = '';

  GlobalKey<FormBuilderState> otherImpKey = GlobalKey<FormBuilderState>();

  _calculateBaseMarketValue() {
    double base = 0.00;
    if (_fruitBearing) {
      base = (pr_qty + nonpr_qty) * _unitValue;
    } else {
      base = qty * _unitValue;
    }
    return base;
  }

  double calculateAdjustment() {
    double adjustment = 0;

    if (_locPobDistance == '0 TO 1') {
      adjustment = _locTypePob - (_roadTypeDeduction + _locTypeRoad);
    } else {
      adjustment = (_roadTypeDeduction + _locTypeRoad + _locTypePob) * -1;
    }

    return adjustment;
  }

  double calculateValueAdjustment() {
    double adjustment = calculateAdjustment();
    double valueAdjustment = _unitValue * adjustment;

    return valueAdjustment;
  }

  double calculateMarketValue() {
    double marketValue = 0;

    marketValue = _unitValue + calculateValueAdjustment(); // Adding adjustment

    return marketValue;
  }

  BoxDecoration box1() {
    return const BoxDecoration(boxShadow: [
      BoxShadow(color: Colors.black12, spreadRadius: 5, blurRadius: 5)
    ], color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(3)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProgressHUD(
        padding: const EdgeInsets.all(24),
        backgroundColor: Colors.black87,
        indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
        child: BlocBuilder<ValueAdjustmentBloc, ValueAdjustmentState>(
            buildWhen: (previous, current) {
          return false;
        }, builder: (context, state) {
          if (state is ShowValueAdjustmentcreen) {
            return BlocConsumer<LandPropertyAppraisalBloc,
                LandPropertyAppraisalState>(listener: (context, state) {
              // TODO: implement listener
            }, builder: (context, state) {
              if (state is LandPropertyAppraisalLoaded) {
                final land_appr = state.landAppr;
                return BlocConsumer<TypeOfRoadBloc, TypeOfRoadState>(
                  listener: (context, state) {
                    // TODO: implement listener
                  },
                  builder: (context, state) {
                    if (state is TypeOfRoadLoaded) {
                      final roadType = state.typeOfRoad;
                      return BlocConsumer<TypeOfLocationBloc,
                          TypeOfLocationState>(
                        listener: (context, state) {
                          // TODO: implement listener
                        },
                        builder: (context, state) {
                          if (state is TypeOfLocationLoaded) {
                            return FormBuilder(
                                key: otherImpKey,
                                onChanged: () {
                                  otherImpKey.currentState?.save();
                                },
                                autovalidateMode: AutovalidateMode.disabled,
                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Container(
                                    child: SingleChildScrollView(
                                      padding: const EdgeInsets.all(8.0),
                                      child: Column(
                                        mainAxisAlignment:
                                            MainAxisAlignment.start,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisSize: MainAxisSize.min,
                                        children: <Widget>[
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child: FormBuilderDropdown<
                                                    LandAppr?>(
                                                  name: 'land_appr_item',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          "Land Appraisal Items",
                                                          ""),
                                                  items: land_appr
                                                      .map((land_appr) =>
                                                          DropdownMenuItem<
                                                              LandAppr?>(
                                                            value: land_appr,
                                                            child: Text((land_appr
                                                                    .subClass ??
                                                                "")),
                                                          ))
                                                      .toList(),
                                                  onChanged:
                                                      (selectedLandAppr) {
                                                    if (selectedLandAppr !=
                                                        null) {
                                                      setState(() {
                                                        _unitValue = double.parse(
                                                            selectedLandAppr
                                                                .baseMarketval!);
                                                      });
                                                    }
                                                  },
                                                )),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          ),
                                          Text("Adjustment Factors"),
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child: FormBuilderDropdown<
                                                    TypeOfRoad?>(
                                                  name: 'road_type',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          "Type of Road", ""),
                                                  items: roadType
                                                      .map((roadType) =>
                                                          DropdownMenuItem<
                                                              TypeOfRoad?>(
                                                            value: roadType,
                                                            child: Text((roadType
                                                                    .roadType ??
                                                                "")),
                                                          ))
                                                      .toList(),
                                                  onChanged: (selectedRoad) {
                                                    if (selectedRoad != null) {
                                                      setState(() {
                                                        _roadTypeDeduction =
                                                            double.parse(
                                                                selectedRoad
                                                                    .deduction!);
                                                        _roadType = selectedRoad
                                                            .roadType!;
                                                      });
                                                    }
                                                  },
                                                )),
                                          ),
                                          SizedBox(
                                            height: 10,
                                          ),
                                          Text("Type of Location"),
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child: FormBuilderDropdown<
                                                    TypeOfLocation?>(
                                                  name: 'loc_type_road',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          "Distance to Road",
                                                          ""),
                                                  items: state.typeOfLocation
                                                      .map((locTypeRoad) =>
                                                          DropdownMenuItem<
                                                              TypeOfLocation?>(
                                                            value: locTypeRoad,
                                                            child: Text((locTypeRoad
                                                                    .distanceKm ??
                                                                "")),
                                                          ))
                                                      .toList(),
                                                  onChanged:
                                                      (selectedLoadRoad) {
                                                    if (selectedLoadRoad !=
                                                        null) {
                                                      setState(() {
                                                        _locTypeRoad = double
                                                            .parse(selectedLoadRoad
                                                                .allRoadTypes!);
                                                        _locRdDistance =
                                                            selectedLoadRoad
                                                                .distanceKm!;
                                                      });
                                                    }
                                                  },
                                                )),
                                          ),
                                          Container(
                                            margin: const EdgeInsets.only(
                                                left: 0,
                                                top: 10,
                                                right: 0,
                                                bottom: 0),
                                            child: Expanded(
                                                flex: 1,
                                                child: FormBuilderDropdown<
                                                    TypeOfLocation?>(
                                                  name: 'loc_type_pob',
                                                  autofocus: false,
                                                  decoration:
                                                      normalTextFieldStyle(
                                                          "Distance to Poblacion",
                                                          ""),
                                                  items: state.typeOfLocation
                                                      .map((locTypePob) =>
                                                          DropdownMenuItem<
                                                              TypeOfLocation?>(
                                                            value: locTypePob,
                                                            child: Text((locTypePob
                                                                    .distanceKm ??
                                                                "")),
                                                          ))
                                                      .toList(),
                                                  onChanged: (selectedLocPob) {
                                                    if (selectedLocPob !=
                                                        null) {
                                                      setState(() {
                                                        _locTypePob = double
                                                            .parse(selectedLocPob
                                                                .localTradingCenter!);

                                                        _locPobDistance =
                                                            selectedLocPob
                                                                .distanceKm!;
                                                      });
                                                    }
                                                  },
                                                )),
                                          ),
                                          const SizedBox(height: 10),
                                          Container(
                                            height: 45.0,
                                            width: double.infinity,
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              border: Border.all(
                                                color: Colors.grey,
                                                width: 1.0,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(5.0),
                                            ),
                                            child: Align(
                                              alignment: Alignment.center,
                                              child: Text(
                                                  (calculateAdjustment() * 100)
                                                          .toString() +
                                                      '%'),
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Container(
                                            height: 45.0,
                                            width: double.infinity,
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              border: Border.all(
                                                color: Colors.grey,
                                                width: 1.0,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(5.0),
                                            ),
                                            child: Align(
                                              alignment: Alignment.center,
                                              child: Text(NumberFormat.currency(
                                                locale: 'en-PH',
                                                symbol: "₱",
                                              ).format(
                                                  calculateValueAdjustment())),
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Container(
                                            height: 45.0,
                                            width: double.infinity,
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              border: Border.all(
                                                color: Colors.grey,
                                                width: 1.0,
                                              ),
                                              borderRadius:
                                                  BorderRadius.circular(5.0),
                                            ),
                                            child: Align(
                                              alignment: Alignment.center,
                                              child: Text(NumberFormat.currency(
                                                locale: 'en-PH',
                                                symbol: "₱",
                                              ).format(calculateMarketValue())),
                                            ),
                                          ),
                                          const SizedBox(height: 10),
                                          Row(
                                            children: [
                                              Container(
                                                width: 120,
                                                height: 60,
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: () async {
                                                    final tempID =
                                                        await SharedPreferences
                                                            .getInstance();
                                                    print(tempID
                                                        .getInt('landid'));

                                                    context.read<ValueAdjustmentBloc>().add(AddValueAdjustments(
                                                        landapprDetailsId:
                                                            tempID.getInt(
                                                                    'landid')! -
                                                                1,
                                                        baseMarketval:
                                                            _unitValue
                                                                .toString(),
                                                        adjustmentFactors: _roadType +
                                                            ' , ' +
                                                            _locPobDistance +
                                                            ' km from road , ' +
                                                            _locPobDistance +
                                                            ' km from poblacion',
                                                        adjustment:
                                                            calculateAdjustment()
                                                                .toString(),
                                                        valueAdjustment:
                                                            calculateValueAdjustment()
                                                                .toString(),
                                                        marketValue:
                                                            calculateMarketValue()
                                                                .toString()));
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        Colors.black,
                                                  ),
                                                  child: const Text("Submit"),
                                                ),
                                              ),
                                              const SizedBox(
                                                  width:
                                                      5), // Use SizedBox for horizontal spacing in a Row
                                              Container(
                                                width: 120,
                                                height: 60,
                                                padding:
                                                    const EdgeInsets.all(8.0),
                                                child: ElevatedButton(
                                                  onPressed: () {
                                                    context
                                                        .read<
                                                            ValueAdjustmentBloc>()
                                                        .add(
                                                            const LoadValueAdjustment());
                                                  },
                                                  style:
                                                      ElevatedButton.styleFrom(
                                                    backgroundColor:
                                                        Colors.black,
                                                  ),
                                                  child: const Text("Cancel"),
                                                ),
                                              ),
                                            ],
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ));
                          }
                          if (state is TypeOfLocationState) {
                            return SomethingWentWrong(
                              message: onError,
                              onpressed: () {
                                context
                                    .read<TypeOfLocationBloc>()
                                    .add(LoadTypeOfLocation());
                              },
                            );
                          }
                          return Container();
                        },
                      );
                    }
                    if (state is LandPropertyAppraisalErrorState) {
                      return SomethingWentWrong(
                        message: onError,
                        onpressed: () {
                          context
                              .read<LandPropertyAppraisalBloc>()
                              .add(LoadLandPropertyAppraisal());
                        },
                      );
                    }
                    return Container();
                  },
                );
              }
              if (state is ValueAdjustmentErrorState) {
                return SomethingWentWrong(
                  message: onError,
                  onpressed: () {
                    context
                        .read<ValueAdjustmentBloc>()
                        .add(LoadValueAdjustment());
                  },
                );
              }
              return Container();
            });
          }
          if (state is ValueAdjustmentErrorState) {
            return Text(state.error);
          }
          return Container(
            child: Text("Land Value Adjustment"),
          );
        }),
      ),
    );
  }
}
