// 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 '../Testss_viewModel/Testss_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 testssCreateEntityScreen extends StatefulWidget {
  const testssCreateEntityScreen({super.key});

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

class _testssCreateEntityScreenState extends State<testssCreateEntityScreen> {

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


  final TextEditingController field_groupController = TextEditingController();


  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['child'] == null) {
                formData['child'] = {};
              }
              formData['child'][fieldOption] = value;
            },
          ),
        ),
      ),
    );
  }

  late Future<List<Map<String, dynamic>>> _value_list_fielddataFuture; // Data from fetchData

  Future<List<Map<String, dynamic>>> value_list_fieldfetchData() async {
    
final provider =
          Provider.of<TestssViewModelScreen>(context, listen: false);
    final resp = await provider.getEntities();

      if (resp != null) {
             return resp;
      } else {
        throw Exception('Failed to load data: ');
      }
  
  }


  void showvalue_list_fieldDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: AlertDialog(
            title: const Text('Select a record'),
            content: FutureBuilder<List<Map<String, dynamic>>>(
              future: _value_list_fielddataFuture,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                } else if (snapshot.hasError) {
                  return Center(child: Text('Error: ${snapshot.error}'));
                } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
                  return const Center(child: Text('No data available..'));
                } else {
final List<String> columnsToShow = [

                    
 

                    'name', 
                     

                    ];
                  return SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: DataTable(
                      columnSpacing: 30,
                      headingRowColor: MaterialStateColor.resolveWith(
                          (states) => Colors.blue.shade100),
                      dataRowColor: MaterialStateColor.resolveWith(
                          (states) => Colors.white),
                      dividerThickness: 0.5,
                      columns: columnsToShow
                          .map(
                            (key) => DataColumn(
                              label: Text(
                                key,
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold, fontSize: 16),
                              ),
                            ),
                          )
                          .toList(),
                      rows: snapshot.data!.map((item) {
                        return DataRow(
                            cells: columnsToShow.map((key) {
                          return DataCell(
                            Text(
                              item[key].toString(),
                              style: const TextStyle(fontSize: 14),
                            ),
                            onTap: () {
                              setState(() {

 
                                nameController.text = item['name'] ?? '';
 

                                // Add more fields as needed
                              });
                              Navigator.pop(context);
                            },
                          );
                        }).toList());
                      }).toList(),
                    ),
                  );
                }
              },
            ),
            actions: [
              TextButton(
                child: const Text('Close'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        );
      },
    );
  }


  late Future<List<Map<String, dynamic>>> _datagrid_fielddataFuture; // Data from fetchData

  Future<List<Map<String, dynamic>>> datagrid_fieldfetchData() async {
    
final provider =
          Provider.of<TestssViewModelScreen>(context, listen: false);
    final resp = await provider.getdatagrid_fieldGrid();

      if (resp != null) {
             return resp;
      } else {
        throw Exception('Failed to load data: ');
      }
  
  }

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






    _value_list_fielddataFuture = value_list_fieldfetchData(); // Initialize _dataFuture with the function


    _datagrid_fielddataFuture = datagrid_fieldfetchData(); // Initialize _dataFuture with the function


} 

  

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<TestssViewModelScreen>(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 Testss"),
 actions: [






Padding(
    padding: const EdgeInsets.only(right: 10),
    child: InkWell(
      onTap: () {
        showvalue_list_fieldDialog(context);
      },
      borderRadius: BorderRadius.circular(12),
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            colors: [Colors.deepPurple, Colors.purpleAccent],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.deepPurpleAccent.withOpacity(0.3),
              spreadRadius: 2,
              blurRadius: 8,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: const Icon(
          Icons.grid_on,
          color: Colors.white,
          size: 28,
        ),
      ),
    ),
  ),
        



],
 ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 ReusableTextField(
                  controller: nameController,

  onSaved:(value) => formData['name'] = value ,
  label:"Enter Name",
  // ValidationProperties
),

  SizedBox(height: 16),


Container(
  padding: EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    color: Colors.grey[200],
    borderRadius: BorderRadius.circular(8.0),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.2),
        spreadRadius: 2,
        blurRadius: 4,
        offset: Offset(0, 2),
      ),
    ],
  ),
  child: Column(
    children: [
      Text(
        "Field Group",
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 16),

 
ReusableTextField(
  onSaved:(value) => formData['bar_code'] = value ,
  label:"Enter Bar_code",
  // ValidationProperties
),

  SizedBox(height: 16),
 

 
ReusableTextField(
  onSaved:(value) => formData['qr_code'] = value ,
  label:"Enter Qr_code",
  // ValidationProperties
),

  SizedBox(height: 16),
 

 SizedBox(height: 16),
    ],
  ),
),
const SizedBox(height: 16),


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

 
          
          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 Testss: $e'),
                              actions: [
                                TextButton(
                                  child: const Text('OK'),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            );
                          },
                        );
                      }
                    }
                  },
                ),








                SizedBox(height: 16),

FutureBuilder<List<Map<String, dynamic>>>(
      future: _datagrid_fielddataFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('No data available..'));
        } else {
          final keys = snapshot.data!.first.keys.toList();

          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: DataTable(
              columnSpacing: 30,
              headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue.shade100),
              dataRowColor: MaterialStateColor.resolveWith((states) => Colors.white),
              dividerThickness: 0.5,
              columns: keys.map(
                    (key) => DataColumn(
                  label: Text(
                    key,
                    style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                  ),
                ),
              )
                  .toList(),
              rows: snapshot.data!.map((item) {
                return DataRow(cells: keys.map((key) {
                  return DataCell(
                    Text(
                      item[key].toString(),
                      style: const TextStyle(fontSize: 14),
                    ),
                  );
                }).toList());
              }).toList(),
            ),
          );
        }
      },
    ),
                SizedBox(height: 16),


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