// 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 '../Forma_viewModel/Forma_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 formaCreateEntityScreen extends StatefulWidget {
  const formaCreateEntityScreen({super.key});

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

class _formaCreateEntityScreenState extends State<formaCreateEntityScreen> {

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


  final TextEditingController fieldggController = TextEditingController();


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

                    
 

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

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

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

  final TextEditingController numberdController = TextEditingController();


  final TextEditingController numbercController = TextEditingController();



  
  String calculateaddOperator = '+';
  String calculateaddresult = '';

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

  void calculatecalculateaddResult() {
    int calculation;
    switch (calculateaddOperator) {
      case '+':
        calculation = 

 
int.parse(numberdController.text) +

  

 
int.parse(numbercController.text) +

  

0;


        break;
      case '-':
        calculation =

 
int.parse(numberdController.text) -
  

 
int.parse(numbercController.text) -
  

0;
        break;
      case '*':
        calculation =

 
int.parse(numberdController.text) *
  

 
int.parse(numbercController.text) *
  

1;
        break;
      case '/':
        if (

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

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



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

 
int.parse(numberdController.text) /
  

 
int.parse(numbercController.text) /
  


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

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




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


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








} 

  

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



 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: 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(
        "Fieldgg",
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 16),

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

  SizedBox(height: 16),
 

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

  SizedBox(height: 16),
 

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






ReusableTextField(
                  controller: numberdController,

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

SizedBox(height: 16), 

ReusableTextField(
                  controller: numbercController,

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

SizedBox(height: 16), 

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

                }
                calculatecalculateaddResult();
                setState(() {

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








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