// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
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 '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart'; 
import '../../../../widgets/custom_dropdown_field.dart';
import 'dart:math';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:barcode_widget/barcode_widget.dart';
import 'package:intl/intl.dart';
 
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart'
;import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:just_audio/just_audio.dart';
import 'package:video_player/video_player.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:lottie/lottie.dart';
import '../../../../utils/toast_messages/toast_message_util.dart';
import 'dart:io';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';






















class basicp3CreateEntityScreen extends StatefulWidget {
  const basicp3CreateEntityScreen({super.key});

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

class _basicp3CreateEntityScreenState extends State<basicp3CreateEntityScreen> {

final Map<String, dynamic> formData = {};
  final _formKey = GlobalKey<FormState>();
bool _isSwitchedtoggle_switch = false;
bool toggle_switch = false;

void _toggleSwitchtoggle_switch(bool value) {
  setState(() {
    _isSwitchedtoggle_switch = value;
  });
}

bool _isSwitchedtoggle_switch2 = false;
bool toggle_switch2 = false;

void _toggleSwitchtoggle_switch2(bool value) {
  setState(() {
    _isSwitchedtoggle_switch2 = value;
  });
}

  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;
    });
  }


  final TextEditingController decimal_fieldController = TextEditingController();


  final TextEditingController decimal_field2Controller = TextEditingController();


  final TextEditingController percentage_fieldController = TextEditingController();


  final TextEditingController percentage_field2Controller = TextEditingController();




late String recaptchacaptcha;
  TextEditingController _recaptchaController = TextEditingController();
  final GlobalKey<ScaffoldMessengerState> _recaptchascaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptchaCaptcha() {
    final random = Random();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    recaptchacaptcha = String.fromCharCodes(Iterable.generate(
        6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

  void verifyrecaptchaCaptcha() {
    print("Verifying captcha");
    if (_recaptchaController.text.isEmpty) {
      print("recaptcha is empty");
      recaptchaSnackbar('Please enter CAPTCHA', success: false);
    } else if (_recaptchaController.text != recaptchacaptcha) {
      print("captcha is not matching");
      recaptchaSnackbar('CAPTCHA verification failed', success: false);
    } else {
      print("captcha is verified");
      recaptchaSnackbar('CAPTCHA Verified', success: true);
      // Navigate to another screen after verification
      // Example navigation to a new screen
     // Navigator.push(
       // context,
       // MaterialPageRoute(builder: (context) => NextScreen()),
    //  );
    }
  }

  void recaptchaSnackbar(String message, {required bool success}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: success ? Colors.green : Colors.red,
      ),
    );
  }


late String recaptcha2captcha;
  TextEditingController _recaptcha2Controller = TextEditingController();
  final GlobalKey<ScaffoldMessengerState> _recaptcha2scaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptcha2Captcha() {
    final random = Random();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    recaptcha2captcha = String.fromCharCodes(Iterable.generate(
        6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

  void verifyrecaptcha2Captcha() {
    print("Verifying captcha");
    if (_recaptcha2Controller.text.isEmpty) {
      print("recaptcha2 is empty");
      recaptcha2Snackbar('Please enter CAPTCHA', success: false);
    } else if (_recaptcha2Controller.text != recaptcha2captcha) {
      print("captcha is not matching");
      recaptcha2Snackbar('CAPTCHA verification failed', success: false);
    } else {
      print("captcha is verified");
      recaptcha2Snackbar('CAPTCHA Verified', success: true);
      // Navigate to another screen after verification
      // Example navigation to a new screen
     // Navigator.push(
       // context,
       // MaterialPageRoute(builder: (context) => NextScreen()),
    //  );
    }
  }

  void recaptcha2Snackbar(String message, {required bool success}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: success ? Colors.green : Colors.red,
      ),
    );
  }


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


















   generaterecaptchaCaptcha();

   generaterecaptcha2Captcha();

} 

  

  @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: "Create Basicp3"),
 actions: [






















],
 ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
  Switch(
              value: _isSwitchedtoggle_switch,
              onChanged: _toggleSwitchtoggle_switch,
              activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.red,
            ),

 Switch(
              value: _isSwitchedtoggle_switch2,
              onChanged: _toggleSwitchtoggle_switch2,
              activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.red,
            ),


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",
    errorText: _isUrlValidurl_field ? null : 'Please enter a valid URL',
  keyboardType: TextInputType.url,


                              onsaved: (value) => formData['url_field'] = value,
  onChanged: _validateUrlurl_field,

                              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",
    errorText: _isUrlValidurl_field2 ? null : 'Please enter a valid URL',
  keyboardType: TextInputType.url,


                              onsaved: (value) => formData['url_field2'] = value,
  onChanged: _validateUrlurl_field2,

                              margin: getMargin(top: 6))
                        ])),
SizedBox(height: 16),

 ReusableTextField(
              onSaved:(value) => formData['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;
              },
            ),

                         const SizedBox(height: 16),



 ReusableTextField(
              onSaved:(value) => formData['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;
              },
            ),

                         const SizedBox(height: 16),



ReusableTextField(
                  controller: percentage_fieldController,

              onSaved:(value) => formData['percentage_field'] = value ,
              label: "Enter Percentage Field",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 

ReusableTextField(
                  controller: percentage_field2Controller,

              onSaved:(value) => formData['percentage_field2'] = value ,
              label: "Enter Percentage Field2",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
             // ValidationProperties     
),

SizedBox(height: 16), 



Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Enter the following CAPTCHA:',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    recaptchacaptcha,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                      letterSpacing: 4,
                      fontFamily: 'Roboto',
                      decoration: TextDecoration.none,
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.refresh),
                    onPressed: () {
                      setState(() {
                        generaterecaptchaCaptcha();
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 24),
            TextFormField(
              controller: _recaptchaController,
              decoration: InputDecoration(
                labelText: 'Enter CAPTCHA',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: verifyrecaptchaCaptcha,
              child: Text('Verify CAPTCHA'),
            ),
          ],
        ),
      ),

Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              'Enter the following CAPTCHA:',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Container(
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    spreadRadius: 2,
                    blurRadius: 5,
                    offset: Offset(0, 3),
                  ),
                ],
              ),
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    recaptcha2captcha,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                      letterSpacing: 4,
                      fontFamily: 'Roboto',
                      decoration: TextDecoration.none,
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.refresh),
                    onPressed: () {
                      setState(() {
                        generaterecaptcha2Captcha();
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 24),
            TextFormField(
              controller: _recaptcha2Controller,
              decoration: InputDecoration(
                labelText: 'Enter CAPTCHA',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: verifyrecaptcha2Captcha,
              child: Text('Verify CAPTCHA'),
            ),
          ],
        ),
      ),

   const SizedBox(width: 8),
                CustomButton(
                  height: getVerticalSize(50),
                  text: "Submit",
                  margin: getMargin(top: 24, bottom: 5),
                  onTap: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save(); 
formData['toggle_switch'] = toggle_switch;


formData['toggle_switch2'] = toggle_switch2;




















 
                      try {
                        print(formData);
  Map<String, dynamic> createdEntity =  await provider.createEntity(formData); 






















 

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






















   ],
          ),
              ),
            ),
          ),
     );
  }
}