import 'dart:convert';

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:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/unit_construction/unit_construction_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/building/general_description/general_description_bloc.dart';
import 'package:unit2/screens/offline/passo/building/edit/edit_building.dart';
import 'package:unit2/screens/offline/passo/building/edit/property_owner_info_edit.dart';

import '../../../../../model/passo/general_description.dart';
import '../../../../../model/passo/unit_construct.dart';
import '../../../../../theme-data.dart/form-style.dart';
import '../../../../../widgets/passo/custom_button.dart';
import '../../../../../widgets/passo/custom_formBuilder_fields.dart';

class GeneralDescriptionEditOffline extends StatefulWidget {
  final int tempId;
  final VoidCallback NextBtn;
  final VoidCallback PrevBtn;

  GeneralDescriptionEditOffline(this.tempId, this.NextBtn, this.PrevBtn);
  @override
  _GeneralDescriptionEditOffline createState() =>
      _GeneralDescriptionEditOffline();
}

class _GeneralDescriptionEditOffline
    extends State<GeneralDescriptionEditOffline> {
  final actual_use = [
    "Residential",
    "Agricultural",
    "Commercial",
    "Industrial",
    "Mineral",
    "Timberland",
  ];

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<GeneralDescriptionBloc, GeneralDescriptionState>(
      listener: (context, state) async {
        // if (state is GenDescLoading) {
        //   final progress = ProgressHUD.of(context);
        //   progress!.showWithText("Please wait...");
        // }
        // if (state is GenDescLoaded) {
        //   final progress = ProgressHUD.of(context);
        //   progress?.dismiss();

        //   final tempID = await SharedPreferences.getInstance();
        //   await tempID.setInt(
        //       'totalValue', int.parse(state.gendesc.totalFloorArea!));
        //        await tempID.setString(
        //       'actualUse', state.gendesc.actualUse!);

        // }
        // if (state is GenDescErrorState) {
        //   final progress = ProgressHUD.of(context);
        //   progress?.dismiss();
        // }
      },
      builder: (context, state) {
        if (state is SpecificGeneralDescriptionLoaded) {
          final gendesc = state.gendesc;
          return BlocConsumer<UnitConstructionAdminBloc,
              UnitConstructionAdminState>(
            listener: (context, state) {
              // TODO: implement listener
            },
            builder: (context, state) {
              if (state is UnitConstructLoaded) {
                return FormBuilder(
                  key: offlineBldgEditKey,
                  initialValue: {
                    'bldg_permit': gendesc.bldgPermit,
                    'date_issued': gendesc.dateIssued.toString(),
                    'cct': gendesc.cct.toString(),
                    'coc_issued': gendesc.certCompletionIssued.toString(),
                    'coo_issued': gendesc.certOccupancyIssued.toString(),
                    'date_cnstructed': gendesc.dateIssued.toString(),
                    'date_occupied': gendesc.dateOccupied.toString(),
                    'bldg_age': gendesc.bldgAge.toString(),
                    'no_of_storeys': gendesc.noStoreys.toString(),
                    'area_of_1stFl': gendesc.area1Stfloor,
                    'area_of_2ndFl': gendesc.area2Ndfloor,
                    'area_of_3rdFl': gendesc.area3Rdfloor,
                    'area_of_4thFl': gendesc.area4Thfloor,
                    'total_area': gendesc.totalFloorArea.toString(),
                    'actual_use': gendesc.actualUse
                  },
                  enabled: true,
                  onChanged: () {
                    offlineBldgEditKey.currentState!.save();
                    debugPrint(
                        offlineBldgEditKey.currentState!.value.toString());
                  },
                  autovalidateMode: AutovalidateMode.disabled,
                  skipDisabled: true,
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: Column(
                        children: [
                          Container(
                            margin: const EdgeInsets.only(
                                left: 0, top: 20, right: 0, bottom: 10),
                            child: const Text('GENERAL DESCRIPTION',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 18),
                                textAlign: TextAlign.left),
                          ),
                          Container(
                            margin: const EdgeInsets.only(
                                left: 0, top: 10, right: 0, bottom: 0),
                            child: FormBuilderDropdown(
                              name: 'bldg_type',
                              autofocus: false,
                              decoration: normalTextFieldStyle(
                                  gendesc.bldgKind ?? "Kind of Building",
                                  "Kind of Building"),
                              items: state.unit
                                  .map((e) => DropdownMenuItem(
                                        value: e,
                                        child:
                                            Text(e.bldgType + '-' + e.building),
                                      ))
                                  .toList(),
                            ),
                          ),
                          customDropDownField(
                              "Actual Use", "", 'actual_use', actual_use),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: customTextField("Bldg. Permit No.", "",
                                      'bldg_permit', TextInputType.phone),
                                ),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customDatTimePicker(
                                        "Certificate of Occupancy Issued ON",
                                        "",
                                        'date_issued'))
                              ]),
                          customTextField(
                              "Condominium Certificate of Title (CCT)",
                              "",
                              'cct',
                              TextInputType.number),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: customDatTimePicker(
                                      "Certificate of Completion Issued ON",
                                      "",
                                      'coc_issued'),
                                ),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customDatTimePicker(
                                        "Certificate of Occupancy Issued ON",
                                        "",
                                        'coo_issued'))
                              ]),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: customDatTimePicker(
                                      "Date Constructed /Completed",
                                      "",
                                      'date_cnstructed'),
                                ),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customDatTimePicker(
                                        "Date Occupied", "", 'date_occupied'))
                              ]),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: customTextField("Bldg. Age", "",
                                      'bldg_age', TextInputType.phone),
                                ),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customTextField("No. of storeys", "",
                                        'no_of_storeys', TextInputType.phone))
                              ]),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                  flex: 1,
                                  child: customTextField("Area of 1st Floor",
                                      "", 'area_of_1stFl', TextInputType.phone),
                                ),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customTextField(
                                        "Area of 2nd Floor",
                                        "",
                                        'area_of_2ndFl',
                                        TextInputType.phone))
                              ]),
                          Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: <Widget>[
                                Expanded(
                                    flex: 1,
                                    child: customTextField(
                                        "Area of 3rd Floor",
                                        "",
                                        'area_of_3rdFl',
                                        TextInputType.phone)),
                                const SizedBox(width: 10.0),
                                Expanded(
                                    // optional flex property if flex is 1 because the default flex is 1
                                    flex: 1,
                                    child: customTextField(
                                        "Area of 4th Floor",
                                        "",
                                        'area_of_4thFl',
                                        TextInputType.phone))
                              ]),
                          customTextField("Total Area", "", 'total_area',
                              TextInputType.phone),
                          SizedBox(
                            height: 50,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              CustomButton(
                                icon: const Icon(Icons.chevron_left_rounded,
                                    color: Colors.white),
                                onPressed: () {
                                  {
                                    widget.PrevBtn();
                                  }
                                  ;
                                },
                              ),
                              CustomButton(
                                icon: const Icon(Icons.chevron_right_rounded,
                                    color: Colors.white),
                                onPressed: () {
                                  {
                                    offlineBldgEditKey.currentState!.save();

                                    var gendescData = GeneralDesc(
                                        id: 1,
                                        bldgapprDetailsId: widget.tempId,
                                        assessedById: "1",
                                        assessedByName: 'hhs',
                                        bldgKind: offlineBldgEditKey
                                                .currentState
                                                ?.value['bldg_type']
                                                ?.building ??
                                            gendesc.bldgKind,
                                        strucType: offlineBldgEditKey
                                                .currentState
                                                ?.value['bldg_type']
                                                ?.bldgType ??
                                            gendesc.strucType,
                                        bldgPermit: offlineBldgEditKey
                                                .currentState
                                                ?.value['bldg_permit'] ??
                                            gendesc.bldgPermit,
                                        dateIssued: offlineBldgEditKey
                                                    .currentState
                                                    ?.value['date_issued'] !=
                                                null
                                            ? offlineBldgEditKey.currentState!.value['date_issued']
                                                .toString()
                                            : gendesc.dateIssued,
                                        cct: offlineBldgEditKey.currentState!.value['cct'] ?? gendesc.cct,
                                        certCompletionIssued: offlineBldgEditKey.currentState!.value['coc_issued'].toString(),
                                        certOccupancyIssued: offlineBldgEditKey.currentState!.value['coo_issued'].toString(),
                                        dateCompleted: offlineBldgEditKey.currentState!.value['date_cnstructed'].toString(),
                                        dateOccupied: offlineBldgEditKey.currentState!.value['date_occupied'].toString(),
                                        bldgAge: offlineBldgEditKey.currentState?.value['bldg_age']!,
                                        noStoreys: offlineBldgEditKey.currentState?.value['no_of_storeys']!,
                                        area1Stfloor: offlineBldgEditKey.currentState?.value['area_of_1stFl'],
                                        area2Ndfloor: offlineBldgEditKey.currentState?.value['area_of_2ndFl'],
                                        area3Rdfloor: offlineBldgEditKey.currentState?.value['area_of_3rdFl'],
                                        area4Thfloor: offlineBldgEditKey.currentState?.value['area_of_4thFl'],
                                        totalFloorArea: offlineBldgEditKey.currentState?.value['total_area'],
                                        floorSketch: 'null',
                                        actualUse: offlineBldgEditKey.currentState?.value['actual_use'],
                                        unitValue: offlineBldgEditKey.currentState?.value['bldg_type']?.unitValue ?? gendesc.unitValue);

                                    context.read<GeneralDescriptionBloc>().add(
                                        UpdateGeneralDescription(
                                            id: widget.tempId,
                                            gendesc: gendescData));

                                    widget.NextBtn();
                                  }
                                  ;
                                },
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                );
              }
              return Container();
            },
          );
        }
        // if (state is GenDescErrorState) {
        //   return SomethingWentWrong(
        //     message: onError,
        //     onpressed: () {
        //       context.read<GeneralDescriptionBloc>().add(LoadGenDesc(
        //           id: widget.tempId, gendesc: GeneralDesc()));
        //     },
        //   );
        // }
        return Container();
      },
    );
  }
}
