// ignore_for_file: use_build_context_synchronously
import 'dart:convert';
import 'package:provider/provider.dart';
import '../Adv5_viewModel/Adv5_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 adv5UpdateEntityScreen extends StatefulWidget {
    final Map<String, dynamic> entity;


  adv5UpdateEntityScreen({required this.entity});

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

class _adv5UpdateEntityScreenState extends State<adv5UpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();




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















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


if (widget.entity['support'] != null) {
      supportList = List.from(widget.entity['support']);
    }













}

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
















        ],
),
      body:  SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
 
                        ReusableTextField(
                           
                            label: "Please Enter Name",
                            initialValue: widget.entity['name'] ?? '',

   // ValidationProperties
                            onSaved: (value) => widget.entity['name'] = value,
),
                    
                          SizedBox(height: 16),


const SizedBox(
  height: 20,
  child: Text(
    'Support',
    style: TextStyle(
      color: Colors.black,
      fontSize: 18,
      fontWeight: FontWeight.bold,
    ),
  ),
),

// Display existing support items
for (var i = 0; i < supportList.length; i++)
  Padding(
    padding: const EdgeInsets.symmetric(vertical: 8.0),
    child: Column(
      children: [

 
        // Field Option Input
        ReusableTextField(
          initialValue: supportList[i]['description'],
         // decoration: InputDecoration(
            label: 'Description',
          //  border: OutlineInputBorder(),
            //filled: true,
            //fillColor: Colors.grey[200],
          //),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please enter a field option';
            }
            return null;
          },
          onSaved: (value) {
            supportList[i]['description'] = value;
          },
   ),
                SizedBox(height: 8),

 

 
        // Field Option Input
        ReusableTextField(
          initialValue: supportList[i]['name'],
         // decoration: InputDecoration(
            label: 'Name',
          //  border: OutlineInputBorder(),
            //filled: true,
            //fillColor: Colors.grey[200],
          //),
          validator: (value) {
            if (value == null || value.isEmpty) {
              return 'Please enter a field option';
            }
            return null;
          },
          onSaved: (value) {
            supportList[i]['name'] = value;
          },
   ),
                SizedBox(height: 8),

 

     
        const SizedBox(height: 8),
        // Remove Item Button
        Align(
          alignment: Alignment.centerRight,
          child: IconButton(
            icon: const Icon(Icons.remove_circle_outline, color: Colors.red),
            onPressed: () {
              setState(() {
                supportList.removeAt(i);
              });
            },
          ),
        ),
      ],
    ),
  ),
// Button to add a new support item
const SizedBox(height: 16),
ElevatedButton(
  onPressed: () {
    setState(() {

      supportList.add({

 
        'description': '',
 

 
        'name': '',
 

      });

    });
  },
  style: ElevatedButton.styleFrom(
    backgroundColor: Colors.blue, // background (button) color
    // onPrimary: Colors.white, // foreground (text) color
    padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
    textStyle: const TextStyle(
      fontSize: 16,
      fontWeight: FontWeight.bold,
    ),
  ),
  child: const Text('Add Support'),
),


 ReusableTextField(
              initialValue: widget.entity['age'].toString(),
              onSaved: (value) => widget.entity['age']= value,
              label: "Enter age",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),

 ReusableTextField(
              initialValue: widget.entity['age2'].toString(),
              onSaved: (value) => widget.entity['age2']= value,
              label: "Enter age2",
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow((RegExp(r'[0-9]'))),
              ],
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a number';
                }
                return null;
              },
            ),









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


                        widget.entity['support'] = supportList;














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

setState(() {
                            // Update the fields with the reloaded data
                            widget.entity.clear();
                            // widget.entity.addAll(updatedEntity);
                            supportList = List.from(widget.entity['support']);
                          });















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