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


  test_aUpdateEntityScreen({required this.entity});

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

class _test_aUpdateEntityScreenState extends State<test_aUpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();





  bool isactive = false;






  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 _isemailEmailValid = true;

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


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




isactive = widget.entity['active'] ?? false; // Set initial value















}

 
  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<Test_aViewModelScreen>(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 Test_a"),        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['description'],
              onSaved: (value) => widget.entity['description']= value,
              label: "Enter Description",
              maxLines: 5,
            ),

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

 ReusableTextField(
              initialValue: widget.entity['number_field'].toString(),
              onSaved: (value) => widget.entity['number_field']= value,
              label: "Enter Number 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['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;
              },
            ),

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",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle
                                  .txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Email",
                              initialValue: widget.entity['email'],
                               keyboardType: TextInputType.url,
                              errorText: _isemailEmailValid ? null : 'Please enter a valid URL',
                                onChanged: _validateemailEmail,



   // ValidationProperties

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

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['active'] = isactive;















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