import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/UI/Template/AutoComplete/Bloc/AutoCompletePegawaiBloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../style.dart';
import '../../templateForm.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownCabangBloc.dart' as cabang;
import 'package:absenkuv3/Bloc/Dropdown/DropdownDepartemenBloc.dart' as departemen;
// ignore: must_be_immutable
class AutoCompletePegawai extends StatefulWidget {
  ModelFilter? modelFilter;
  String? initialData;
  double? formHeight;
  double? radius;
  String? title;
  double? fontSize;
  Icon? prefixIcon;
  AutoCompletePegawai(this.modelFilter,{this.radius, this.formHeight, this.initialData, this.title, this.prefixIcon, this.fontSize});
  @override
  _AutoCompletePegawaiState createState() => _AutoCompletePegawaiState();
}

class _AutoCompletePegawaiState extends State<AutoCompletePegawai> {
  TextEditingController keyword = new TextEditingController();
  ModelFilter modelFilter = new ModelFilter();
  bool openDropdown = false;
  DataDropdown? selectedPegawai;

  @override
  void initState() {
    super.initState();
    print('initAutoComplete');
    modelFilter = new ModelFilter();
    keyword.addListener(cariListener);
  }

  cariListener() {
    if(keyword.text.length>2){
      BlocProvider.of<AutoCompletePegawaiBloc>(context).add(GetPegawai(keyword.text, modelFilter));
      setState(() {
        if(keyword.text!=""&&keyword.text!=null)
          openDropdown = true;
        else openDropdown = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return 
    MultiBlocListener(listeners: [
        BlocListener<cabang.DropdownCabangBloc, cabang.DropdownState>(
          listener: (BuildContext context, cabang.DropdownState state){
          if(state is cabang.DropdownSuccessState && state.selectedValue!=null){
            modelFilter.idCabang = state.selectedValue!.id;
            print("ID CABANG AUTOCOMPLETE ${modelFilter.idCabang}");
          }

        },),
        BlocListener<departemen.DropdownDepartemenBloc, departemen.DropdownState>(
          listener: (BuildContext context, departemen.DropdownState state){
          if(state is departemen.DropdownSuccessState && state.selectedValue!=null){
            modelFilter.idDepartemen = state.selectedValue!.id;
            print("ID DEPARTEMEN AUTOCOMPLETE ${modelFilter.idDepartemen}");
          }
        }),
    ],
        child: FutureBuilder<String>(
                future: PengaturanBahasa().getDataBahasa(),
                builder: (context, snapshot) {
                  return Container(
                    margin: EdgeInsets.only(bottom: 12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        BlocBuilder<AutoCompletePegawaiBloc, AutoCompletePegawaiState>(
                          builder: (BuildContext context, AutoCompletePegawaiState state){
                            if(state is SetPegawaiSuccess && state.pegawai!=null) {
                              selectedPegawai = state.pegawai;
                              return TemplateForm(
                                fontSize:widget.fontSize??null,
                                titleText:widget.title??null,
                                prefixIcon: widget.prefixIcon??null,
                                hintText: selectedPegawai!=null?selectedPegawai!.nama: snapshot.data == null || snapshot.data == 'en' ? "All Employee" : "Semua Pegawai",
                                controller: keyword,
                                color: CustomStyle.fontColorBlack,
                                formHeight: widget.formHeight,
                                radius: widget.radius,
                                bottomMargin: 0,
                                buttonEnd: GestureDetector(
                                    onTap: ()=>BlocProvider.of<AutoCompletePegawaiBloc>(context).add(SetPegawai(null)),
                                    child: Icon(Icons.close, color: Colors.red, size: 22,)),
                              );
                            }
                            else {
                              selectedPegawai = null;
                              return TemplateForm(
                                fontSize:widget.fontSize??null,
                                titleText:widget.title??null,
                                prefixIcon: widget.prefixIcon??null,
                                hintText: selectedPegawai!=null?selectedPegawai!.nama:snapshot.data == null || snapshot.data == 'en' ? "All Employee" : "Semua Pegawai",
                                controller: keyword,
                                color: CustomStyle.fontColorBlack,
                                formHeight: widget.formHeight,
                                radius: widget.radius,
                                bottomMargin: 0,);
                            }},
                        ),
                        openDropdown?BlocBuilder<AutoCompletePegawaiBloc, AutoCompletePegawaiState>(
                            builder: (BuildContext context, AutoCompletePegawaiState state){
                              if(state is GetPegawaiSuccess) return Container(
                                margin: EdgeInsets.only(top: 6),
                                padding: EdgeInsets.fromLTRB(8,4,8,12),
                                decoration: BoxDecoration(
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.grey.withOpacity(0.16),
                                        spreadRadius: 1,
                                        blurRadius: 7,
                                        offset: Offset(0, 1), // changes position of shadow
                                      ),
                                    ],
                                    color: Colors.white,
                                    borderRadius: new BorderRadius.all(Radius.circular(0))
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: state.listPegawai!
                                      .map((item) => templateContentAutoComplete(item))
                                      .toList(),
                                ),
                              );
                              else if(state is ProgressState) return Container(
                                  height: 100,
                                  child: Center(child: CircularProgressIndicator(strokeWidth: 8,)));
                              else return Container(
                                    height: 100,
                                    child: Center(child: Text(snapshot.data == null || snapshot.data == 'en' ? "Employee not found" : "Pegawai tidak ditemukan", style: TextStyle(fontSize: CustomStyle.fontSizeSmall),),));
                            }):Container(),
                      ],
                    ),
                  );
                }
        ));
  
  }

  Widget templateContentAutoComplete(DataDropdown data){
    return GestureDetector(
      onTap: (){
        setState(() {
          keyword.text = "";
          selectedPegawai = data;
          openDropdown = false;
          FocusScopeNode currentFocus = FocusScope.of(context);

          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
        });
        BlocProvider.of<AutoCompletePegawaiBloc>(context).add(SetPegawai(data));
      },
      child: Container(
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide( //                   <--- left side
                  color: Colors.grey[300]!,
                  width: 0.5,
                ),
              )),
          padding: EdgeInsets.fromLTRB(14,16,14,16),
          child: Text(data.nama!, style: TextStyle(fontSize: widget.fontSize??CustomStyle.fontSizeSmall),)),
    );
  }
}
