// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../../BuilderField/shared/ui/entity_details.dart';
import '../Dv2_viewModel/Dv2_view_model_screen.dart';
import 'Dv2_update_entity_screen.dart';

class Dv2DetailsScreen extends StatefulWidget {
  final Map<String, dynamic> entity;

  const Dv2DetailsScreen({
    super.key,
    required this.entity,
  });

  @override
  State<Dv2DetailsScreen> createState() => _Dv2DetailsScreenState();
}

class _Dv2DetailsScreenState extends State<Dv2DetailsScreen> {
  void _navigateToUpdateScreen(Map<String, dynamic> entity) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChangeNotifierProvider(
          create: (context) => Dv2ViewModelScreen(),
          child: Dv2UpdateEntityScreen(entity: entity),
        ),
      ),
    ).then((_) {
      // Refresh the details screen with updated data
      setState(() {});
    });
  }

  void _showDeleteDialog(Map<String, dynamic> entity) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Confirm Deletion'),
          content: const Text('Are you sure you want to delete this Dv2?'),
          actions: [
            TextButton(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('Delete'),
              onPressed: () async {
                Navigator.of(context).pop();
                final vm =
                    Provider.of<Dv2ViewModelScreen>(context, listen: false);
                final success = await vm.deleteEntity(entity['id']);
                if (success && mounted) {
                  Navigator.pop(context); // Go back to list
                }
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<Dv2ViewModelScreen>(
      builder: (context, viewModel, child) {
        return EntityDetails(
          entity: widget.entity,
          onEdit: (entity) => _navigateToUpdateScreen(entity),
          onDelete: (entity) => _showDeleteDialog(entity),
          title: 'Dv2',
          displayFields: [

  
 {'key': 'test3', 'label': 'test3', 'type': 'field_group'},
 

  
 {'key': 'name', 'label': 'name', 'type': 'field_group'},
 

  
 {'key': 'last_name', 'label': 'last_name', 'type': 'field_group'},
 


  {'key': 'currency', 'label': 'Currency', 'type': 'currency'},

  {'key': 'qrcode_field', 'label': 'QRCode Field', 'type': 'qr_code'},

  {'key': 'barcode_field', 'label': 'BarCode Field', 'type': 'bar_code'},

  {'key': 'static', 'label': 'Static', 'type': 'communication'},

          ],
          isLoading: viewModel.isLoading,
        );
      },
    );
  }
}
