import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/passo/land/land_property_assessment/land_property_assessment_bloc.dart';
import 'package:unit2/bloc/passo/land/land_value_adjustments/land_value_adjustments_bloc.dart';
import 'package:unit2/model/passo/land_property_assessment.dart';
import 'package:unit2/model/passo/land_value_adjustment.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/utils/text_container.dart';
import 'package:unit2/widgets/error_state.dart';

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

  AddPropertyAssessmentEditModal(this.tempId);

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

class _AddPropertyAssessmentEditModal
    extends State<AddPropertyAssessmentEditModal> {
  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;
  String _actualUse = "Residential";
  String _assessmentLevel = "";

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

  final typeOfTree = [
    "Non-Fruit Bearing",
    "Fruit Bearing",
  ];

  final actual_use = [
    "Residential",
    "Agricultural",
    "Commercial",
    "Industrial",
    "Mineral",
    "Timberland",
  ];

  calculateAssessmentValue() {
    switch (_actualUse) {
      case "Residential":
        return _unitValue * 0.20;
        break;
      case "Agricultural":
        return _unitValue * 0.40;
        break;
      case "Commercial":
        return _unitValue * 0.50;
        break;
      case "Industrial":
        return _unitValue * 0.50;
        break;
      case "Mineral":
        return _unitValue * 0.50;
        break;
      case "Timberland":
        return _unitValue * 0.20;
        break;
      default:
    }
  }

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

  double _amountofDepreciation(unitVal, unitBase, area, depreciation) {
    return ((unitVal * unitBase) * area) * depreciation;
  }

  double _totalMarketValue(unitBase, area) {
    return unitBase * area;
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LandPropertyAssessmentBloc, LandPropertyAssessmentState>(
        buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddLandPropertyAssessmentScreen) {
        return BlocConsumer<LandValueAdjustmentsBloc,
            LandValueAdjustmentsState>(listener: (context, state) {
          // TODO: implement listener
        }, builder: (context, state) {
          if (state is LandValueAdjustmentsLoaded) {
            final assessment = state.val_adj;
            return FormBuilder(
                key: assessmentKey,
                onChanged: () {
                  assessmentKey.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<ValueAdjustments>(
                                  name: 'value_adjustments',
                                  autofocus: false,
                                  decoration: normalTextFieldStyle(
                                      "Value Adjustments", ""),
                                  items: state.val_adj
                                      .map((adj) =>
                                          DropdownMenuItem<ValueAdjustments>(
                                            value: adj,
                                            child: Text(
                                              (adj.adjustmentFactors ?? ""),
                                            ),
                                          ))
                                      .toList(),
                                  onChanged: (selectedAdj) {
                                    if (selectedAdj != null) {
                                      setState(() {
                                        _unitValue = double.parse(
                                            selectedAdj.marketValue!);
                                      });
                                    }
                                  },
                                )),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          FormBuilderDropdown<String?>(
                            name: "land_actual_use",
                            autofocus: false,
                            decoration: normalTextFieldStyle("Actual Use", ""),
                            items: actual_use
                                .map((item) => DropdownMenuItem(
                                      value: item,
                                      child: Text(item),
                                    ))
                                .toList(),
                            onChanged: (value) {
                              setState(() {
                                _actualUse = value!;

                                switch (value) {
                                  case "Residential":
                                    setState(() {
                                      _assessmentLevel = '20';
                                    });

                                    break;
                                  case "Agricultural":
                                    setState(() {
                                      _assessmentLevel = '40';
                                    });

                                    break;
                                  case "Commercial":
                                    setState(() {
                                      _assessmentLevel = '50';
                                    });

                                    break;
                                  case "Industrial":
                                    setState(() {
                                      _assessmentLevel = '50';
                                    });

                                    break;
                                  case "Mineral":
                                    setState(() {
                                      _assessmentLevel = '50';
                                    });

                                    break;
                                  case "Timberland":
                                    setState(() {
                                      _assessmentLevel = '20';
                                    });

                                    break;
                                  default:
                                }
                              });
                            },
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Text('Assessment Level'),
                          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(_assessmentLevel + '%'),
                            ),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Text('Assessment Value'),
                          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(calculateAssessmentValue().toString() ==
                                      "0.00"
                                  ? "00.0"
                                  : calculateAssessmentValue())),
                            ),
                          ),
                          const SizedBox(height: 10),
                          Row(
                            children: [
                              Container(
                                width: 120,
                                height: 60,
                                padding: const EdgeInsets.all(8.0),
                                child: ElevatedButton(
                                  onPressed: () async {
                                    var assessment = LandPropertyAssessment(
                                        landapprDetailsId: widget.tempId,
                                        actualUse: _actualUse,
                                        marketval: _unitValue.toString(),
                                        assessmentLevel: _assessmentLevel,
                                        assessedValue:
                                            calculateAssessmentValue()
                                                .toString(),
                                        totalMarketval: '0',
                                        totalAssessedval: '0');

                                    context
                                        .read<LandPropertyAssessmentBloc>()
                                        .add(AddLandPropertyAssessment(
                                            assessment: assessment));
                                  },
                                  style: ElevatedButton.styleFrom(
                                    primary: 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<LandPropertyAssessmentBloc>()
                                        .add(
                                            const LoadLandPropertyAssessment());
                                  },
                                  style: ElevatedButton.styleFrom(
                                    primary: Colors.black,
                                  ),
                                  child: const Text("Cancel"),
                                ),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                ));
          }
          if (state is LandValueAdjustmentsErrorState) {
            return SomethingWentWrong(
              message: onError,
              onpressed: () {
                context
                    .read<LandValueAdjustmentsBloc>()
                    .add(LoadLandValueAdjustments());
              },
            );
          }
          return Container();
        });
      }
      if (state is LandPropertyAssessmentErrorState) {
        return SomethingWentWrong(
          message: onError,
          onpressed: () {
            context
                .read<LandPropertyAssessmentBloc>()
                .add(LoadLandPropertyAssessment());
          },
        );
      }
      return Container();
    });
  }
}
