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


  emp_detailsUpdateEntityScreen({required this.entity});

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

class _emp_detailsUpdateEntityScreenState extends State<emp_detailsUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();










  bool _passwordVisiblepassword_field = false;
  bool _isPasswordValidpassword_field = true;
  bool _doPasswordsMatchpassword_field = true;

  String _passwordpassword_field = ''; // To store the first password

  void _validatePasswordpassword_field(String password) {
    setState(() {
      _isPasswordValidpassword_field = password.isNotEmpty;
      _passwordpassword_field = password; // Store the password for later comparison
      _doPasswordsMatchpassword_field = true; // Reset match flag on new input
    });
  }

  void _validateConfirmPasswordpassword_field(String confirmPassword) {
    setState(() {
      _doPasswordsMatchpassword_field = confirmPassword == _passwordpassword_field;
    });
  }



TextEditingController date_field = TextEditingController(); 
DateTime selectedDatedate_field = DateTime.now();

Future<void> _selectDatedate_field(BuildContext context) async {
  final DateTime? picked = await showDatePicker(
    context: context,
    initialDate: selectedDatedate_field,
    firstDate: DateTime(2000),
    lastDate: DateTime(2101),
  );
  print(picked);
  if (picked != null && picked != selectedDatedate_field) {
    setState(() {
      selectedDatedate_field = picked;
    });
  }
}



bool _isemail_fieldEmailValid = true;

void _validateemail_fieldEmail(String email) {
  setState(() {
    _isemail_fieldEmailValid = RegExp(r'^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$').hasMatch(email);
  });
}

  bool istoggle_switch = false;

bool _isUrlValidurl_field = true;

void _validateUrlurl_field(String url) {
  setState(() {
    _isUrlValidurl_field= Uri.parse(url).isAbsolute;
  });
}










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

 
    'bar_code',

 

 
    'qr_code',

 

  ];

Widget _buildDropdownselectsta(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? 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('bar_code'),
              value: 'bar_code',
              groupValue: selectedradios,
              onChanged: (value) {
                setState(() {
                  selectedradios = value;
                  Navigator.pop(context, value);
                });
              },
            ),
        

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


          ],
        );
      },
    );

    if (result != null) {
      setState(() {
        selectedradios = 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<Emp_detailsViewModelScreen>(context, listen: false);


















istoggle_switch = widget.entity['toggle_switch'] ?? false; // Set initial value











  selectedselectsta = widget.entity['selectsta'] ?? selectstaList[0] ; // Initialize with the default value

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



 
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<Emp_detailsViewModelScreen>(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 Emp_details"),        actions: [
























































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

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


 ReusableTextField(
              initialValue: widget.entity['numbera'].toString(),
              onSaved: (value) => widget.entity['numbera']= value,
              label: "Enter Numbera",
              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['phone_number'],
              onSaved: (value) => widget.entity['phone_number'] = value,
              label: "Enter Phone Number",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
 LengthLimitingTextInputFormatter(
                        10), // Limit input to 10 digits
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter  Phone Number';
                }
                if (value.length != 10) {
                      return 'Phone number must be exactly 10 digits';
                    }
                    return null;
              },
            ),

 // }),
            ReusableTextField(
              initialValue: widget.entity['paragraph_field'],
              onSaved: (value) =>  widget.entity['paragraph_field']= value,
              label: "Enter Paragraph Field",
              maxLines: 5,
            ),

TextFormField(
              initialValue: widget.entity['password_field'],

                  obscureText: !_passwordVisiblepassword_field,
                  decoration: InputDecoration(
                    labelText: 'Password Field',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepassword_field
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepassword_field = !_passwordVisiblepassword_field;
                        });
                      },
                    ),
                    errorText:
                        _isPasswordValidpassword_field ? null : 'Please enter a password',
                    border: OutlineInputBorder(),
                  ),
                  onSaved: (value) => widget.entity['password_field'] = value,
                  onChanged: _validatePasswordpassword_field,
                ),
                const SizedBox(height: 16),
                TextFormField(
                  obscureText: !_passwordVisiblepassword_field,
                  decoration: InputDecoration(
                    labelText: 'Confirm Password Field',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepassword_field
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepassword_field = !_passwordVisiblepassword_field;
                        });
                      },
                    ),
                    errorText:
                        _doPasswordsMatchpassword_field ? null : 'Passwords do not match',
                    border: OutlineInputBorder(),
                  ),
                  onChanged: _validateConfirmPasswordpassword_field,
                ),





            ReusableTextField(
              initialValue: widget.entity['textarea_field'],
              onSaved: (value) => widget.entity['textarea_field']= value,
              label: "Enter Textarea Field",
              maxLines: 5,
            ),

 ReusableDatePickerField(label: 'Date Field', controller: date_field, initialDate: widget.entity['date_field'],
                                      onSaved: (value) => widget.entity['date_field'] = value,),



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

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


  Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Email Field",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle
                                  .txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Email Field",
                              initialValue: widget.entity['email_field'],
                               keyboardType: TextInputType.url,
                              errorText: _isemail_fieldEmailValid ? null : 'Please enter a valid URL',
                                onChanged: _validateemail_fieldEmail,



   // ValidationProperties

                              onsaved: (value) {
                                widget.entity['email_field'] = value;
                              },
                              margin: getMargin(top: 6))
                        ])),

SizedBox(height: 16),

Row(
  children: [
    Switch(
      value: istoggle_switch,
      onChanged: (newValue) {
        setState(() {
          istoggle_switch = newValue;
        });
      },
  activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.red,
    ),
    const SizedBox(width: 8),
    const Text('toggle switch'),
  ],
),

  Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Url Field",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle
                                  .txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Url Field",
                              initialValue: widget.entity['url_field'],
                               keyboardType: TextInputType.url,
                              errorText: _isUrlValidurl_field ? null : 'Please enter a valid URL',
                                onChanged: _validateUrlurl_field,



   // ValidationProperties

                              onsaved: (value) {
                                widget.entity['url_field'] = value;
                              },
                              margin: getMargin(top: 6))
                        ])),

SizedBox(height: 16),

 ReusableTextField(
              initialValue: widget.entity['decimal_field'].toString(),
              onSaved: (value) => widget.entity['decimal_field']= value,
              label: "Enter Decimal Field",
              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['percentage_field'].toString(),
              onSaved: (value) => widget.entity['percentage_field']= value,
              label: "Enter Percentage Field",
              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 recaptcha",
                            initialValue: widget.entity['recaptcha'] ?? '',

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



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

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




 _buildDropdownselectsta(
             'selectsta',
              selectstaList,
              selectedselectsta,
              (value) {
                setState(() {
                 selectedselectsta = value;
                  widget.entity['selectsta'] = value; // Save selected value to entity
                });
              },
            ),


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: 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),



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

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



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

   // ValidationProperties
                            onSaved: (value) => widget.entity['survey_form'] = 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['numberb'].toString(),
              onSaved: (value) => widget.entity['numberb']= value,
              label: "Enter Numberb",
              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['toggle_switch'] = istoggle_switch;

















     

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