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

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

class _basicp2CreateEntityScreenState extends State<basicp2CreateEntityScreen> {

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


  final TextEditingController textarea2Controller = TextEditingController();


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


TextEditingController date_field2 = TextEditingController(); 

 DateTime selectedDatedate_field2 = DateTime.now();
  Future<void> _selectDatedate_field2(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDatedate_field2,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != selectedDatedate_field2) {
      setState(() {
        selectedDatedate_field2 = picked;
      });
    }
  }


TextEditingController datetime_field = TextEditingController();

DateTime selectedDateTimedatetime_field = DateTime.now();
  Future<void> _selectDateTimedatetime_field(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDateTimedatetime_field,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    if (picked != null) {
      final TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(selectedDateTimedatetime_field),
      );
      print(pickedTime);
      if (pickedTime != null) {
        setState(() {
          selectedDateTimedatetime_field = DateTime(
            picked.year,
            picked.month,
            picked.day,
            pickedTime.hour,
            pickedTime.minute,
          );
        });
      }
    }
  }


TextEditingController datetime_field2 = TextEditingController();

DateTime selectedDateTimedatetime_field2 = DateTime.now();
  Future<void> _selectDateTimedatetime_field2(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDateTimedatetime_field2,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );

    if (picked != null) {
      final TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(selectedDateTimedatetime_field2),
      );
      print(pickedTime);
      if (pickedTime != null) {
        setState(() {
          selectedDateTimedatetime_field2 = DateTime(
            picked.year,
            picked.month,
            picked.day,
            pickedTime.hour,
            pickedTime.minute,
          );
        });
      }
    }
  }


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


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




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


















} 

  

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

















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

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


                       SizedBox(height: 16),


ReusableTextField(
                  controller: textarea2Controller,

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


                       SizedBox(height: 16),


ReusableDatePickerField(
                label:' Date Field', controller: date_field 
,
                                      onSaved: (value) => formData['date_field'] = value,),
const SizedBox(height: 16),


ReusableDatePickerField(
                label:' Date Field2', controller: date_field2 
,
                                      onSaved: (value) => formData['date_field2'] = value,),
const SizedBox(height: 16),


ReusableDateTimePickerField(label: 'Datetime Field', controller: datetime_field,
                                      onSaved: (value) => formData['datetime_field'] = value,

),
const SizedBox(height: 16),


ReusableDateTimePickerField(label: 'Datetime Field2', controller: datetime_field2,
                                      onSaved: (value) => formData['datetime_field2'] = value,

),
const SizedBox(height: 16),



Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Email Field",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle.txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Email Field",
    errorText: _isemail_fieldEmailValid ? null : 'Please enter a valid email',

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


Padding(
                    padding: getPadding(top: 19),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text("Email Field2",
                              overflow: TextOverflow.ellipsis,
                              textAlign: TextAlign.left,
                              style: AppStyle.txtGilroyMedium16Bluegray900),
                          CustomTextFormField(
                              hintText: "Enter Email Field2",
    errorText: _isemail_field2EmailValid ? null : 'Please enter a valid email',

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



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


















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