import 'dart:convert';

import 'package:absenkuv3/Bloc/Dropdown/DropdownJenisIzinBloc.dart';
import 'package:absenkuv3/Repository/Model/mIzin.dart';
import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shimmer/shimmer.dart';

class DropdownJenisIzin extends StatefulWidget {
  final color;
  final double fontSize;
  final String? initialData;
  final double? formHeight;
  DropdownJenisIzin(
      {this.initialData,
      this.color = Colors.grey,
      this.fontSize = 14,
      this.formHeight});

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

class _DropdownJenisIzinState extends State<DropdownJenisIzin> {
  @override
  void initState() {
    super.initState();
    BlocProvider.of<DropdownJenisIzinBloc>(context).add(GetDataDropdown());
  }

  Future getDataBahasa() async {
    String jsonString;
    String bahasa = await sharedPreferences().getBahasa();
    if (bahasa == 'id') {
      jsonString = await rootBundle
          .loadString('assets/id/template/template_dropdown_jenis_izin.json');
    } else {
      jsonString = await rootBundle
          .loadString('assets/en/template/template_dropdown_jenis_izin.json');
    }
    var data = json.decode(jsonString);
    return data;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getDataBahasa(),
        builder: (context, snapshot) {
          return Container(
            margin: EdgeInsets.only(bottom: 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Text(
                    snapshot.data == null
                        ? ''
                        : snapshot.data['template_dropdown_jenis_izin']
                            ['title'],
                    style: TextStyle(
                        color: widget.color,
                        fontWeight: FontWeight.bold,
                        fontSize: widget.fontSize),
                  ),
                ),
                BlocBuilder<DropdownJenisIzinBloc, DropdownState>(
                  builder: (BuildContext context, DropdownState state) {
                    if (state is DropdownSuccessState)
                      return Container(
                        height: widget.formHeight ?? CustomStyle.formHeight,
                        padding: EdgeInsets.only(right: 12),
                        decoration: BoxDecoration(
                            border: Border.all(
                                width: 0.8, //
                                color: CustomStyle
                                    .fontColorBlack! //                  <--- border width here
                                ),
                            borderRadius:
                                new BorderRadius.all(Radius.circular(6))),
                        child: DropdownButton(
                          isExpanded: true,
                          underline: Container(),
                          elevation: 2,
                          style: TextStyle(
                              color: widget.color,
                              fontSize: 13,
                              fontWeight: FontWeight.normal),
                          icon: Icon(Icons.keyboard_arrow_down),
                          hint: Container(
                              padding: EdgeInsets.only(left: 12),
                              child: Text(
                                widget.initialData != null
                                    ? widget.initialData!
                                    : snapshot.data == null
                                        ? ''
                                        : '${snapshot.data['template_dropdown_jenis_izin']['subtitle']}',
                                style: TextStyle(
                                    color: widget.color,
                                    fontWeight: FontWeight.normal),
                              )),
                          value: state.selectedValue,
                          items: state.dropdownRespon!.data!.map((item) {
                            return DropdownMenuItem(
                              child: Container(
                                  padding: EdgeInsets.only(left: 12),
                                  child: Text(
                                    item.nama!,
                                  )),
                              value: item,
                            );
                          }).toList(),
                          onChanged: (dynamic value) =>
                              BlocProvider.of<DropdownJenisIzinBloc>(context)
                                  .add(SelectDataDropdown(value)),
                        ),
                      );
                    else
                      return Container(
                        height: widget.formHeight ?? CustomStyle.formHeight,
                        width: MediaQuery.of(context).size.width,
                        child: Shimmer.fromColors(
                          baseColor: Colors.grey[200]!,
                          highlightColor: Colors.white,
                          period: Duration(seconds: 4),
                          child: Card(),
                        ),
                      );
                  },
                ),
              ],
            ),
          );
        });
  }
}

class DropdownJenisIzinV2 extends StatefulWidget {
  // final Color color;
  final double fontSize;
  final String? initialData;
  final double? formHeight;
  final double marginHorizontal;

  DropdownJenisIzinV2({
    this.initialData,
    // this.color = Colors.grey,
    this.fontSize = 14,
    this.formHeight,
    this.marginHorizontal = 0,
  });

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

class _DropdownJenisIzinV2State extends State<DropdownJenisIzinV2> {
  String? selectedValue;
  Map? labelText;

  @override
  void initState() {
    super.initState();
    BlocProvider.of<DropdownJenisIzinBloc>(context).add(GetDataDropdown());
    loadTemplateLabel();
  }

  Future<void> loadTemplateLabel() async {
    String jsonString;
    String bahasa = await sharedPreferences().getBahasa();
    if (bahasa == 'id') {
      jsonString = await rootBundle
          .loadString('assets/id/template/template_dropdown_jenis_izin.json');
    } else {
      jsonString = await rootBundle
          .loadString('assets/en/template/template_dropdown_jenis_izin.json');
    }

    var data = json.decode(jsonString);
    setState(() {
      labelText = data['template_dropdown_jenis_izin'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(
        // horizontal: widget.marginHorizontal,
        vertical: 12,
      ),
      child: BlocBuilder<DropdownJenisIzinBloc, DropdownState>(
        builder: (BuildContext context, DropdownState state) {
          if (state is DropdownSuccessState) {
            final items = state.dropdownRespon?.data ?? [];
            return DropdownButtonFormField(
              value: selectedValue,
              isExpanded:
                  true, // penting untuk membiarkan dropdown mengikuti lebar parent
              decoration: InputDecoration(
                isDense: true,
                fillColor: Colors.transparent,
                filled: false,
                label: labelText == null
                    ? null
                    : Column(
                        // gunakan Column untuk multi-line label
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            labelText!['title'],
                            style: TextStyle(
                              fontSize: widget.fontSize,
                              fontWeight: FontWeight.w400,
                              color: selectedValue == null
                                  ? Colors.grey
                                  : Colors.black,
                            ),
                            softWrap: true,
                            maxLines: 2, // atau lebih sesuai kebutuhan
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: 2),
                          Text(
                            '*',
                            style: TextStyle(
                              fontSize: widget.fontSize,
                              color: Colors.red,
                            ),
                          ),
                        ],
                      ),
                contentPadding: EdgeInsets.symmetric(
                  vertical: 10,
                  horizontal: 8, // tambah horizontal untuk memberi ruang
                ),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(
                    color: CustomStyle.colorLineFormDropdown,
                  ),
                ),
              ),
              items: items.map((item) {
                return DropdownMenuItem(
                  value: item.nama,
                  child: Text(
                    item.nama ?? '',
                    style: TextStyle(fontSize: 13),
                    softWrap: true,
                    maxLines: 2, // max line untuk item dalam dropdown
                    overflow: TextOverflow.ellipsis,
                  ),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  selectedValue = value;
                });
                DataJenisIzin? selectedItem;
                try {
                  selectedItem = items.firstWhere((e) => e.nama == value);
                } catch (e) {
                  selectedItem = null;
                }

                if (selectedItem != null) {
                  BlocProvider.of<DropdownJenisIzinBloc>(context)
                      .add(SelectDataDropdown(selectedItem));
                }
              },
            );

            // return
            // DropdownButtonFormField(
            //     value: selectedValue,
            //     isExpanded: true,
            //     decoration: InputDecoration(

            //       enabled: false,
            //       fillColor: Colors.transparent,
            //       filled: false,
            //       label: labelText == null
            //           ? null
            //           : Row(
            //               children: [
            //                 Text(
            //                   labelText!['title'],
            //                   style: TextStyle(
            //                     fontSize: widget.fontSize,
            //                     fontWeight: FontWeight.w400,
            //                     color: selectedValue == null
            //                         ? Colors.grey
            //                         : Colors.black,
            //                   ),
            //                 ),
            //                 SizedBox(width: 5),
            //                 Text(
            //                   '*',
            //                   style: TextStyle(
            //                     fontSize: widget.fontSize,
            //                     color: Colors.red,
            //                   ),
            //                 ),
            //               ],
            //             ),
            //       contentPadding: EdgeInsets.symmetric(vertical: 10),
            //       enabledBorder: UnderlineInputBorder(
            //         borderSide: BorderSide(
            //           color: CustomStyle.colorLineFormDropdown,
            //         ),
            //       ),
            //     ),
            //     items: items.map((item) {
            //       return DropdownMenuItem(
            //         value: item.nama,
            //         child: Text(
            //           item.nama ?? '',
            //           style: TextStyle(fontSize: 13),
            //           softWrap: true,
            //           maxLines: 2,
            //           overflow: TextOverflow.ellipsis,
            //         ),
            //       );
            //     }).toList(),
            //     onChanged: (value) {
            //       setState(() {
            //         selectedValue = value;
            //       });
            //       DataJenisIzin? selectedItem;
            //       try {
            //         selectedItem = items.firstWhere((e) => e.nama == value);
            //       } catch (e) {
            //         selectedItem = null;
            //       }

            //       // final selectedItem = items.firstWhere((e) => e.nama == value,
            //       //     orElse: () => null);

            //       if (selectedItem != null) {
            //         BlocProvider.of<DropdownJenisIzinBloc>(context)
            //             .add(SelectDataDropdown(selectedItem));
            //       }
            //     });
          }

          return Container(
            height: widget.formHeight ?? CustomStyle.formHeight,
            width: MediaQuery.of(context).size.width,
            child: Shimmer.fromColors(
              baseColor: Colors.grey[200]!,
              highlightColor: Colors.white,
              period: Duration(seconds: 4),
              child: Card(),
            ),
          );
        },
      ),
    );
  }
}

// class DropdownJenisIzinV2 extends StatefulWidget {
//   final color;
//   final double fontSize;
//   final String? initialData;
//   final double? formHeight;
//   double marginHorizontal;
//   DropdownJenisIzinV2(
//       {this.initialData,
//       this.color = Colors.grey,
//       this.fontSize = 14,
//       this.formHeight,
//       this.marginHorizontal = 0});

//   @override
//   _DropdownJenisIzinV2State createState() => _DropdownJenisIzinV2State();
// }

// class _DropdownJenisIzinV2State extends State<DropdownJenisIzinV2> {
//   TextEditingController _controller = TextEditingController();

//   @override
//   void initState() {
//     super.initState();
//     BlocProvider.of<DropdownJenisIzinBloc>(context).add(GetDataDropdown());
//   }

//   Future getDataBahasa() async {
//     String jsonString;
//     String bahasa = await sharedPreferences().getBahasa();
//     if (bahasa == 'id') {
//       jsonString = await rootBundle
//           .loadString('assets/id/template/template_dropdown_jenis_izin.json');
//     } else {
//       jsonString = await rootBundle
//           .loadString('assets/en/template/template_dropdown_jenis_izin.json');
//     }
//     var data = json.decode(jsonString);
//     return data;
//   }

//   @override
//   Widget build(BuildContext context) {
//     return FutureBuilder(
//         future: getDataBahasa(),
//         builder: (context, snapshot) {
//           return Container(
//             // margin: EdgeInsets.only(
//             //     bottom: 12,
//             //     top: 11,
//             //     left: widget.marginHorizontal,
//             //     right: widget.marginHorizontal),
//             margin: EdgeInsets.only(right: 10, bottom: 12),
//             child: Column(
//               crossAxisAlignment: CrossAxisAlignment.start,
//               children: [
//                 BlocBuilder<DropdownJenisIzinBloc, DropdownState>(
//                   builder: (BuildContext context, DropdownState state) {
//                     if (state is DropdownSuccessState)
//                       return Container(
//                         child: DropdownMenu(
//                           dropdownMenuEntries:
//                               state.dropdownRespon!.data!.map((item) {
//                             return DropdownMenuEntry(
//                                 value: item, label: item.nama!);
//                           }).toList(),
//                           inputDecorationTheme: InputDecorationTheme(
//                             contentPadding: EdgeInsets.symmetric(vertical: 7.0),
//                             enabledBorder: UnderlineInputBorder(
//                                 borderSide: BorderSide(
//                                     color: CustomStyle.colorLineFormDropdown)),
//                           ),
//                           controller: _controller,
//                           onSelected: (value) =>
//                               BlocProvider.of<DropdownJenisIzinBloc>(context)
//                                   .add(SelectDataDropdown(value!)),
//                           label: Row(
//                             children: [
//                               Text(snapshot.data == null
//                         ? ''
//                         : snapshot.data['template_dropdown_jenis_izin']
//                             ['title'],
//                                   style: TextStyle(
//                                       fontSize: widget.fontSize,
//                                       fontWeight: FontWeight.w400)),
//                               SizedBox(width: 7),
//                               Text('*',
//                                   style: TextStyle(
//                                       color: Colors.red,
//                                       fontSize: widget.fontSize)),
//                             ],
//                           ),
//                           textStyle: TextStyle(fontSize: 13),
//                           requestFocusOnTap: false,
//                           width: MediaQuery.of(context).size.width-20,
//                         ),
//                       );
//                     else
//                       return Container(
//                         height: widget.formHeight ?? CustomStyle.formHeight,
//                         width: MediaQuery.of(context).size.width,
//                         child: Shimmer.fromColors(
//                           baseColor: Colors.grey[200]!,
//                           highlightColor: Colors.white,
//                           period: Duration(seconds: 4),
//                           child: Card(),
//                         ),
//                       );
//                   },
//                 ),
//               ],
//             ),
//           );
//         });
//   }
// }
