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

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

class _dv2CreateEntityScreenState extends State<dv2CreateEntityScreen> {

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


  final TextEditingController per_addressController = TextEditingController();


String inputValuecurrency = '';
String outputValuecurrency = '';

void _convertCurrency_currency() {
  String inputText = inputValuecurrency.replaceAll(',', ''); // Remove commas
  try {
    double parsedValue = double.parse(inputText); // Parse the value
    String formattedValue =
        parsedValue.toStringAsFixed(2); // Format to 2 decimal places
    setState(() {
      outputValuecurrency = formattedValue;
    });
  } catch (e) {
    setState(() {
      outputValuecurrency = "Invalid input";
    });
  }
}


String inputValuecurrency2 = '';
String outputValuecurrency2 = '';

void _convertCurrency_currency2() {
  String inputText = inputValuecurrency2.replaceAll(',', ''); // Remove commas
  try {
    double parsedValue = double.parse(inputText); // Parse the value
    String formattedValue =
        parsedValue.toStringAsFixed(2); // Format to 2 decimal places
    setState(() {
      outputValuecurrency2 = formattedValue;
    });
  } catch (e) {
    setState(() {
      outputValuecurrency2 = "Invalid input";
    });
  }
}


  String inputDataqrcode_field = 'Hello QR!';  // Default data for QR code generation
  TextEditingController controllerInputqrcode_field = TextEditingController();

  String inputDataqrcode_field2 = 'Hello QR!';  // Default data for QR code generation
  TextEditingController controllerInputqrcode_field2 = TextEditingController();

 String inputDatabarcode_field = 'Hello BarCode'; // By default barcode
  TextEditingController controllerInputbarcode_field = TextEditingController();

 String inputDatabarcode_field2 = 'Hello BarCode'; // By default barcode
  TextEditingController controllerInputbarcode_field2 = TextEditingController();



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








controllerInputqrcode_field.text = inputDataqrcode_field;

controllerInputqrcode_field2.text = inputDataqrcode_field2;

  controllerInputbarcode_field.text = inputDatabarcode_field;

  controllerInputbarcode_field2.text = inputDatabarcode_field2;



} 

  

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

















),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 Container(
  padding: EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    color: Colors.grey[200],
    borderRadius: BorderRadius.circular(8.0),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.2),
        spreadRadius: 2,
        blurRadius: 4,
        offset: Offset(0, 2),
      ),
    ],
  ),
  child: Column(
    children: [
      Text(
        "Address",
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 16),

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

  SizedBox(height: 16),
 

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

  SizedBox(height: 16),
 

 SizedBox(height: 16),
    ],
  ),
),
const SizedBox(height: 16),


Container(
  padding: EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    color: Colors.grey[200],
    borderRadius: BorderRadius.circular(8.0),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.2),
        spreadRadius: 2,
        blurRadius: 4,
        offset: Offset(0, 2),
      ),
    ],
  ),
  child: Column(
    children: [
      Text(
        "per address",
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
      SizedBox(height: 16),

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

  SizedBox(height: 16),
 

 SizedBox(height: 16),
    ],
  ),
),
const SizedBox(height: 16),


 TextFormField(
                        keyboardType: TextInputType.number,
                        onChanged: (text) {
                          setState(() {
                            inputValuecurrency = text;
                          });
                        },
                        decoration: const InputDecoration(
                          labelText:
                          'Enter Currency Value (with or without commas)',
                          prefixIcon: Icon(Icons.currency_rupee),
                      border: OutlineInputBorder(),

                        ),
                        onSaved: (value) {
                          _convertCurrency_currency();
                          formData['currency'] = outputValuecurrency;
                        }),
                const SizedBox(height: 16),  

 TextFormField(
                        keyboardType: TextInputType.number,
                        onChanged: (text) {
                          setState(() {
                            inputValuecurrency2 = text;
                          });
                        },
                        decoration: const InputDecoration(
                          labelText:
                          'Enter Currency Value (with or without commas)',
                          prefixIcon: Icon(Icons.currency_rupee),
                      border: OutlineInputBorder(),

                        ),
                        onSaved: (value) {
                          _convertCurrency_currency2();
                          formData['currency2'] = outputValuecurrency2;
                        }),
                const SizedBox(height: 16),  

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Generate QR Code',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            QrImageView(
              data: inputDataqrcode_field,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode_field,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode_field = value;
                });
              },
            ),
          ],
        ),
      ),
  

 Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              'Generate QR Code',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            QrImageView(
              data: inputDataqrcode_field2,
              version: QrVersions.auto,
              size: 200.0,
              gapless: false,
            ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputqrcode_field2,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for QR code',
              ),
              onChanged: (value) {
                setState(() {
                  inputDataqrcode_field2 = value;
                });
              },
            ),
          ],
        ),
      ),
  

 Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'Generate Barcode',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            if (inputDatabarcode_field.isNotEmpty)
              BarcodeWidget(
                barcode: Barcode.code128(), // Choose the type of barcode
                data: inputDatabarcode_field,
                width: 200,
                height: 80,
              ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputbarcode_field,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for barcode',
              ),
              onChanged: (value) {
                setState(() {
                  inputDatabarcode_field = value;
  formData['barcode_field'] = inputDatabarcode_field;
                });
              },
            ),
            const SizedBox(height: 16),
          
          ],
        ),

 Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'Generate Barcode',
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 16),
            if (inputDatabarcode_field2.isNotEmpty)
              BarcodeWidget(
                barcode: Barcode.code128(), // Choose the type of barcode
                data: inputDatabarcode_field2,
                width: 200,
                height: 80,
              ),
            const SizedBox(height: 16),
            TextField(
              controller: controllerInputbarcode_field2,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter data for barcode',
              ),
              onChanged: (value) {
                setState(() {
                  inputDatabarcode_field2 = value;
  formData['barcode_field2'] = inputDatabarcode_field2;
                });
              },
            ),
            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); 


















 

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


















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