import 'package:flutter/material.dart';
import 'base_field.dart';
import '../ui/entity_form.dart';
import '../../../shared/widgets/inputs/modern_text_field.dart';

/// Calculated field
/// - Select multiple source fields from current form
/// - Apply operation: add, subtract, multiply, divide, concat
/// - Displays result (read-only) and stores it in controller
class CalculatedField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final List<String> sourceKeys; // keys of other fields in same form
  final String operation; // add|sub|mul|div|concat

  CalculatedField({
    required this.fieldKey,
    required this.label,
    this.hint = '',
    this.isRequired = false,
    required this.sourceKeys,
    required this.operation,
  });

  @override
  String? Function(String?)? get validator => (value) {
        if (isRequired && (value == null || value.isEmpty)) {
          return '$label is required';
        }
        return null;
      };

  @override
  Map<String, dynamic>? get customProperties => const {
        'isCalculated': true,
      };

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return _CalculatedWidget(
      label: label,
      hint: hint,
      controller: controller,
      colorScheme: colorScheme,
      sourceKeys: sourceKeys,
      operation: operation,
      validate: validator,
    );
  }
}

class _CalculatedWidget extends StatefulWidget {
  final String label;
  final String hint;
  final TextEditingController controller;
  final ColorScheme colorScheme;
  final List<String> sourceKeys;
  final String operation;
  final String? Function(String?)? validate;

  const _CalculatedWidget({
    required this.label,
    required this.hint,
    required this.controller,
    required this.colorScheme,
    required this.sourceKeys,
    required this.operation,
    required this.validate,
  });

  @override
  State<_CalculatedWidget> createState() => _CalculatedWidgetState();
}

class _CalculatedWidgetState extends State<_CalculatedWidget> {
  List<TextEditingController> _sources = const [];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final scope = EntityFormScope.of(context);
    if (scope != null) {
      _sources = widget.sourceKeys
          .map((k) => scope.controllers[k])
          .whereType<TextEditingController>()
          .toList();
      for (final c in _sources) {
        c.addListener(_recompute);
      }
      _recompute();
    }
  }

  @override
  void dispose() {
    for (final c in _sources) {
      c.removeListener(_recompute);
    }
    super.dispose();
  }

  void _recompute() {
    String result = '';
    if (widget.operation == 'Concatination') {
      result = _sources
          .map((c) => c.text.trim())
          .where((s) => s.isNotEmpty)
          .join(' ');
    } else {
      final nums =
          _sources.map((c) => double.tryParse(c.text.trim()) ?? 0.0).toList();
      if (nums.isEmpty) {
        result = '';
      } else {
        double acc = nums.first;
        for (int i = 1; i < nums.length; i++) {
          switch (widget.operation) {
            case 'Addition':
              acc += nums[i];
              break;
            case 'Subtraction':
              acc -= nums[i];
              break;
            case 'Multiplication':
              acc *= nums[i];
              break;
            case 'Division':
              if (nums[i] != 0) acc /= nums[i];
              break;
          }
        }
        result = acc.toString();
      }
    }
    if (widget.controller.text != result) {
      widget.controller.text = result;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return ModernTextField(
      label: widget.label,
      hint: widget.hint,
      controller: widget.controller,
      readOnly: true,
      validator: widget.validate,
      suffixIcon: const Icon(Icons.functions),
    );
  }
}
