// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
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 'package:barcode_widget/barcode_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:intl/intl.dart';

import 'dart:math';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
import 'package:flutter/services.dart';
class testssUpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  testssUpdateEntityScreen({required this.entity});

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

class _testssUpdateEntityScreenState extends State<testssUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();




  var selectedselectstat; // Initialize with the default value \n);
  List<String> selectstatList = [

 
    'bar_code',

 

 
    'qr_code',

 

  ];

Widget _buildDropdownselectstat(String label, List<String> options, String? value, void Function(String?) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: DropdownButtonFormField<String>(
        decoration: InputDecoration(labelText: label,
          border: OutlineInputBorder(),
),
        value: value,
        onChanged: onChanged,
        items: options.map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    );
  }

  String? selectedradio_field;
 

  Future<void> _showradio_fieldSelectionDialog(BuildContext context) async {
    final result = await showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: const Text('Select radio_field'),
          children: [
            
 
            RadioListTile<String>(
              title: const Text('bar_code'),
              value: 'bar_code',
              groupValue: selectedradio_field,
              onChanged: (value) {
                setState(() {
                  selectedradio_field = value;
                  Navigator.pop(context, value);
                });
              },
            ),
        

 
            RadioListTile<String>(
              title: const Text('qr_code'),
              value: 'qr_code',
              groupValue: selectedradio_field,
              onChanged: (value) {
                setState(() {
                  selectedradio_field = value;
                  Navigator.pop(context, value);
                });
              },
            ),
        


          ],
        );
      },
    );

    if (result != null) {
      setState(() {
        selectedradio_field = result;
      });
    }
  }


 

  bool qcBox = false;
 

 

  bool bcBox = false;
 








final TextEditingController _inputcurrencyController = TextEditingController();
double editedcurrencyValue = 0.0;

late String inputDataqrcode_field;
  late TextEditingController controllerInputqrcode_field;


 late  String inputDatabarcode_field; // By default barcode
  TextEditingController controllerInputbarcode_field = TextEditingController();









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


  selectedselectstat = widget.entity['selectstat'] ?? selectstatList[0] ; // Initialize with the default value

selectedradio_field = widget.entity['radio_field'] ?? ''; // Initialize selected radio_field 



 
qcBox = widget.entity['q'] ?? false; 
 

 
bcBox = widget.entity['b'] ?? false; 
 








 // Convert the currency value to double if it's not already
    if (widget.entity['currency'] is String) {
      widget.entity['currency'] =
          double.tryParse(widget.entity['currency']) ?? 0.0;
    }

    // Initially set the controller text without formatting
    _inputcurrencyController.text = widget.entity['currency'].toString();
    editedcurrencyValue = widget.entity['currency'];

 inputDataqrcode_field = widget.entity['qrcode_field'] ?? "Hello";
    controllerInputqrcode_field = TextEditingController(text: inputDataqrcode_field);

  inputDatabarcode_field = widget.entity['barcode_field'] ?? "Hello";
    controllerInputbarcode_field.text = inputDatabarcode_field;








}

 
  @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: "Update Testss"),        actions: [


























        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 
                        ReusableTextField(
                           
                            label: "Please Enter Name",
                            initialValue: widget.entity['name'] ?? '',

   // ValidationProperties
                            onSaved: (value) => widget.entity['name'] = value,
),
                    
                          SizedBox(height: 16),




 _buildDropdownselectstat(
             'selectstat',
              selectstatList,
              selectedselectstat,
              (value) {
                setState(() {
                 selectedselectstat = value;
                  widget.entity['selectstat'] = value; // Save selected value to entity
                });
              },
            ),


Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "Radio Field",
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.left,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Colors.blueGrey[900],
              ),
            ),
            const SizedBox(height: 6),
            GestureDetector(
              onTap: () => _showradio_fieldSelectionDialog(context),
              child: AbsorbPointer(
                child: TextFormField(
                  decoration: InputDecoration(
                    hintText: "Enter Radio Field",
                    border: OutlineInputBorder(),
                    contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                  ),
                  controller: TextEditingController(text: selectedradio_field),
                  onSaved: (value) {
                    widget.entity['radio_field'] = value;
                  },
                ),
              ),
            ),
            const SizedBox(height: 16),
          
          ],
        ),
      ),

                Row(
                  children: [


 
                    Checkbox(
                      value: qcBox,
                      onChanged: (newValue) {
                        setState(() {
                          qcBox = newValue!;
                        });
                      },
                    ),
                    const SizedBox(width: 8),
                    Text('Q'),

 

 
                    Checkbox(
                      value: bcBox,
                      onChanged: (newValue) {
                        setState(() {
                          bcBox = newValue!;
                        });
                      },
                    ),
                    const SizedBox(width: 8),
                    Text('B'),

 

                  ],
                ),
                SizedBox(height: 16),






                        ReusableTextField(
                           
                            label: "Please Enter audio Field",
                            initialValue: widget.entity['audio_field'] ?? '',

   // ValidationProperties
                            onSaved: (value) => widget.entity['audio_field'] = value,
),
                    
                          SizedBox(height: 16),


Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    TextFormField(
      controller: _inputcurrencyController,
      keyboardType: TextInputType.number,
      decoration: const InputDecoration(
        labelText: 'Edit Currency Value',
        prefixIcon: Icon(Icons.money),
                      border: OutlineInputBorder(),

      ),
      onChanged: (text) {
        setState(() {
          try {
            String currencyString = text;
            currencyString = currencyString.replaceAll(',', ''); // Remove commas
            currencyString = currencyString.replaceAll('₹', ''); // Remove currency symbol
            editedcurrencyValue = double.parse(currencyString);
            print("Parsed double value: $editedcurrencyValue");
          } catch (e) {
            print("Invalid input: $text");
            editedcurrencyValue = 0.0; // Set to a default value or handle the error accordingly
          }
        });
      },
      onSaved: (value) {
        widget.entity['currency'] = editedcurrencyValue;
      },
    ),
    SizedBox(height: 16),
    Text(
      'Edited Currency Value: ${editedcurrencyValue.toStringAsFixed(2)}', // Display formatted currency value
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
      ),
    ),
    SizedBox(height: 16),
    // Add other form fields here
  ],
),


Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Generate QR Code',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            QrImageView(
              data: inputDataqrcode_field,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode_field,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode_field = value;
 widget.entity['qrcode_field'] = inputDataqrcode_field;
                });
              },
            ),
          ],
        ),

    Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Text(
                      'Generate Barcode',
                      style: TextStyle(fontSize: 18),
                    ),
                    const SizedBox(height: 16),
                    if (inputDatabarcode_field.isNotEmpty)
                      BarcodeWidget(
                        barcode: Barcode.code128(), // Choose the type of barcode
                        data: inputDatabarcode_field,
                        width: 200,
                        height: 80,
                      ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: controllerInputbarcode_field,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Enter data for barcode',
                      ),
                      onChanged: (value) {
                        setState(() {
                          inputDatabarcode_field = value;
                          widget.entity['barcode_field'] = inputDatabarcode_field;
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    // ElevatedButton(
                    //   onPressed: () {
                    //     setState(() {
                    //       inputData = controllerInput.text;
                    //     });
                    //   },
                    //   child: const Text('Generate Barcode'),
                    // ),
                  ],
                ),
  const SizedBox(height: 16),

 ReusableTextField(
              initialValue: widget.entity['numa'].toString(),
              onSaved: (value) => widget.entity['numa']= value,
              label: "Enter Numa",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),

 ReusableTextField(
              initialValue: widget.entity['numb'].toString(),
              onSaved: (value) => widget.entity['numb']= value,
              label: "Enter Numb",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),



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








     

                  widget.entity['q'] = qcBox;
 

     

                  widget.entity['b'] = bcBox;
 




















       
                        try {
                        await provider.updateEntity(
                              widget.entity[
                                  'id'], // Assuming 'id' is the key in your entity map
                              widget.entity);   



























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