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

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

class _basicp1CreateEntityScreenState extends State<basicp1CreateEntityScreen> {

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


  final TextEditingController name2Controller = TextEditingController();


  final TextEditingController number1Controller = TextEditingController();


  final TextEditingController number2Controller = TextEditingController();


  final TextEditingController phone_numberController = TextEditingController();


  final TextEditingController phone_number2Controller = TextEditingController();


  final TextEditingController paragraph_fieldController = TextEditingController();


  final TextEditingController paragraph_field2Controller = TextEditingController();



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

  final TextEditingController textareaController = TextEditingController();


  final TextEditingController textarea_fieldController = TextEditingController();


  final TextEditingController textarea_field2Controller = TextEditingController();


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
























} 

  

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























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

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

  SizedBox(height: 16),


ReusableTextField(
                  controller: number1Controller,

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

SizedBox(height: 16), 

ReusableTextField(
                  controller: number2Controller,

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

SizedBox(height: 16), 

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

ReusableTextField(
              onSaved:(value) => formData['phone_number2'] = value ,
              label: "Enter Phone Number2",
              keyboardType: TextInputType.number,
              inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(
                        10), // Limit input to 10 digits
            ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter Phone Number2';
                }
                if (value.length != 10) {
                      return 'Phone number must be exactly 10 digits';
                    }
                    return null;
              },
            ),

ReusableTextField(
                  controller: paragraph_fieldController,

              onSaved:(value) => formData['paragraph_field'] = value ,
              label: "Enter Paragraph Field",
              maxLines: 5,

            ),

ReusableTextField(
                  controller: paragraph_field2Controller,

              onSaved:(value) => formData['paragraph_field2'] = value ,
              label: "Enter Paragraph Field2",
              maxLines: 5,

            ),

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

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


                       SizedBox(height: 16),


ReusableTextField(
                  controller: textarea_fieldController,

  onSaved:(value) => formData['textarea_field'] = value ,
  label: "Enter Textarea Field",
  maxLines: 5,
// ValidationProperties
),


                       SizedBox(height: 16),


ReusableTextField(
                  controller: textarea_field2Controller,

  onSaved:(value) => formData['textarea_field2'] = value ,
  label: "Enter Textarea Field2",
  maxLines: 5,
// 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(); 
























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
























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