import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:intl/intl.dart';
import 'package:searchfield/searchfield.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/model/passo/additional_items.dart';
import 'package:unit2/model/passo/class_components.dart';
import 'package:unit2/model/passo/unit_construct.dart';
import 'package:unit2/theme-data.dart/form-style.dart';

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

  AddExtraItemsEdit(this.unit, this.options, this.tempId);

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

class _AddExtraItemsEdit extends State<AddExtraItemsEdit> {
  GlobalKey<FormBuilderState> formKey = GlobalKey<FormBuilderState>();
  final focus = FocusNode();
  double _computedValue = 0;
  bool isPainted = false;
  bool isSecondHand = false;
  TextEditingController textEditingController = TextEditingController();
  double _unitBase = 0;
  int _areaValue = 0;
  double _depValue = 0;
  double _unitValue = 0;
  double _marketValue = 0;
  String _className = "";
  int _classId = 0;
  String _structureType = "";
  bool _withoutBUCC = false;
  int _notPaintedUnitVal = 0;
  int _secondHandUnitVal = 0;

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

  double _computeValue(double unitbase, double unitvalue, double area) {
// Compute some value based on the text here
    return (unitbase * unitvalue) * area;
  }

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

  double _adjustedMarketValue(unitVal, unitBase, area, depreciation) {
    double depAmount = ((unitVal * unitBase) * area) * depreciation;

    return ((unitVal * unitBase) * area) - depAmount;
  }

  double _totalMarketValue(unitVal, unitBase, area, depreciation, withBUCC,
      className, painted, secondHand, paintedUnitVal, secondhandUntVal) {
    if (withBUCC == false) {
      if (painted == true || secondHand == true) {
        final deductions = (paintedUnitVal + secondhandUntVal) / 100;

        print(deductions);
        return (((unitVal - deductions) * unitBase) * area);
      } else {
        return ((unitVal * unitBase) * area);
      }
    } else {
      return (unitVal * area);
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AdditionalItemsEditBloc, AdditionalItemsEditState>(
        buildWhen: (previous, current) {
      return false;
    }, builder: (context, state) {
      if (state is ShowAddItemsScreenEdit) {
        return FormBuilder(
            key: formKey,
            onChanged: () {
              formKey.currentState?.save();
            },
            autovalidateMode: AutovalidateMode.disabled,
            child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Container(
                  height: 800,
                  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: FormBuilderDropdown(
                            name: 'extra_item',
                            autofocus: false,
                            decoration:
                                normalTextFieldStyle("Additional Item", ""),
                            items: widget.options
                                .map((e) => DropdownMenuItem(
                                      value: e,
                                      child: Text(e.componentName),
                                    ))
                                .toList(),
                            onChanged: (value) {
                              if (value!.minBaseUnitvalPercent != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.minBaseUnitvalPercent);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.minBaseUnitvalPercent});
                              }
                              if (value.maxBaseUnitvalPercent != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.maxBaseUnitvalPercent);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.maxBaseUnitvalPercent});
                              }
                              if (value.minUnitvalSqrmtr != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.minUnitvalSqrmtr);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.minUnitvalSqrmtr});
                              }
                              if (value.maxUnitvalSqrmtr != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.maxUnitvalSqrmtr);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.maxUnitvalSqrmtr});
                              }
                              if (value.minAddBaseunitval != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.minAddBaseunitval);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.minAddBaseunitval});
                              }
                              if (value.maxAddBaseunitval != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.maxAddBaseunitval);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.maxAddBaseunitval});
                              }
                              if (value.minDeductBaserate != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.minDeductBaserate);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.minDeductBaserate});
                              }
                              if (value.maxDeductBaserate != '0.00') {
                                setState(() {
                                  _unitValue =
                                      double.parse(value.maxDeductBaserate);
                                  _className = value.componentName;
                                  _classId = value.id;
                                  _withoutBUCC = value.withoutBucc;
                                });
                                formKey.currentState!.patchValue(
                                    {'unitValue': value.maxDeductBaserate});
                              }
                            },
                          ),
                        ),
                        const SizedBox(height: 10),
                        Container(
                          margin: const EdgeInsets.only(
                              left: 0, top: 10, right: 0, bottom: 0),
                          child: SizedBox(
                            height: 45,
                            child: SearchField(
                              itemHeight: 70,
                              suggestions: widget.unit
                                  .map((UnitConstruct unit) =>
                                      SearchFieldListItem(
                                          unit.bldgType! +
                                              ' - ' +
                                              unit.building,
                                          item: unit,
                                          child: ListTile(
                                            title: Text(
                                              unit.bldgType +
                                                  ' - ' +
                                                  unit.building!.toUpperCase(),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          )))
                                  .toList(),

                              validator: FormBuilderValidators.required(
                                  errorText: "This field is required"),

                              searchInputDecoration: normalTextFieldStyle(
                                      "Structure Type", "")
                                  .copyWith(
                                      suffixIcon:
                                          const Icon(Icons.arrow_drop_down)),
                              ////agency suggestion tap
                              focusNode: focus,
                              suggestionState: Suggestion.expand,
                              onSuggestionTap: (unit) {
                                setState(() {
                                  _unitBase =
                                      double.parse(unit.item!.unitValue);
                                  _structureType = unit.item!.bldgType +
                                      ' - ' +
                                      unit.item!.building;
                                });
                                focus.unfocus();
                              },
                            ),
                          ),
                        ),
                        // const SizedBox(height: 10),
                        // Container(
                        //   margin: const EdgeInsets.only(
                        //       left: 0, top: 10, right: 0, bottom: 0),
                        //   child: FormBuilderDropdown(
                        //     name: 'struc_type',
                        //     autofocus: false,
                        //     decoration:
                        //         normalTextFieldStyle("Structure Type", ""),
                        //     items: widget.unit
                        //         .map((e) => DropdownMenuItem(
                        //               value: e,
                        //               child:
                        //                   Text(e.bldgType + " - " + e.building),
                        //             ))
                        //         .toList(),
                        //     onChanged: (val) {
                        //       setState(() {
                        //         _unitBase = double.parse(val!.unitValue);
                        //         _structureType = val.bldgType;
                        //       });
                        //     },
                        //   ),
                        // ),
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: FormBuilderTextField(
                                name: 'unitValue',
                                decoration:
                                    normalTextFieldStyle("Unit Value", ""),
                                validator: FormBuilderValidators.compose([]),
                              ),
                            ),
                            const SizedBox(width: 10),
                            Expanded(
                              flex: 1,
                              child: FormBuilderTextField(
                                name: 'areaValue',
                                decoration: normalTextFieldStyle("Area", ""),
                                validator: FormBuilderValidators.compose([]),
                                onChanged: (value) {
                                  setState(() {
                                    _areaValue = int.parse(value!);
                                  });
                                },
                              ),
                            ),
                          ],
                        ),
                        // const SizedBox(height: 10),
                        // FormBuilderTextField(
                        //   name: 'depRate',
                        //   decoration:
                        //       normalTextFieldStyle("Depreciation Rate", ""),
                        //   validator: FormBuilderValidators.compose([]),
                        //   onChanged: (value) {
                        //     setState(() {
                        //       _depValue = double.parse(value!);
                        //     });
                        //   },
                        // ),
                        // const SizedBox(height: 10),
                        // FormBuilderTextField(
                        //   name: 'marketValue',
                        //   decoration: normalTextFieldStyle(
                        //       NumberFormat.currency(
                        //               locale: 'en-PH', symbol: "₱")
                        //           .format(_totalMarketValue(_unitValue,
                        //               _unitBase, _areaValue, _depValue)),
                        //       ""),
                        //   validator: FormBuilderValidators.compose([]),
                        //   onChanged: (value) {
                        //     setState(() {
                        //       _marketValue = double.parse(value!);
                        //     });
                        //   },
                        // ),
                        // const SizedBox(height: 10),
                        // Text('Amount of Depreciation'),
                        // const SizedBox(height: 5),
                        // 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(_amountofDepreciation(_unitValue,
                        //               _unitBase, _areaValue, _depValue)))),
                        // ),

                        Visibility(
                          visible: !_withoutBUCC,
                          child: Column(
                            children: [
                              const SizedBox(height: 10),
                              Text('Building is not painted?'),
                              const SizedBox(height: 5),
                              Container(
                                child: Row(
                                  children: [
                                    Checkbox(
                                      value: isPainted,
                                      onChanged: (bool? value) {
                                        setState(() {
                                          isPainted = value!;
                                          if (value == false) {
                                            _notPaintedUnitVal = 0;
                                          } else {
                                            _notPaintedUnitVal = 10;
                                          }
                                        });
                                      },
                                    ),
                                    const SizedBox(width: 10),
                                    Container(
                                      height: 40.0,
                                      width: 100,
                                      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(' - ' +
                                              _notPaintedUnitVal.toString() +
                                              '%')),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 10),
                              Text('Uses second hand materials?'),
                              const SizedBox(height: 5),
                              Container(
                                child: Row(
                                  children: [
                                    Checkbox(
                                      value: isSecondHand,
                                      onChanged: (bool? value) {
                                        setState(() {
                                          isSecondHand = value!;
                                          if (isSecondHand == false) {
                                            _secondHandUnitVal = 0;
                                            formKey.currentState!.patchValue(
                                                {'secondHandMat': '0'});
                                          } else {
                                            _secondHandUnitVal = 5;
                                            formKey.currentState!.patchValue(
                                                {'secondHandMat': '5'});
                                          }
                                        });
                                      },
                                    ),
                                    const SizedBox(width: 10),
                                    Row(
                                      children: [
                                        SizedBox(
                                          height: 40,
                                          width: 100,
                                          child: FormBuilderTextField(
                                            enabled: isSecondHand,
                                            name: 'secondHandMat',
                                            textAlign: TextAlign.center,
                                            decoration: normalTextFieldStyle(
                                                "Unit Value", ""),
                                            validator:
                                                FormBuilderValidators.compose(
                                                    []),
                                            onChanged: (value) {
                                              // Check if the value is not null before parsing to double
                                              if (value != null &&
                                                  value.isNotEmpty) {
                                                setState(() {
                                                  _secondHandUnitVal =
                                                      int.parse(value);
                                                });
                                              } else {
                                                // Handle the case when the value is empty or null
                                                // For example, set _secondHandUnitVal to a default value or show an error message.
                                              }
                                            },
                                          ),
                                        ),
                                        SizedBox(
                                          height: 40,
                                          width: 40,
                                          child: Center(
                                            child: Text(
                                              '%',
                                              style: TextStyle(
                                                  fontSize: 18,
                                                  fontWeight: FontWeight.bold),
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),

                        const SizedBox(height: 10),
                        Text('Market Value'),
                        const SizedBox(height: 5),
                        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(_totalMarketValue(
                                      _unitValue,
                                      _unitBase,
                                      _areaValue,
                                      _depValue,
                                      _withoutBUCC,
                                      _className,
                                      isPainted,
                                      isSecondHand,
                                      _notPaintedUnitVal,
                                      _secondHandUnitVal)))),
                        ),
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            Container(
                              width: 120,
                              height: 60,
                              padding: const EdgeInsets.all(8.0),
                              child: ElevatedButton(
                                onPressed: () {
                                  var itemss = AdditionalItems(
                                      id: 1,
                                      bldgapprDetailsId: widget.tempId,
                                      classId: _classId,
                                      className: _className,
                                      structType: _structureType,
                                      unitValue:
                                          _withoutBUCC == true ? 0 : _unitValue,
                                      baseUnitValue: _unitBase,
                                      area: _areaValue,
                                      marketValue:
                                          (_unitValue * _unitBase) * _areaValue,
                                      depreciationRate: _depValue,
                                      adjustedMarketVal: _totalMarketValue(
                                          _unitValue,
                                          _unitBase,
                                          _areaValue,
                                          _depValue,
                                          _withoutBUCC,
                                          _className,
                                          isPainted,
                                          isSecondHand,
                                          _notPaintedUnitVal,
                                          _secondHandUnitVal),
                                      actualUse: 'Test',
                                      amtDepreciation: _amountofDepreciation(
                                        _unitValue,
                                        _unitBase,
                                        _areaValue,
                                        _depValue,
                                      ),
                                      painted: true,
                                      secondhand: true,
                                      paintedUnitval: '1',
                                      secondhandUnitval: '1');

                                  context.read<AdditionalItemsEditBloc>().add(
                                      AddAdditionalItemsEdit(items: itemss));
                                },
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.black,
                                ),
                                child: const Text("Submit"),
                              ),
                            ),
                            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<AdditionalItemBloc>()
                                      .add(LoadAdditionalItems());
                                },
                                style: ElevatedButton.styleFrom(
                                  primary: Colors.black,
                                ),
                                child: const Text("Cancel"),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                )));
      }
      return Container();
    });
  }
}
