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

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

class _regformCreateEntityScreenState extends State<regformCreateEntityScreen> {

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


  final TextEditingController roll_numberController = 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;
      });
    }
  }


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



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

  List<Map<String, dynamic>> selectedfileupload_field = [];

  Future<void> _pickfileupload_field(Map<String, dynamic> newFile, StateSetter setState) async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      setState(() {
        newFile['fileBytes'] = result.files.first.bytes;
        newFile['fileFileName'] = result.files.first.name;
      });
     ToastMessageUtil.showToast(
            message: "File Uploaded",
            toastType: ToastType.success);
    } else {
      print("No files selected");
    }
  }

  Widget _fileupload_fieldbuildUploadRow(Map<String, dynamic> newFile) {
    return StatefulBuilder(builder: (context, setState) {
      String? selectedFileName = newFile['fileFileName'];
      return Card(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        child: ListTile(
          leading: Icon(Icons.file_copy, color: Colors.blueAccent),
          title: Text(selectedFileName ?? 'No file selected', style: TextStyle(color: Colors.grey[700])),
          trailing: ElevatedButton(
            onPressed: () => _pickfileupload_field(newFile, setState),
            child: const Text('Select File'),
          ),
        ),
      );
    });
  }

  void _addfileupload_fieldUploadRow() {
    Map<String, dynamic> newFile = {};
    setState(() {
      selectedfileupload_field.add(newFile);
    });
  }

  void _removefileupload_fieldUploadRow(int index) {
    setState(() {
      selectedfileupload_field.removeAt(index);
    });
  }

  Future<void> _uploadfileupload_field(int entityId) async {
  // Check if selectedfileupload_field is null or empty
  if (selectedfileupload_field == null || selectedfileupload_field.isEmpty) {
    print("No files selected for upload.");
    return;
  }

  final provider = Provider.of<RegformViewModelScreen>(context, listen: false);

  for (var selectedfile in selectedfileupload_field) {
    // Ensure selectedfile is not null and has valid data
    if (selectedfile == null ||
        selectedfile['fileFileName'] == null ||
        selectedfile['fileBytes'] == null) {
      print("Skipping a file due to missing data: $selectedfile");
      continue; // Skip this iteration
    }

    try {
      await provider.uploadfileupload_field(
        entityId.toString(),
        'Regform',
        selectedfile['fileFileName'],
        selectedfile['fileBytes'],
      );
      print("File uploaded successfully: ${selectedfile['fileFileName']}");
    } catch (e) {
      print("Failed to upload file: ${selectedfile['fileFileName']} - Error: $e");
    }
  }
}


  List<Map<String, dynamic>> selectedimageupload_field = [];

  Future<void> _showimageupload_fieldImage(Map<String, dynamic> newImage, StateSetter setState) async {
    final ImagePicker picker = ImagePicker();

    // Show a dialog to choose the source
    final ImageSource? source = await showDialog<ImageSource>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('Select Image Source'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.of(context).pop(ImageSource.camera),
            child: const Text('Camera'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(ImageSource.gallery),
            child: const Text('Gallery'),
          ),
        ],
      ),
    );

    if (source != null) {
      final XFile? pickedImage = await picker.pickImage(source: source);

      if (pickedImage != null) {
        Uint8List imageBytes = await pickedImage.readAsBytes();
        setState(() {
          newImage['imageBytes'] = imageBytes;
          newImage['imageFileName'] = pickedImage.name;
        });
      ToastMessageUtil.showToast(
            message: "File Uploaded",
            toastType: ToastType.success);
      } else {
        print("No image selected");
      }
    }
  }

  Widget _buildUploadRowimageupload_field(Map<String, dynamic> newImage) {
    return StatefulBuilder(builder: (context, setState) {
      String? selectedFileName = newImage['imageFileName'];
      Uint8List? imageBytes = newImage['imageBytes'];
      return Card(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        child: ListTile(
          leading: imageBytes != null
              ? Image.memory(imageBytes, width: 50, height: 50, fit: BoxFit.cover)
              : Icon(Icons.image, color: Colors.blueAccent),
          title: Text(selectedFileName ?? 'No image selected', style: TextStyle(color: Colors.grey[700])),
          trailing: ElevatedButton(
            onPressed: () => _showimageupload_fieldImage(newImage, setState),
            child: const Text('Select Image'),
          ),
        ),
      );
    });
  }

  void _addUploadRowimageupload_field() {
    Map<String, dynamic> newImage = {};
    setState(() {
      selectedimageupload_field.add(newImage);
    });
  }

  void _removeUploadRowimageupload_field(int index) {
    setState(() {
      selectedimageupload_field.removeAt(index);
    });
  }

  Future<void> _uploadimageupload_field(int entityId) async {

 // Check if the selectedimageupload_field list is null or empty
    if (selectedimageupload_field == null ||
        selectedimageupload_field.isEmpty) {
      print("No images selected for upload.");
      return;
    }
final provider =
          Provider.of<RegformViewModelScreen>(context, listen: false);
    for (var selectedImage in selectedimageupload_field) {
 if (selectedImage == null ||
          selectedImage['imageFileName'] == null ||
          selectedImage['imageBytes'] == null) {
        print("Skipping an image due to missing data: $selectedImage");
        continue; // Skip this iteration
      }

      try {
     
      await provider.uploadimageupload_field(
                               entityId.toString(),
        'Regform',
        selectedImage['imageFileName'],
        selectedImage['imageBytes'],
      );
        print("Image uploaded successfully: ${selectedImage['imageFileName']}");
      } catch (e) {
        print(
            "Failed to upload image: ${selectedImage['imageFileName']} - Error: $e");
      }
    }
  }

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














} 

  

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














],
 ),
      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: roll_numberController,

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

SizedBox(height: 16), 

ReusableDatePickerField(
                label:' Date Field', controller: date_field 
,
                                      onSaved: (value) => formData['date_field'] = 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))
                        ])),

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

 SizedBox(
                  height:  MediaQuery.of(context).size.height*0.5,
child: Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: selectedfileupload_field.length,
              itemBuilder: (context, index) {
                return Stack(
                  children: [
                    _fileupload_fieldbuildUploadRow(selectedfileupload_field[index]),
                    Positioned(
                      right: 8,
                      top: 8,
                      child: IconButton(
                        icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                        onPressed: () {
                          _removefileupload_fieldUploadRow(index);
                        },
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            icon: const Icon(Icons.add),
            label: const Text('Add File Upload Row'),
            onPressed: _addfileupload_fieldUploadRow,
            style: ElevatedButton.styleFrom(
              foregroundColor: Colors.white, backgroundColor: Colors.blueAccent,
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              textStyle: const TextStyle(fontSize: 16),
            ),
          ),
          const SizedBox(height: 16),
        
        ],
      ),
    ),),
 const SizedBox(height: 16),

 SizedBox(
                  height:  MediaQuery.of(context).size.height*0.5,
child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Expanded(
              child: ListView.builder(
                itemCount: selectedimageupload_field.length,
                itemBuilder: (context, index) {
                  return Stack(
                    children: [
                      _buildUploadRowimageupload_field(selectedimageupload_field[index]),
                      Positioned(
                        right: 8,
                        top: 8,
                        child: IconButton(
                          icon: const Icon(Icons.remove_circle, color: Colors.redAccent),
                          onPressed: () {
                            _removeUploadRowimageupload_field(index);
                          },
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('Add Image Upload Row'),
              onPressed: _addUploadRowimageupload_field,
              style: ElevatedButton.styleFrom(
                foregroundColor: Colors.white,
                backgroundColor: Colors.blueAccent,
                padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                textStyle: const TextStyle(fontSize: 16),
              ),
            ),
            const SizedBox(height: 16),
           
          ],
        ),
      ),
    ),

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










                        await _uploadfileupload_field(createdEntity['id']);


                        await _uploadimageupload_field(createdEntity['id']);


 

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














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