import 'package:flutter/material.dart';
import 'base_field.dart';

/// Read-only Data Grid field
/// - Fetches tabular data from an async loader
/// - Renders a DataTable
/// - Excluded from form submission
class DataGridField extends BaseField {
  final String fieldKey;
  final String label;
  final String hint;
  final bool isRequired;
  final Future<List<Map<String, dynamic>>> Function() dataLoader;

  DataGridField({
    required this.fieldKey,
    required this.label,
    this.hint = '',
    this.isRequired = false,
    required this.dataLoader,
  });

  @override
  String? Function(String?)? get validator => null;

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

  @override
  Widget buildField({
    required TextEditingController controller,
    required ColorScheme colorScheme,
    VoidCallback? onChanged,
  }) {
    return _DataGridFieldWidget(
      colorScheme: colorScheme,
      dataLoader: dataLoader,
    );
  }
}

class _DataGridFieldWidget extends StatefulWidget {
  final ColorScheme colorScheme;
  final Future<List<Map<String, dynamic>>> Function() dataLoader;

  const _DataGridFieldWidget({
    required this.colorScheme,
    required this.dataLoader,
  });

  @override
  State<_DataGridFieldWidget> createState() => _DataGridFieldWidgetState();
}

class _DataGridFieldWidgetState extends State<_DataGridFieldWidget> {
  late Future<List<Map<String, dynamic>>> _future;

  @override
  void initState() {
    super.initState();
    _future = widget.dataLoader();
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = widget.colorScheme;
    return FutureBuilder<List<Map<String, dynamic>>>(
      future: _future,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const LinearProgressIndicator(minHeight: 2);
        }
        if (snapshot.hasError) {
          return Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: colorScheme.errorContainer.withOpacity(0.2),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: colorScheme.error.withOpacity(0.3)),
            ),
            child: Row(
              children: [
                Icon(Icons.error_outline, color: colorScheme.error),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    snapshot.error.toString(),
                    style: TextStyle(color: colorScheme.error),
                  ),
                ),
              ],
            ),
          );
        }
        final data = snapshot.data ?? const <Map<String, dynamic>>[];
        if (data.isEmpty) {
          return Text('No data available',
              style: TextStyle(color: colorScheme.onSurfaceVariant));
        }
        final columns = data.first.keys.toList();
        return SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: DataTable(
            columnSpacing: 24,
            headingRowColor: MaterialStateColor.resolveWith(
                (_) => colorScheme.primaryContainer.withOpacity(0.3)),
            dataRowColor:
                MaterialStateColor.resolveWith((_) => colorScheme.surface),
            dividerThickness: 0.5,
            columns: columns
                .map((k) => DataColumn(
                      label: Text(k,
                          style: const TextStyle(fontWeight: FontWeight.w600)),
                    ))
                .toList(),
            rows: data
                .map(
                  (row) => DataRow(
                    cells: columns
                        .map((k) => DataCell(Text(row[k]?.toString() ?? '')))
                        .toList(),
                  ),
                )
                .toList(),
          ),
        );
      },
    );
  }
}
