// 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 '../Testm_viewModel/Testm_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 testmCreateEntityScreen extends StatefulWidget {
  const testmCreateEntityScreen({super.key});

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

class _testmCreateEntityScreenState extends State<testmCreateEntityScreen> {

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


  final TextEditingController fieldggController = 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>>> _dataggdataFuture; // Data from fetchData

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

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

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

  Future<List<Map<String, dynamic>>> valuellfetchData() async {
    
    final resp = await apiService.getEntities();

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


  void showvaluellDialog(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: _valuelldataFuture,
              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 = [

                    
 

                    'namem', 
                     

                    ];
                  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(() {

 
                                namemController.text = item['namem'] ?? '';
 

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


  final TextEditingController numbermController = TextEditingController();


  final TextEditingController numberbController = TextEditingController();



  
  String calculatedggOperator = '+';
  String calculatedggresult = '';

  final List<String> calculatedggoperators = ['+', '-', '*', '/'];

  void calculatecalculatedggResult() {
    int calculation;
    switch (calculatedggOperator) {
      case '+':
        calculation = 

 
int.parse(numbermController.text) +

  

 
int.parse(numberbController.text) +

  

0;


        break;
      case '-':
        calculation =

 
int.parse(numbermController.text) -
  

 
int.parse(numberbController.text) -
  

0;
        break;
      case '*':
        calculation =

 
int.parse(numbermController.text) *
  

 
int.parse(numberbController.text) *
  

1;
        break;
      case '/':
        if (

 
int.parse(numbermController.text)== 0 || 
  

 
int.parse(numberbController.text)== 0 || 
  



1 != 1) {
          calculatedggresult = 'Division by zero error';
          return;
        }
        calculation = (

 
int.parse(numbermController.text) /
  

 
int.parse(numberbController.text) /
  


1).toInt();
        break;
      default:
        calculation = 0;
    }
    setState(() {
      calculatedggresult = 'Result: $calculation';
    });
  }

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






    _dataggdataFuture = dataggfetchData(); // Initialize _dataFuture with the function


    _valuelldataFuture = valuellfetchData(); // Initialize _dataFuture with the function








} 

  

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<TestmViewModelScreen>(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 Testm"),







 actions: [
          IconButton(
            icon: const Icon(Icons.grid_on),
            onPressed: () {
              showvaluellDialog(context);
            },
          ),
        ],







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

  onSaved:(value) => formData['namem'] = value ,
  label:"Enter Namem",
  // 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(
        "Fieldgg",
        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('namemmm'),
 
		

        ],
      ),
    ),





ReusableTextField(
                  controller: numbermController,

              onSaved:(value) => formData['numberm'] = value ,
              label: "Enter Numberm",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 

ReusableTextField(
                  controller: numberbController,

              onSaved:(value) => formData['numberb'] = value ,
              label: "Enter Numberb",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 

     
            const SizedBox(height: 8.0),
            DropdownButtonFormField<String>(
              value: calculatedggOperator,
              items: calculatedggoperators.map((String operator) {
                return DropdownMenuItem(
                  value: operator,
                  child: Text(operator),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  calculatedggOperator = value!;
                  print(calculatedggOperator.toString());
                  print("value-- $value");
                });
              },
              decoration: const InputDecoration(labelText: 'Operator'),
            ),
            const SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () {
                if (_formKey.currentState!.validate()) {
                  _formKey.currentState?.save();  // Save the form fields

                }
                calculatecalculatedggResult();
                setState(() {

                });
              },
              child: const Text('Calculate'),
            ),
            const SizedBox(height: 20.0),
            Text(calculatedggresult,style: TextStyle(color: Colors.black),),

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






                SizedBox(height: 16),

FutureBuilder<List<Map<String, dynamic>>>(
      future: _dataggdataFuture,
      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),










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