// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
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 'package:barcode_widget/barcode_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import '../../../../widgets/custom_button.dart';
import '../../../../widgets/custom_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:intl/intl.dart';

import 'dart:math';
import '../../../../Reuseable/reusable_text_field.dart';
import '../../../../Reuseable/reusable_date_picker_field.dart';
import '../../../../Reuseable/reusable_date_time_picker_field.dart';
import '../../../../Reuseable/reusable_dropdown_field.dart';
import 'package:flutter/services.dart';
class dv2UpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  dv2UpdateEntityScreen({required this.entity});

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

class _dv2UpdateEntityScreenState extends State<dv2UpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();





final TextEditingController _inputcurrencyController = TextEditingController();
double editedcurrencyValue = 0.0;

final TextEditingController _inputcurrency2Controller = TextEditingController();
double editedcurrency2Value = 0.0;

late String inputDataqrcode_field;
  late TextEditingController controllerInputqrcode_field;


late String inputDataqrcode_field2;
  late TextEditingController controllerInputqrcode_field2;


 late  String inputDatabarcode_field; // By default barcode
  TextEditingController controllerInputbarcode_field = TextEditingController();


 late  String inputDatabarcode_field2; // By default barcode
  TextEditingController controllerInputbarcode_field2 = TextEditingController();





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




 // Convert the currency value to double if it's not already
    if (widget.entity['currency'] is String) {
      widget.entity['currency'] =
          double.tryParse(widget.entity['currency']) ?? 0.0;
    }

    // Initially set the controller text without formatting
    _inputcurrencyController.text = widget.entity['currency'].toString();
    editedcurrencyValue = widget.entity['currency'];

 // Convert the currency value to double if it's not already
    if (widget.entity['currency'] is String) {
      widget.entity['currency'] =
          double.tryParse(widget.entity['currency']) ?? 0.0;
    }

    // Initially set the controller text without formatting
    _inputcurrency2Controller.text = widget.entity['currency'].toString();
    editedcurrency2Value = widget.entity['currency'];

 inputDataqrcode_field = widget.entity['qrcode_field'] ?? "Hello";
    controllerInputqrcode_field = TextEditingController(text: inputDataqrcode_field);

 inputDataqrcode_field2 = widget.entity['qrcode_field2'] ?? "Hello";
    controllerInputqrcode_field2 = TextEditingController(text: inputDataqrcode_field2);

  inputDatabarcode_field = widget.entity['barcode_field'] ?? "Hello";
    controllerInputbarcode_field.text = inputDatabarcode_field;


  inputDatabarcode_field2 = widget.entity['barcode_field2'] ?? "Hello";
    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: "Update Dv2"),        actions: [


















        ],
),
      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),
     
      
 
      SizedBox(height: 16),
      TextFormField(
        initialValue: widget.entity['name'],
        decoration: InputDecoration(
          labelText: 'address name',
        ),
        onChanged: (value) {
          setState(() {
            widget.entity['name'] = value;
          });
        },
      ),
       

 
      SizedBox(height: 16),
      TextFormField(
        initialValue: widget.entity['last_name'],
        decoration: InputDecoration(
          labelText: 'address last_name',
        ),
        onChanged: (value) {
          setState(() {
            widget.entity['last_name'] = value;
          });
        },
      ),
       

      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),
     
      
 
      SizedBox(height: 16),
      TextFormField(
        initialValue: widget.entity['test'],
        decoration: InputDecoration(
          labelText: 'per_address test',
        ),
        onChanged: (value) {
          setState(() {
            widget.entity['test'] = value;
          });
        },
      ),
       

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



Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    TextFormField(
      controller: _inputcurrencyController,
      keyboardType: TextInputType.number,
      decoration: const InputDecoration(
        labelText: 'Edit Currency Value',
        prefixIcon: Icon(Icons.money),
                      border: OutlineInputBorder(),

      ),
      onChanged: (text) {
        setState(() {
          try {
            String currencyString = text;
            currencyString = currencyString.replaceAll(',', ''); // Remove commas
            currencyString = currencyString.replaceAll('₹', ''); // Remove currency symbol
            editedcurrencyValue = double.parse(currencyString);
            print("Parsed double value: $editedcurrencyValue");
          } catch (e) {
            print("Invalid input: $text");
            editedcurrencyValue = 0.0; // Set to a default value or handle the error accordingly
          }
        });
      },
      onSaved: (value) {
        widget.entity['currency'] = editedcurrencyValue;
      },
    ),
    SizedBox(height: 16),
    Text(
      'Edited Currency Value: ${editedcurrencyValue.toStringAsFixed(2)}', // Display formatted currency value
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
      ),
    ),
    SizedBox(height: 16),
    // Add other form fields here
  ],
),


Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    TextFormField(
      controller: _inputcurrency2Controller,
      keyboardType: TextInputType.number,
      decoration: const InputDecoration(
        labelText: 'Edit Currency Value',
        prefixIcon: Icon(Icons.money),
                      border: OutlineInputBorder(),

      ),
      onChanged: (text) {
        setState(() {
          try {
            String currencyString = text;
            currencyString = currencyString.replaceAll(',', ''); // Remove commas
            currencyString = currencyString.replaceAll('₹', ''); // Remove currency symbol
            editedcurrency2Value = double.parse(currencyString);
            print("Parsed double value: $editedcurrency2Value");
          } catch (e) {
            print("Invalid input: $text");
            editedcurrency2Value = 0.0; // Set to a default value or handle the error accordingly
          }
        });
      },
      onSaved: (value) {
        widget.entity['currency2'] = editedcurrency2Value;
      },
    ),
    SizedBox(height: 16),
    Text(
      'Edited Currency Value: ${editedcurrency2Value.toStringAsFixed(2)}', // Display formatted currency value
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
      ),
    ),
    SizedBox(height: 16),
    // Add other form fields here
  ],
),


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;
 widget.entity['qrcode_field'] = inputDataqrcode_field;
                });
              },
            ),
          ],
        ),

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;
 widget.entity['qrcode_field2'] = inputDataqrcode_field2;
                });
              },
            ),
          ],
        ),

    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;
                          widget.entity['barcode_field'] = inputDatabarcode_field;
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    // ElevatedButton(
                    //   onPressed: () {
                    //     setState(() {
                    //       inputData = controllerInput.text;
                    //     });
                    //   },
                    //   child: const Text('Generate Barcode'),
                    // ),
                  ],
                ),
  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;
                          widget.entity['barcode_field2'] = inputDatabarcode_field2;
                        });
                      },
                    ),
                    const SizedBox(height: 16),
                    // ElevatedButton(
                    //   onPressed: () {
                    //     setState(() {
                    //       inputData = controllerInput.text;
                    //     });
                    //   },
                    //   child: const Text('Generate Barcode'),
                    // ),
                  ],
                ),
  const SizedBox(height: 16),




 
          CustomButton(
                  height: getVerticalSize(50),
                  text: "Update",
                  margin: getMargin(top: 24, bottom: 5),
                  onTap: () async {
                    if (_formKey.currentState!.validate()) {
                      _formKey.currentState!.save();


















       
                        try {
                        await provider.updateEntity(
                              widget.entity[
                                  'id'], // Assuming 'id' is the key in your entity map
                              widget.entity);   



















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