// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import '../Adv4_viewModel/Adv4_view_model_screen.dart';
import '../../../../utils/image_constant.dart';
import '../../../../utils/size_utils.dart';
import '../../../../theme/app_style.dart';
import '../../../../widgets/app_bar/appbar_image.dart';
import '../../../../widgets/app_bar/appbar_title.dart';
import '../../../../widgets/app_bar/custom_app_bar.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart'; 
import '../../../../widgets/custom_dropdown_field.dart';
import 'dart:math';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:intl/intl.dart';
 
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart'
;import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:just_audio/just_audio.dart';
import 'package:video_player/video_player.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lottie/lottie.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'dart:io';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';










class adv4CreateEntityScreen extends StatefulWidget {
  const adv4CreateEntityScreen({super.key});

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

class _adv4CreateEntityScreenState extends State<adv4CreateEntityScreen> {

final Map<String, dynamic> formData = {};
  final _formKey = GlobalKey<FormState>();

List<Map<String, dynamic>> atocItems = [];
  int? selectedatocId; // to store selected state id

  String selectedatocValue = ''; // Use nullable type  Future<void> _load

  TextEditingController atocController = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> atockey = GlobalKey();
Future<List<Map<String, dynamic>>> _loadatocItems() async {
final provider =
          Provider.of<Adv4ViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getatoc();
      print('atoc data is : $selectTdata');

      if (selectTdata != null &&selectTdata.isNotEmpty) {


 

             atocItems = selectTdata;

 

        return atocItems;
      } else {
        print('atoc data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load atoc items: $e');
      return [];
    }
  }



List<Map<String, dynamic>> atc2Items = [];
  int? selectedatc2Id; // to store selected state id

  String selectedatc2Value = ''; // Use nullable type  Future<void> _load

  TextEditingController atc2Controller = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> atc2key = GlobalKey();
Future<List<Map<String, dynamic>>> _loadatc2Items() async {
final provider =
          Provider.of<Adv4ViewModelScreen>(context, listen: false);
    try {
      final selectTdata = await provider.getatc2();
      print('atc2 data is : $selectTdata');

      if (selectTdata != null &&selectTdata.isNotEmpty) {


 

             atc2Items = selectTdata;

 

        return atc2Items;
      } else {
        print('atc2 data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load atc2 items: $e');
      return [];
    }
  }


 List<String> atdy1Items = [];
  List<String> selectedatdy1Value = []; 

  TextEditingController atdy1Controller = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> atdy1key = GlobalKey();
Future<List<String>> _loadatdy1Items() async {
final provider =
          Provider.of<Adv4ViewModelScreen>(context, listen: false);

    try {
      final selectTdata = await provider.getatdy1();
      print('atdy1 data is : $selectTdata');

      if (selectTdata != null && selectTdata.isNotEmpty) {


 

        List<String> datareturned = [];
        selectTdata.forEach((element) {
if (element['name'] != null)
          datareturned.add(element['name']);
        });
 

        return datareturned;
      } else {
        print('atdy1 data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load atdy1 items: $e');
      return [];
    }
  }

 List<String> atdy2Items = [];
  List<String> selectedatdy2Value = []; 

  TextEditingController atdy2Controller = TextEditingController();
  GlobalKey<AutoCompleteTextFieldState<String>> atdy2key = GlobalKey();
Future<List<String>> _loadatdy2Items() async {
final provider =
          Provider.of<Adv4ViewModelScreen>(context, listen: false);

    try {
      final selectTdata = await provider.getatdy2();
      print('atdy2 data is : $selectTdata');

      if (selectTdata != null && selectTdata.isNotEmpty) {


 

        List<String> datareturned = [];
        selectTdata.forEach((element) {
if (element['name'] != null)
          datareturned.add(element['name']);
        });
 

        return datareturned;
      } else {
        print('atdy2 data is null or empty');
        return [];
      }
    } catch (e) {
      print('Failed to load atdy2 items: $e');
      return [];
    }
  }

  Widget buildFormField(String fieldOption) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16.0),
      child: Card(
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: TextFormField(
            decoration: InputDecoration(
              labelText: fieldOption,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            onSaved: (value) {
              if (formData['support'] == null) {
                formData['support'] = {};
              }
              formData['support'][fieldOption] = value;
            },
          ),
        ),
      ),
    );
  }

 @override
  void initState() {
    super.initState(); 
    final provider = Provider.of<Adv4ViewModelScreen>(context, listen: false);










} 

  

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<Adv4ViewModelScreen>(context, listen: false);
    return Scaffold(
      appBar: CustomAppBar(
          height: getVerticalSize(49),
          leadingWidth: 40,
          leading: AppbarImage(
              height: getSize(24),
              width: getSize(24),
              svgPath: ImageConstant.imgArrowleftBlueGray900,
              margin: getMargin(left: 16, top: 12, bottom: 13),
              onTap: () {
                Navigator.pop(context);
              }),
          centerTitle: true,
          title: AppbarTitle(text: "Create Adv4"),
 actions: [










],
 ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                 FutureBuilder<List<Map<String, dynamic>>>(
                  future: _loadatocItems(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      if (snapshot.hasError) {
                        return Text('Error: ${snapshot.error}');
                      }

                      final atoc = snapshot.data ?? [];
                      final fieldNameItems = atoc
                          .map((e) => e['name'])
                          .where((name) => name != null)
                          .cast<String>()
                          .toList();

                      return Autocomplete<String>(
                        optionsBuilder: (TextEditingValue textEditingValue) {
                          if (textEditingValue.text.isEmpty) {
                            return const Iterable<String>.empty();
                          } else {
                            return fieldNameItems.where((String option) {
                              return option.toLowerCase().contains(
                                  textEditingValue.text.toLowerCase());
                            });
                          }
                        },
                        onSelected: (String selection) {
                          setState(() {

 
                            selectedatocValue = selection;
                            selectedatocId = atoc.firstWhere((element) =>
                                element['name'] == selection)['id'];
 

                            formData['atoc'] = selectedatocId;
                          });
                        },
                        fieldViewBuilder: (BuildContext context,
                            TextEditingController textEditingController,
                            FocusNode focusNode,
                            VoidCallback onFieldSubmitted) {
                          return TextFormField(
                            controller: textEditingController,
                            focusNode: focusNode,
                            decoration: InputDecoration(
                              contentPadding:
                                  const EdgeInsets.symmetric(horizontal: 16.0),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurple, width: 2),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurple, width: 2),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurpleAccent, width: 2),
                              ),
                              hintText: 'Select atoc',
                              hintStyle: TextStyle(color: Colors.grey[600]),
                            ),
                          );
                        },
                      );
                    } else if (snapshot.connectionState ==
                        ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    } else {
                      return Text('Loading...');
                    }
                  },
                ),
                const SizedBox(height: 16),
                Text('Selected Value: $selectedatocValue'),

                FutureBuilder<List<Map<String, dynamic>>>(
                  future: _loadatc2Items(),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      if (snapshot.hasError) {
                        return Text('Error: ${snapshot.error}');
                      }

                      final atc2 = snapshot.data ?? [];
                      final fieldNameItems = atc2
                          .map((e) => e['name'])
                          .where((name) => name != null)
                          .cast<String>()
                          .toList();

                      return Autocomplete<String>(
                        optionsBuilder: (TextEditingValue textEditingValue) {
                          if (textEditingValue.text.isEmpty) {
                            return const Iterable<String>.empty();
                          } else {
                            return fieldNameItems.where((String option) {
                              return option.toLowerCase().contains(
                                  textEditingValue.text.toLowerCase());
                            });
                          }
                        },
                        onSelected: (String selection) {
                          setState(() {

 
                            selectedatc2Value = selection;
                            selectedatc2Id = atc2.firstWhere((element) =>
                                element['name'] == selection)['id'];
 

                            formData['atc2'] = selectedatc2Id;
                          });
                        },
                        fieldViewBuilder: (BuildContext context,
                            TextEditingController textEditingController,
                            FocusNode focusNode,
                            VoidCallback onFieldSubmitted) {
                          return TextFormField(
                            controller: textEditingController,
                            focusNode: focusNode,
                            decoration: InputDecoration(
                              contentPadding:
                                  const EdgeInsets.symmetric(horizontal: 16.0),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurple, width: 2),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurple, width: 2),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                                borderSide: BorderSide(
                                    color: Colors.deepPurpleAccent, width: 2),
                              ),
                              hintText: 'Select atc2',
                              hintStyle: TextStyle(color: Colors.grey[600]),
                            ),
                          );
                        },
                      );
                    } else if (snapshot.connectionState ==
                        ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    } else {
                      return Text('Loading...');
                    }
                  },
                ),
                const SizedBox(height: 16),
                Text('Selected Value: $selectedatc2Value'),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "atdy1",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loadatdy1Items(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final atdy1Items = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return atdy1Items.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selectedatdy1Value.contains(selection)) {
                          selectedatdy1Value.remove(selection);
                        } else {
                          selectedatdy1Value.add(selection);
                        }
                        formData['atdy1'] = selectedatdy1Value.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter atdy1",
                          filled: true,
                          fillColor: Colors.grey[200],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 20),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),
            SizedBox(height: 16),
            Text(
              'Selected Values:',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Wrap(
              spacing: 8.0,
              children: selectedatdy1Value.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selectedatdy1Value.remove(value);
                      formData['atdy1'] = selectedatdy1Value.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "atdy2",
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF4A4A4A), // BlueGray900 color
              ),
            ),
            SizedBox(height: 10),
            FutureBuilder<List<String>>(
              future: _loadatdy2Items(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done) {
                  final atdy2Items = snapshot.data ?? [];
                  return Autocomplete<String>(
                    optionsBuilder: (TextEditingValue textEditingValue) {
                      if (textEditingValue.text.isEmpty) {
                        return const Iterable<String>.empty();
                      } else {
                        return atdy2Items.where((String option) {
                          return option.toLowerCase().contains(textEditingValue.text.toLowerCase());
                        });
                      }
                    },
                    onSelected: (String selection) {
                      setState(() {
                        if (selectedatdy2Value.contains(selection)) {
                          selectedatdy2Value.remove(selection);
                        } else {
                          selectedatdy2Value.add(selection);
                        }
                        formData['atdy2'] = selectedatdy2Value.join(',');
                      });
                    },
                    fieldViewBuilder: (BuildContext context,
                        TextEditingController textEditingController,
                        FocusNode focusNode,
                        VoidCallback onFieldSubmitted) {
                      return TextField(
                        controller: textEditingController,
                        focusNode: focusNode,
                        decoration: InputDecoration(
                          hintText: "Enter atdy2",
                          filled: true,
                          fillColor: Colors.grey[200],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(
                              vertical: 15, horizontal: 20),
                        ),
                      );
                    },
                  );
                } else {
                  return Center(child: CircularProgressIndicator());
                }
              },
            ),
            SizedBox(height: 16),
            Text(
              'Selected Values:',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            Wrap(
              spacing: 8.0,
              children: selectedatdy2Value.map((value) {
                return Chip(
                  label: Text(value),
                  deleteIcon: Icon(Icons.clear),
                  onDeleted: () {
                    setState(() {
                      selectedatdy2Value.remove(value);
                      formData['atdy2'] = selectedatdy2Value.join(',');
                    });
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),

Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            height: 20,
            child: Text(
              'Support',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          const SizedBox(height: 16), // Add space between elements

 
          
          buildFormField('description'),
 

 
          
          buildFormField('name'),
 
		

        ],
      ),
    ),

   const SizedBox(width: 8),
                CustomButton(
                  height: getVerticalSize(50),
                  text: "Submit",
                  margin: getMargin(top: 24, bottom: 5),
                  onTap: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save(); 










 
                      try {
                        print(formData);
  Map<String, dynamic> createdEntity =  await provider.createEntity(formData); 










 

                        Navigator.pop(context);
                      } catch (e) {
                        // ignore: use_build_context_synchronously
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: const Text('Error'),
                              content: Text('Failed to create Adv4: $e'),
                              actions: [
                                TextButton(
                                  child: const Text('OK'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      }
                    }
                  },
                ),










   ],
          ),
              ),
            ),
          ),
     );
  }
}