// 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 '../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 '../../../../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 testfCreateEntityScreen extends StatefulWidget {
  const testfCreateEntityScreen({super.key});

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

class _testfCreateEntityScreenState extends State<testfCreateEntityScreen> {

final Map<String, dynamic> formData = {};
  final _formKey = GlobalKey<FormState>();
  final TextEditingController nameController = TextEditingController();


  final TextEditingController numbersController = TextEditingController();


  final TextEditingController phonesController = TextEditingController();


  final TextEditingController paragraphsController = TextEditingController();



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

  final TextEditingController textareasController = TextEditingController();


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),
    );
    if (picked != null && picked != selectedDatedates) {
      setState(() {
        selectedDatedates = picked;
      });
    }
  }


  final TextEditingController datetimesController = TextEditingController();


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


bool _isSwitchedtoggless = false;
bool toggless = false;

void _toggleSwitchtoggless(bool value) {
  setState(() {
    _isSwitchedtoggless = value;
  });
}

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


  final TextEditingController decimalsController = TextEditingController();


late String recaptchascaptcha;
  TextEditingController _recaptchasController = TextEditingController();
  final GlobalKey<ScaffoldMessengerState> _recaptchasscaffoldKey = GlobalKey<ScaffoldMessengerState>();
void generaterecaptchasCaptcha() {
    final random = Random();
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    recaptchascaptcha = String.fromCharCodes(Iterable.generate(
        6, (_) => chars.codeUnitAt(random.nextInt(chars.length))));
  }

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

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


  final TextEditingController percentagesController = TextEditingController();




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
























   generaterecaptchasCaptcha();





} 

  

  @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: "Create Testf"),





























),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 ReusableTextField(
                  controller: nameController,

  onSaved:(value) => formData['name'] = value ,
  label:"Enter Name",
  // ValidationProperties
),

  SizedBox(height: 16),


ReusableTextField(
                  controller: numbersController,

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

SizedBox(height: 16), 

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

              onSaved:(value) => formData['paragraphs'] = value ,
              label: "Enter Paragraphs",
              maxLines: 5,

            ),

TextFormField(
                  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) => formData['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(
                  controller: textareasController,

  onSaved:(value) => formData['textareas'] = value ,
  label: "Enter Textareas",
  maxLines: 5,
// ValidationProperties
),


                       SizedBox(height: 16),


ReusableDatePickerField(
                label:' Dates', controller: dates 
,
                                      onSaved: (value) => formData['dates'] = value,),
const SizedBox(height: 16),


ReusableTextField(
                  controller: datetimesController,

  onSaved:(value) => formData['datetimes'] = value ,
  label:"Enter Datetimes",
  // ValidationProperties
),

  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",
    errorText: _isemailsEmailValid ? null : 'Please enter a valid email',

onsaved: (value) => formData['emails'] = value,
  onChanged: (value) {
    _validateemailsEmail(value);
  },                            
  margin: getMargin(top: 6))
                        ])),

 Switch(
              value: _isSwitchedtoggless,
              onChanged: _toggleSwitchtoggless,
              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("Urls",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle.txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Urls",
    errorText: _isUrlValidurls ? null : 'Please enter a valid URL',
  keyboardType: TextInputType.url,


                              onsaved: (value) => formData['urls'] = value,
  onChanged: _validateUrlurls,

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

ReusableTextField(
                  controller: decimalsController,

              onSaved:(value) => formData['decimals'] = value ,
              label: "Enter Decimals",
              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(
                    recaptchascaptcha,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                      letterSpacing: 4,
                      fontFamily: 'Roboto',
                      decoration: TextDecoration.none,
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.refresh),
                    onPressed: () {
                      setState(() {
                        generaterecaptchasCaptcha();
                      });
                    },
                  ),
                ],
              ),
            ),
            SizedBox(height: 24),
            TextFormField(
              controller: _recaptchasController,
              decoration: InputDecoration(
                labelText: 'Enter CAPTCHA',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: verifyrecaptchasCaptcha,
              child: Text('Verify CAPTCHA'),
            ),
          ],
        ),
      ),

ReusableTextField(
                  controller: percentagesController,

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

SizedBox(height: 16), 



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












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






























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