import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../fields/base_field.dart';
import '../../../shared/widgets/buttons/modern_button.dart';
import '../../../core/constants/ui_constants.dart';

/// Reusable form component that dynamically renders fields based on field definitions
/// This allows UI to be independent of field types and enables reusability
class EntityForm extends StatefulWidget {
  final List<BaseField> fields;
  final Map<String, dynamic>? initialData;
  final Function(Map<String, dynamic>) onSubmit;
  final String submitButtonText;
  final bool isLoading;

  const EntityForm({
    super.key,
    required this.fields,
    this.initialData,
    required this.onSubmit,
    this.submitButtonText = 'Submit',
    this.isLoading = false,
  });

  @override
  State<EntityForm> createState() => _EntityFormState();
}

class _EntityFormState extends State<EntityForm> {
  final _formKey = GlobalKey<FormState>();
  final Map<String, TextEditingController> _controllers = {};
  final Map<String, BaseField> _fieldByKey = {};

  @override
  void initState() {
    super.initState();
    _initializeControllers();
  }

  void _initializeControllers() {
    for (final field in widget.fields) {
      _controllers[field.fieldKey] = TextEditingController(
        text: widget.initialData?[field.fieldKey]?.toString() ?? '',
      );
      _fieldByKey[field.fieldKey] = field;
    }
  }

  @override
  void dispose() {
    for (final controller in _controllers.values) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<DynamicThemeProvider>(
      builder: (context, dynamicThemeProvider, child) {
        final colorScheme = dynamicThemeProvider.getCurrentColorScheme(
          Theme.of(context).brightness == Brightness.dark,
        );

        return Form(
          key: _formKey,
          child: Column(
            children: [
              // Dynamic field rendering
              ...widget.fields.map((field) => Padding(
                    padding:
                        const EdgeInsets.only(bottom: UIConstants.spacing16),
                    child: field.buildField(
                      controller: _controllers[field.fieldKey]!,
                      colorScheme: colorScheme,
                      onChanged: () => setState(() {}),
                    ),
                  )),

              const SizedBox(height: UIConstants.spacing24),

              // Submit button
              ModernButton(
                text: widget.submitButtonText,
                type: ModernButtonType.primary,
                size: ModernButtonSize.large,
                isLoading: widget.isLoading,
                onPressed: widget.isLoading ? null : _handleSubmit,
              ),
            ],
          ),
        );
      },
    );
  }

  void _handleSubmit() {
    if (_formKey.currentState!.validate()) {
      // Dynamic cross-field match for any password-confirm group
      final Map<String, String> passwordByGroup = {};
      final Map<String, String> confirmByGroup = {};
      for (final entry in _controllers.entries) {
        final key = entry.key;
        final field = _fieldByKey[key];
        final props = field?.customProperties ?? const {};
        final isPassword = props['isPassword'] == true;
        if (!isPassword) continue;
        final String? groupId = props['groupId'];
        if (groupId == null) continue;
        final bool isConfirm = props['isConfirm'] == true;
        if (isConfirm) {
          confirmByGroup[groupId] = entry.value.text;
        } else {
          passwordByGroup[groupId] = entry.value.text;
        }
      }
      for (final gid in confirmByGroup.keys) {
        final confirm = confirmByGroup[gid] ?? '';
        final pass = passwordByGroup[gid] ?? '';
        if (confirm.isNotEmpty && confirm != pass) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Passwords do not match')),
          );
          return;
        }
      }

      final formData = <String, dynamic>{};
      for (final entry in _controllers.entries) {
        final key = entry.key;
        final field = _fieldByKey[key];
        final value = entry.value.text.trim();

        // Skip confirm entries for any password group
        final props = field?.customProperties ?? const {};
        final bool isPassword = props['isPassword'] == true;
        final bool isConfirm = props['isConfirm'] == true;
        if (isPassword && isConfirm) continue;

        formData[key] = value;
      }
      widget.onSubmit(formData);
    }
  }
}
