// 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 '../Form_d_viewModel/Form_d_view_model_screen.dart';
import 'Form_d_update_entity_screen.dart';

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

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

  @override
  State<Form_dDetailsScreen> createState() => _Form_dDetailsScreenState();
}

class _Form_dDetailsScreenState extends State<Form_dDetailsScreen> {
  void _navigateToUpdateScreen(Map<String, dynamic> entity) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ChangeNotifierProvider(
          create: (context) => Form_dViewModelScreen(),
          child: Form_dUpdateEntityScreen(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 Form_d?'),
          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<Form_dViewModelScreen>(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<Form_dViewModelScreen>(
      builder: (context, viewModel, child) {
        return EntityDetails(
          entity: widget.entity,
          onEdit: (entity) => _navigateToUpdateScreen(entity),
          onDelete: (entity) => _showDeleteDialog(entity),
          title: 'Form_d',
          displayFields: [
  {'key': 'namek', 'label': 'Namek', 'type': 'text'},

  {'key': 'number_field_a', 'label': 'Number Field a', 'type': 'number'},

  {'key': 'number_field_b', 'label': 'Number Field b', 'type': 'number'},

  {'key': 'calculated_sub', 'label': 'calculated sub', 'type': 'calculated_field'},

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