// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Testk_viewModel/Testk_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 testkUpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  testkUpdateEntityScreen({required this.entity});

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

class _testkUpdateEntityScreenState extends State<testkUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();









  String? selectedradios;
 

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

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


          ],
        );
      },
    );

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


 

  bool scBox = false;
 

 

  bool rcBox = false;
 

 

  bool fcBox = false;
 










final TextEditingController _inputcurrencyxController = TextEditingController();
double editedcurrencyxValue = 0.0;

late String inputDataqrcode;
  late TextEditingController controllerInputqrcode;


 late  String inputDatabarcodes; // By default barcode
  TextEditingController controllerInputbarcodes = TextEditingController();



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








selectedradios = widget.entity['radios'] ?? ''; // Initialize selected radios 



 
scBox = widget.entity['s'] ?? false; 
 

 
rcBox = widget.entity['r'] ?? false; 
 

 
fcBox = widget.entity['f'] ?? 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
    _inputcurrencyxController.text = widget.entity['currency'].toString();
    editedcurrencyxValue = widget.entity['currency'];

 inputDataqrcode = widget.entity['qrcode'] ?? "Hello";
    controllerInputqrcode = TextEditingController(text: inputDataqrcode);

  inputDatabarcodes = widget.entity['barcodes'] ?? "Hello";
    controllerInputbarcodes.text = inputDatabarcodes;


}

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


























        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
  ReusableTextField(
              initialValue: widget.entity['decimals'].toString(),
              onSaved: (value) => widget.entity['decimals']= value,
              label: "Enter Decimals",
              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['percentages'].toString(),
              onSaved: (value) => widget.entity['percentages']= value,
              label: "Enter Percentages",
              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(
                           
                            label: "Please Enter recaptchas",
                            initialValue: widget.entity['recaptchas'] ?? '',

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



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

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


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

                Row(
                  children: [


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

 

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

 

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

 

                  ],
                ),
                SizedBox(height: 16),






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

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



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

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


Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    TextFormField(
      controller: _inputcurrencyxController,
      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
            editedcurrencyxValue = double.parse(currencyString);
            print("Parsed double value: $editedcurrencyxValue");
          } catch (e) {
            print("Invalid input: $text");
            editedcurrencyxValue = 0.0; // Set to a default value or handle the error accordingly
          }
        });
      },
      onSaved: (value) {
        widget.entity['currencyx'] = editedcurrencyxValue;
      },
    ),
    SizedBox(height: 16),
    Text(
      'Edited Currency Value: ${editedcurrencyxValue.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,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode = value;
 widget.entity['qrcode'] = inputDataqrcode;
                });
              },
            ),
          ],
        ),

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

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












     

                  widget.entity['s'] = scBox;
 

     

                  widget.entity['r'] = rcBox;
 

     

                  widget.entity['f'] = fcBox;
 
















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