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


  basicp3UpdateEntityScreen({required this.entity});

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

class _basicp3UpdateEntityScreenState extends State<basicp3UpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();

  bool istoggle_switch = false;

  bool istoggle_switch2 = false;

bool _isUrlValidurl_field = true;

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

bool _isUrlValidurl_field2 = true;

void _validateUrlurl_field2(String url) {
  setState(() {
    _isUrlValidurl_field2= Uri.parse(url).isAbsolute;
  });
}
















  @override
  void initState() {
    super.initState();
    final provider = Provider.of<Basicp3ViewModelScreen>(context, listen: false);
istoggle_switch = widget.entity['toggle_switch'] ?? false; // Set initial value

istoggle_switch2 = widget.entity['toggle_switch2'] ?? false; // Set initial value



















}

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






















        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 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'),
  ],
),

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

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

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



   // ValidationProperties

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

SizedBox(height: 16),

ReusableTextField(
 initialValue: widget.entity['decimal_field'],
              onSaved: (value) => widget.entity['decimal_field'] = value,
              label: "Enter Decimal Field",
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*')),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a decimal number';
                }
                final decimalRegExp = RegExp(r'^\d*\.?\d*$');
                if (!decimalRegExp.hasMatch(value)) {
                  return 'Please enter a valid decimal number';
                }
                return null;
              },
            ),

ReusableTextField(
 initialValue: widget.entity['decimal_field2'],
              onSaved: (value) => widget.entity['decimal_field2'] = value,
              label: "Enter Decimal Field2",
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*')),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a decimal number';
                }
                final decimalRegExp = RegExp(r'^\d*\.?\d*$');
                if (!decimalRegExp.hasMatch(value)) {
                  return 'Please enter a valid decimal 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(
              initialValue: widget.entity['percentage_field2'].toString(),
              onSaved: (value) => widget.entity['percentage_field2']= value,
              label: "Enter Percentage Field2",
              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 documentsequenc",
                            initialValue: widget.entity['documentsequenc'] ?? '',

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



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

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



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

   // ValidationProperties
                            onSaved: (value) => widget.entity['recaptcha2'] = 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['toggle_switch'] = istoggle_switch;

widget.entity['toggle_switch2'] = istoggle_switch2;



















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