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:form_builder_validators/form_builder_validators.dart';
import 'package:searchfield/searchfield.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/memoranda/memoranda_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/admin/signatories/signatories_admin_bloc.dart';
import 'package:unit2/bloc/offline/offline_passo/land/land_property_signture/land_property_signature_bloc.dart';
import 'package:unit2/screens/offline/passo/land/add/add_land.dart';

import '../../../../../model/passo/land_ext.dart';
import '../../../../../model/passo/memoranda.dart';
import '../../../../../model/passo/signatories.dart';
import '../../../../../theme-data.dart/colors.dart';
import '../../../../../utils/text_container.dart';
import '../../../../../widgets/error_state.dart';

class LandSignatoriesOfflinePage extends StatefulWidget {
  Function onSAve;
  LandSignatoriesOfflinePage(this.onSAve);

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

class _LandSignatoriesOfflinePage extends State<LandSignatoriesOfflinePage> {
  bool isTaxable = false;
  bool isExempt = false;
  final focus = FocusNode();
  String _memoranda = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProgressHUD(
        padding: const EdgeInsets.all(24),
        backgroundColor: Colors.black87,
        indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
        child:
            BlocConsumer<LandPropertySignatureBloc, LandPropertySignatureState>(
          listener: (context, state) {
            // if (state is LandExtLoading) {
            //   final progress = ProgressHUD.of(context);
            //   progress!.showWithText("Please wait...");
            // }

            // if (state is LandExtErrorState) {
            //   final progress = ProgressHUD.of(context);
            //   progress?.dismiss();
            // }
          },
          builder: (context, state) {
            if (state is LandPropertySignatureInitial) {
              return BlocConsumer<SignatoriesAdminBloc, SignatoriesAdminState>(
                listener: (context, state) {
                  // if (state is SignatoriesLoading) {
                  //   final progress = ProgressHUD.of(context);
                  //   progress!.showWithText("Please wait...");
                  // }

                  // if (state is SignatoriesErrorState) {
                  //   final progress = ProgressHUD.of(context);
                  //   progress?.dismiss();
                  // }
                },
                builder: (context, state) {
                  if (state is SignatoriesLoaded) {
                    final signatories = state.signatories;
                    return BlocConsumer<MemorandaAdminBloc,
                        MemorandaAdminState>(
                      listener: (context, state) {
                        // if (state is MemorandaLoading) {
                        //   final progress = ProgressHUD.of(context);
                        //   progress!.showWithText("Please wait...");
                        // }
                        // if (state is MemorandaLoaded) {
                        //   final progress = ProgressHUD.of(context);
                        //   progress?.dismiss();
                        // }
                        // if (state is MemorandaErrorState) {
                        //   final progress = ProgressHUD.of(context);
                        //   progress?.dismiss();
                        // }
                      },
                      builder: (context, state) {
                        if (state is MemorandaLoaded) {
                          return SingleChildScrollView(
                              child: Column(
                            children: [
                              Container(
                                margin: const EdgeInsets.only(
                                    left: 0, top: 20, right: 0, bottom: 10),
                                child: const Text('PROPERTY ASSESSMENT cont..',
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 18),
                                    textAlign: TextAlign.left),
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Row(
                                    children: [
                                      const Text('Taxable'),
                                      Checkbox(
                                        checkColor: Colors.white,
                                        value: isTaxable,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            isTaxable = value!;
                                          });
                                        },
                                      )
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      const Text('Exempt'),
                                      Checkbox(
                                        checkColor: Colors.white,
                                        value: isExempt,
                                        onChanged: (bool? value) {
                                          setState(() {
                                            isExempt = value!;
                                          });
                                        },
                                      )
                                    ],
                                  ),
                                ],
                              ),
                              Column(
                                children: [
                                  const SizedBox(
                                    height: 20,
                                  ),
                                  const Text(
                                    'EFFECTIVITY OF ASSESSMENT / REASSESSMENT :',
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  const SizedBox(
                                    height: 20,
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceAround,
                                    children: [
                                      const Text('Qtr.'),
                                      SizedBox(
                                        width: 70,
                                        height: 25,
                                        child: FormBuilderTextField(
                                          name: 'land_qtr',
                                          validator:
                                              FormBuilderValidators.compose([]),
                                        ),
                                      ),
                                      const SizedBox(
                                        width: 20,
                                      ),
                                      const Text('Yr.'),
                                      SizedBox(
                                        width: 70,
                                        height: 25,
                                        child: FormBuilderTextField(
                                          name: 'land_yr',
                                          validator:
                                              FormBuilderValidators.compose([]),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              Container(
                                margin: const EdgeInsets.only(
                                    left: 0, top: 40, right: 0, bottom: 10),
                                child: const Text('SIGNATORIES',
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 18),
                                    textAlign: TextAlign.left),
                              ),
                              const SizedBox(
                                height: 30,
                              ),
                              Align(
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  'APPRAISED/ASSESSED BY:',
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                  textAlign: TextAlign.start,
                                ),
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 200,
                                        child: FormBuilderDropdown<Signatories>(
                                            name: 'appraised_by_land',
                                            autofocus: false,
                                            items: signatories
                                                .map((signatories) =>
                                                    DropdownMenuItem(
                                                      value: signatories,
                                                      child: Text(
                                                          '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                    ))
                                                .toList()),
                                      ),
                                      Text('Name'),
                                    ],
                                  ),
                                  const SizedBox(
                                    width: 15,
                                  ),
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 100,
                                        child: FormBuilderDateTimePicker(
                                          name: 'app_date_land',
                                          initialEntryMode:
                                              DatePickerEntryMode.calendarOnly,
                                          initialValue: DateTime.now(),
                                          inputType: InputType.date,

                                          initialTime: const TimeOfDay(
                                              hour: 8, minute: 0),
                                          // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                        ),
                                      ),
                                      Text('Date'),
                                    ],
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 30,
                              ),
                              const Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    'RECOMMENDING APPROVAL:',
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  )),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                children: [
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 200,
                                        child: FormBuilderDropdown<Signatories>(
                                            name: 'rec_approval_land',
                                            autofocus: false,
                                            items: signatories
                                                .map((signatories) =>
                                                    DropdownMenuItem(
                                                      value: signatories,
                                                      child: Text(
                                                          '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                    ))
                                                .toList()),
                                      ),
                                      Text('Name'),
                                    ],
                                  ),
                                  const SizedBox(
                                    width: 15,
                                  ),
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 100,
                                        child: FormBuilderDateTimePicker(
                                          name: 'rec_date_land',
                                          initialEntryMode:
                                              DatePickerEntryMode.calendarOnly,
                                          initialValue: DateTime.now(),
                                          inputType: InputType.date,

                                          initialTime: const TimeOfDay(
                                              hour: 8, minute: 0),
                                          // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                        ),
                                      ),
                                      Text('Date'),
                                    ],
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 30,
                              ),
                              const Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    'APPROVED BY:',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                    ),
                                  )),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 200,
                                        child: FormBuilderDropdown<Signatories>(
                                            name: 'apprvd_by_land',
                                            autofocus: false,
                                            items: signatories
                                                .map((signatories) =>
                                                    DropdownMenuItem(
                                                      value: signatories,
                                                      child: Text(
                                                          '${signatories.firstname} ${signatories.middlename} ${signatories.lastname}'),
                                                    ))
                                                .toList()),
                                      ),
                                      Text('Name'),
                                    ],
                                  ),
                                  const SizedBox(
                                    width: 15,
                                  ),
                                  Column(
                                    children: [
                                      SizedBox(
                                        width: 100,
                                        child: FormBuilderDateTimePicker(
                                          name: 'apprvd_by_date_land',
                                          initialEntryMode:
                                              DatePickerEntryMode.calendarOnly,
                                          initialValue: DateTime.now(),
                                          inputType: InputType.date,

                                          initialTime: const TimeOfDay(
                                              hour: 8, minute: 0),
                                          // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                        ),
                                      ),
                                      Text('Date'),
                                    ],
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 50,
                              ),
                              const Align(
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    'MEMORANDA: ',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                    ),
                                  )),
                              SizedBox(
                                height: 50,
                              ),
                              SizedBox(
                                  width: 500,
                                  height: 50,
                                  child: SearchField(
                                    itemHeight: 70,
                                    suggestions: state.memo
                                        .map((Memoranda memoranda) =>
                                            SearchFieldListItem(
                                              '${memoranda.memoranda}',
                                              item:
                                                  memoranda, // Change: Use individual Memoranda object
                                              child: ListTile(
                                                title: Text(
                                                  '${memoranda.memoranda}',
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            ))
                                        .toList(),
                                    validator: FormBuilderValidators.required(
                                        errorText: "This field is required"),
                                    // searchInputDecoration:
                                    //     normalTextFieldStyle(
                                    //             "Memoranda", "")
                                    //         .copyWith(
                                    //   suffixIcon: const Icon(
                                    //       Icons.arrow_drop_down),
                                    // ),
                                    focusNode: focus,
                                    suggestionState: Suggestion.expand,
                                    suggestionDirection: SuggestionDirection.up,
                                    onSuggestionTap: (memoranda) {
                                      setState(() {
                                        _memoranda = memoranda.item!.memoranda!;
                                      });
                                      focus.unfocus();
                                    },
                                  )),
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('Sworn Statement No. :'),
                                  SizedBox(
                                    width: 150,
                                    height: 20,
                                    child: FormBuilderTextField(
                                      name: 'sworn_statement_land',
                                      decoration: InputDecoration(),
                                      validator:
                                          FormBuilderValidators.compose([]),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('Date Received:'),
                                  SizedBox(
                                    width: 150,
                                    height: 20,
                                    child: FormBuilderDateTimePicker(
                                      name: 'date_received_land',
                                      initialEntryMode:
                                          DatePickerEntryMode.calendarOnly,
                                      initialValue: DateTime.now(),
                                      inputType: InputType.date,

                                      initialTime:
                                          const TimeOfDay(hour: 8, minute: 0),
                                      // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('Date of Entry in the Rec. of Ass. :'),
                                  SizedBox(
                                    width: 100,
                                    height: 20,
                                    child: FormBuilderDateTimePicker(
                                      name: 'date_of_entry_land',
                                      initialEntryMode:
                                          DatePickerEntryMode.calendarOnly,
                                      initialValue: DateTime.now(),
                                      inputType: InputType.date,

                                      initialTime:
                                          const TimeOfDay(hour: 8, minute: 0),
                                      // locale: const Locale.fromSubtags(languageCode: 'fr'),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(
                                height: 30,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('By:'),
                                  SizedBox(
                                    width: 150,
                                    height: 20,
                                    child: FormBuilderTextField(
                                      name: 'by_land',
                                      decoration: InputDecoration(),
                                      validator:
                                          FormBuilderValidators.compose([]),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 30,
                              ),
                              ElevatedButton(
                                onPressed: () async {
                                  final tempID =
                                      await SharedPreferences.getInstance();
                                  var ext = LandExt();

                                  print(ext.toJson());
                                  context.read<LandPropertySignatureBloc>().add(AddLandPropertySignature(
                                      id: 1,
                                      landapprDetailsId:
                                          tempID.getInt('landid')! + 1,
                                      dateCreated: 'test',
                                      dateModified: 'test',
                                      assessedById: 'test',
                                      assessedByName: 'test',
                                      taxable: isTaxable == true ? '1' : '0',
                                      exempt: isExempt == true ? '1' : '0',
                                      qtr: landKeyOffline
                                          .currentState!.value['land_qtr'],
                                      yr: landKeyOffline
                                          .currentState!.value['land_yr'],
                                      appraisedbyName: landKeyOffline
                                              .currentState!
                                              .value['appraised_by_land']
                                              .firstname +
                                          ' ' +
                                          landKeyOffline
                                              .currentState!
                                              .value['appraised_by_land']
                                              .middlename +
                                          ' ' +
                                          landKeyOffline
                                              .currentState!
                                              .value['appraised_by_land']
                                              .lastname,
                                      appraisedbyDate: landKeyOffline.currentState!.value['app_date_land']
                                          .toString(),
                                      recommendapprName: landKeyOffline
                                              .currentState!
                                              .value['rec_approval_land']
                                              .firstname +
                                          ' ' +
                                          landKeyOffline
                                              .currentState!
                                              .value['rec_approval_land']
                                              .middlename +
                                          ' ' +
                                          landKeyOffline.currentState!.value['rec_approval_land'].lastname,
                                      recommendapprDate: landKeyOffline.currentState!.value['rec_date_land'].toString(),
                                      approvedbyName: landKeyOffline.currentState!.value['apprvd_by_land'].firstname + ' ' + landKeyOffline.currentState!.value['apprvd_by_land'].middlename + ' ' + landKeyOffline.currentState!.value['apprvd_by_land'].lastname,
                                      approvedbyDate: landKeyOffline.currentState!.value['apprvd_by_date_land'].toString(),
                                      memoranda: _memoranda,
                                      swornstatementNo: landKeyOffline.currentState!.value['sworn_statement_land'],
                                      dateReceived: landKeyOffline.currentState!.value['date_received_land'].toString(),
                                      entryDateAssessment: landKeyOffline.currentState!.value['date_of_entry_land'].toString(),
                                      entryDateBy: landKeyOffline.currentState!.value['by_land']));
                                  widget.onSAve();
                                },
                                style: ElevatedButton.styleFrom(
                                    backgroundColor: primary,
                                    foregroundColor: Colors.red),
                                child: SizedBox(
                                  width: 250,
                                  height: 50,
                                  child: Align(
                                    alignment: Alignment.center,
                                    child: Text(
                                      'Save',
                                      style: TextStyle(
                                        color: Colors.white,
                                      ),
                                      textAlign: TextAlign.center,
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(
                                height: 30,
                              ),
                            ],
                          ));
                        }
                        // if (state is MemorandaErrorState) {
                        //   return SomethingWentWrong(
                        //     message: onError,
                        //     onpressed: () {
                        //       // context
                        //       //     .read<MemorandaBloc>()
                        //       //     .add(LoadMemoranda());
                        //     },
                        //   );
                        // }
                        return Container();
                      },
                    );
                  }
                  // if (state is SignatoriesAd) {
                  //   return SomethingWentWrong(
                  //     message: onError,
                  //     onpressed: () {
                  //       context.read<SignatoriesBloc>().add(LoadSignatories());
                  //     },
                  //   );
                  // }
                  return Container();
                },
              );
            }
            // if (state is LandExtErrorState) {
            //   return SomethingWentWrong(
            //     message: onError,
            //     onpressed: () {
            //       context.read<LandExtBloc>().add(LoadLandExt());
            //     },
            //   );
            // }
            return Container();
          },
        ),
      ),
    );
  }
}
