// 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 '../Adv5_viewModel/Adv5_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 adv5CreateEntityScreen extends StatefulWidget {
  const adv5CreateEntityScreen({super.key});

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

class _adv5CreateEntityScreenState extends State<adv5CreateEntityScreen> {

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


List<Map<String, dynamic>> supportList = [];

  final TextEditingController ageController = TextEditingController();


  final TextEditingController age2Controller = TextEditingController();



  
  String additionOperator = '+';
  String additionresult = '';

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

  void calculateadditionResult() {
    int calculation;
    switch (additionOperator) {
      case '+':
        calculation = 

 
int.parse(ageController.text) +

  

 
int.parse(age2Controller.text) +

  

0;


        break;
      case '-':
        calculation =

 
int.parse(ageController.text) -
  

 
int.parse(age2Controller.text) -
  

0;
        break;
      case '*':
        calculation =

 
int.parse(ageController.text) *
  

 
int.parse(age2Controller.text) *
  

1;
        break;
      case '/':
        if (

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

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



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

 
int.parse(ageController.text) /
  

 
int.parse(age2Controller.text) /
  


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


  
  String subtrationOperator = '+';
  String subtrationresult = '';

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

  void calculatesubtrationResult() {
    int calculation;
    switch (subtrationOperator) {
      case '+':
        calculation = 

 
int.parse(ageController.text) +

  

 
int.parse(age2Controller.text) +

  

0;


        break;
      case '-':
        calculation =

 
int.parse(ageController.text) -
  

 
int.parse(age2Controller.text) -
  

0;
        break;
      case '*':
        calculation =

 
int.parse(ageController.text) *
  

 
int.parse(age2Controller.text) *
  

1;
        break;
      case '/':
        if (

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

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



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

 
int.parse(ageController.text) /
  

 
int.parse(age2Controller.text) /
  


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

  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<Adv5ViewModelScreen>(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 = [

                    
 

                    'age', 
                     

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

 
                                ageController.text = item['age'] ?? '';
 

                                // 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>>> _value_list_field2dataFuture; // Data from fetchData

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

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


  void showvalue_list_field2Dialog(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_field2dataFuture,
              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', 
                     

 

                    'age2', 
                     

 

                    'age', 
                     

                    ];
                  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'] ?? '';
 

 
                                age2Controller.text = item['age2'] ?? '';
 

 
                                ageController.text = item['age'] ?? '';
 

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


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












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


    _value_list_field2dataFuture = value_list_field2fetchData(); // Initialize _dataFuture with the function


} 

  

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

Padding(
    padding: const EdgeInsets.only(right: 10),
    child: InkWell(
      onTap: () {
        showvalue_list_field2Dialog(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),


const SizedBox(
  height: 20,
  child: Text(
    'Support',
    selectionColor: Colors.black,
  ),
),
Container(
  height: 4,
  color: Colors.blue,
),
// One-to-Many Relationship UI
ListView.builder(
  shrinkWrap: true,
  itemCount: supportList.length,
  itemBuilder: (context, index) {
    return Column(
      children: [
       
 
        ReusableTextField(
          //decoration: InputDecoration(
            label: 'Item ${index + 1} - description',
        //  ),
          onSaved: (value) {
            if (supportList.length <= index) {
              supportList.add({});
            }
            supportList[index]['description'] = value;
          },
        ),
        const SizedBox(height: 16),
    

 
        ReusableTextField(
          //decoration: InputDecoration(
            label: 'Item ${index + 1} - name',
        //  ),
          onSaved: (value) {
            if (supportList.length <= index) {
              supportList.add({});
            }
            supportList[index]['name'] = value;
          },
        ),
        const SizedBox(height: 16),
    

        ElevatedButton(
          onPressed: () {
            setState(() {
              supportList.removeAt(index);
            });
          },
          child: const Text('Remove Item'),
        ),
      ],
    );
  },
),
const SizedBox(height: 16),
// Button to add more items
ElevatedButton(
  onPressed: () {
    setState(() {
      supportList.add({});
    });
  },
  child: const Text('Add Item'),
),


ReusableTextField(
                  controller: ageController,

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

SizedBox(height: 16), 

ReusableTextField(
                  controller: age2Controller,

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

SizedBox(height: 16), 

     
            const SizedBox(height: 8.0),
            DropdownButtonFormField<String>(
              value: additionOperator,
              items: additionoperators.map((String operator) {
                return DropdownMenuItem(
                  value: operator,
                  child: Text(operator),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  additionOperator = value!;
                  print(additionOperator.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

                }
                calculateadditionResult();
                setState(() {

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

     
            const SizedBox(height: 8.0),
            DropdownButtonFormField<String>(
              value: subtrationOperator,
              items: subtrationoperators.map((String operator) {
                return DropdownMenuItem(
                  value: operator,
                  child: Text(operator),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  subtrationOperator = value!;
                  print(subtrationOperator.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

                }
                calculatesubtrationResult();
                setState(() {

                });
              },
              child: const Text('Calculate'),
            ),
            const SizedBox(height: 20.0),
            Text(subtrationresult,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(); 


                          formData['support'] = supportList;














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
















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