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:searchfield/searchfield.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:unit2/bloc/passo/land/land_ext/land_ext_bloc.dart';
import 'package:unit2/bloc/passo/memoranda/memoranda_bloc.dart';
import 'package:unit2/bloc/passo/signatories/signatories_bloc.dart';
import 'package:unit2/model/passo/land_ext.dart';
import 'package:unit2/model/passo/memoranda.dart';
import 'package:unit2/model/passo/signatories.dart';
import 'package:unit2/screens/passo/Land/add_land.dart';
import 'package:unit2/theme-data.dart/colors.dart';

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

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

class _LandSignatories extends State<LandSignatories> {
  bool isTaxable = false;
  bool isExempt = false;
  final focus = FocusNode();
  String _memoranda = "";
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<LandExtBloc, LandExtState>(
      listener: (context, state) {
        // TODO: implement listener
      },
      builder: (context, state) {
        if (state is LandExtLoaded) {
          return BlocConsumer<SignatoriesBloc, SignatoriesState>(
            listener: (context, state) {
              // TODO: implement listener
            },
            builder: (context, state) {
              if (state is SignatoriesLoaded) {
                final signatories = state.signatories;
                return BlocConsumer<MemorandaBloc, MemorandaState>(
                  listener: (context, state) {
                    // TODO: implement listener
                  },
                  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: 100,
                              child: SearchField(
                                suggestions: state.memorada
                                    .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,
                                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([]),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 30,
                          ),
                          ElevatedButton(
                            onPressed: () async {
                              final tempID =
                                  await SharedPreferences.getInstance();
                              var ext = LandExt(
                                  landapprDetailsId:
                                      tempID.getInt('landid')! - 1,
                                  taxable: isTaxable,
                                  exempt: isExempt,
                                  qtr: int.parse(
                                      landKey.currentState!.value['land_qtr']),
                                  yr: int.parse(
                                      landKey.currentState!.value['land_yr']),
                                  appraisedbyName: landKey.currentState!.value['appraised_by_land'].firstname +
                                      ' ' +
                                      landKey
                                          .currentState!
                                          .value['appraised_by_land']
                                          .middlename +
                                      ' ' +
                                      landKey.currentState!
                                          .value['appraised_by_land'].lastname,
                                  appraisedbyDate: landKey
                                      .currentState!.value['app_date_land'],
                                  recommendapprName: landKey
                                          .currentState!
                                          .value['rec_approval_land']
                                          .firstname +
                                      ' ' +
                                      landKey
                                          .currentState!
                                          .value['rec_approval_land']
                                          .middlename +
                                      ' ' +
                                      landKey.currentState!
                                          .value['rec_approval_land'].lastname,
                                  recommendapprDate: landKey
                                      .currentState!.value['rec_date_land'],
                                  approvedbyName: landKey.currentState!.value['apprvd_by_land'].firstname +
                                      ' ' +
                                      landKey.currentState!.value['apprvd_by_land'].middlename +
                                      ' ' +
                                      landKey.currentState!.value['apprvd_by_land'].lastname,
                                  approvedbyDate: landKey.currentState!.value['apprvd_by_date_land'],
                                  memoranda: _memoranda,
                                  swornstatementNo: landKey.currentState!.value['sworn_statement_land'],
                                  dateReceived: landKey.currentState!.value['date_received_land'],
                                  entryDateAssessment: landKey.currentState!.value['date_of_entry_land'],
                                  entryDateBy: landKey.currentState!.value['by_land']);

                              context.read<LandExtBloc>()
                                ..add(UpdateLandExt(landext: ext));
                              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,
                          ),
                        ],
                      ));
                    }
                    return Container();
                  },
                );
              }
              return Container();
            },
          );
        }
        return Container();
      },
    );
  }
}
