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


  ad8UpdateEntityScreen({required this.entity});

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

class _ad8UpdateEntityScreenState extends State<ad8UpdateEntityScreen> {
  final _formKey = GlobalKey<FormState>();




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



  void showUpdatesupportDialog(BuildContext parentContext) {

 
    final descriptionController = TextEditingController();
 

 
    final nameController = TextEditingController();
 


    final _dialogFormKey = GlobalKey<FormState>();

    showDialog(
           context: parentContext, // 👈 Parent context use karein
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Update Support'),
          content: Form(
            key: _dialogFormKey,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [

 
                ReusableTextField(
                  controller: descriptionController,
                  label: 'Description',
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter an Description';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
 

 
                ReusableTextField(
                  controller: nameController,
                  label: 'Name',
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter an Name';
                    }
                    return null;
                  },
                ),
                const SizedBox(height: 16),
 

              ],
            ),
          ),
          actions: [
            TextButton(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('Submit'),
              onPressed: () async {
                if (_dialogFormKey.currentState!.validate()) {
                  _dialogFormKey.currentState!.save();

                  // Save the data to the table or API
                  final Map<String, dynamic> SupportData = {
                    
 
                    'description': descriptionController.text,
                     

 
                    'name': nameController.text,
                     

                  };

                  try {
final provider =
          Provider.of<Ad8ViewModelScreen>(
                      parentContext, // 👈 Parent context use karein
 listen: false);
                    await provider.updateSupport(widget.entity['id'], SupportData);
                    Fluttertoast.showToast(msg: 'Entry added successfully');
                    Navigator.of(context).pop();
                  } catch (e) {
                    showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return AlertDialog(
                          title: const Text('Error'),
                          content: Text('Failed to add entry: $e'),
                          actions: [
                            TextButton(
                              child: const Text('OK'),
                              onPressed: () {
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        );
                      },
                    );
                  }
                }
              },
            ),
          ],
        );
      },
    );
  }


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


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



}

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




          TextButton(
            child: const Text(' Update Support'),
            onPressed: () {
              showUpdatesupportDialog(context);
            },
          ),

    

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




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