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


  testfUpdateEntityScreen({required this.entity});

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

class _testfUpdateEntityScreenState extends State<testfUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();










  bool _passwordVisiblepasswordss = false;
  bool _isPasswordValidpasswordss = true;
  bool _doPasswordsMatchpasswordss = true;

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

  void _validatePasswordpasswordss(String password) {
    setState(() {
      _isPasswordValidpasswordss = password.isNotEmpty;
      _passwordpasswordss = password; // Store the password for later comparison
      _doPasswordsMatchpasswordss = true; // Reset match flag on new input
    });
  }

  void _validateConfirmPasswordpasswordss(String confirmPassword) {
    setState(() {
      _doPasswordsMatchpasswordss = confirmPassword == _passwordpasswordss;
    });
  }



TextEditingController dates = TextEditingController(); 
DateTime selectedDatedates = DateTime.now();

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



bool _isemailsEmailValid = true;

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

  bool istoggless = false;

bool _isUrlValidurls = true;

void _validateUrlurls(String url) {
  setState(() {
    _isUrlValidurls= Uri.parse(url).isAbsolute;
  });
}










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


















istoggless = widget.entity['toggless'] ?? false; // Set initial value











}

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


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

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

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

                  obscureText: !_passwordVisiblepasswordss,
                  decoration: InputDecoration(
                    labelText: 'Passwordss',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepasswordss
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepasswordss = !_passwordVisiblepasswordss;
                        });
                      },
                    ),
                    errorText:
                        _isPasswordValidpasswordss ? null : 'Please enter a password',
                    border: OutlineInputBorder(),
                  ),
                  onSaved: (value) => widget.entity['passwordss'] = value,
                  onChanged: _validatePasswordpasswordss,
                ),
                const SizedBox(height: 16),
                TextFormField(
                  obscureText: !_passwordVisiblepasswordss,
                  decoration: InputDecoration(
                    labelText: 'Confirm Passwordss',
                    suffixIcon: IconButton(
                      icon: Icon(
                        _passwordVisiblepasswordss
                            ? Icons.visibility
                            : Icons.visibility_off,
                      ),
                      onPressed: () {
                        setState(() {
                          _passwordVisiblepasswordss = !_passwordVisiblepasswordss;
                        });
                      },
                    ),
                    errorText:
                        _doPasswordsMatchpasswordss ? null : 'Passwords do not match',
                    border: OutlineInputBorder(),
                  ),
                  onChanged: _validateConfirmPasswordpasswordss,
                ),





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

 ReusableDatePickerField(label: 'Dates', controller: dates, initialDate: widget.entity['dates'],
                                      onSaved: (value) => widget.entity['dates'] = value,),



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

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


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



   // ValidationProperties

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

SizedBox(height: 16),

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

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



   // ValidationProperties

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

SizedBox(height: 16),

 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(
                           
                            label: "Please Enter recaptchas",
                            initialValue: widget.entity['recaptchas'] ?? '',

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


 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 documentss",
                            initialValue: widget.entity['documentss'] ?? '',

   // ValidationProperties
                            onSaved: (value) => widget.entity['documentss'] = value,
),
                    
                          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['toggless'] = istoggless;











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