// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// add_edit_basic_info.dart
//
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/widgets/autocomplete_text_field.dart';
import 'package:nokken/src/core/services/error/validation_service.dart';
import 'package:nokken/src/core/services/database/drugs_repository.dart';

/// Basic Information Section with name, dosage, and inventory fields
class BasicInfoSection extends ConsumerWidget {
  final TextEditingController nameController;
  final TextEditingController dosageController;
  final int currentQuantity;
  final int refillThreshold;
  final ValueChanged<int> onQuantityChanged;
  final ValueChanged<int> onThresholdChanged;

  const BasicInfoSection({
    super.key,
    required this.nameController,
    required this.dosageController,
    required this.currentQuantity,
    required this.refillThreshold,
    required this.onQuantityChanged,
    required this.onThresholdChanged,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // Watch the provider for drug name suggestions
    final drugNamesAsync = ref.watch(drugNamesProvider);

    return SharedWidgets.basicCard(
      context: context,
      title: 'Basic Information',
      children: [
        // Medication name field with autocomplete
        drugNamesAsync.when(
          data: (drugNames) {
            print('Rendering autocomplete with ${drugNames.length} options');
            // Only use autocomplete if we have options (we should if the file is loaded correctly)
            if (drugNames.isNotEmpty) {
              return AutocompleteTextField(
                controller: nameController,
                labelText: 'Medication Name',
                options: drugNames,
                hintText: 'Start typing medication name',
                onSelected: (value) {
                  print('Selected medication: $value');
                },
              );
            } else {
              // If no options available, fall back to regular text field
              return TextFormField(
                controller: nameController,
                decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                  labelText: 'Medication Name',
                ),
                validator: ValidationService.nameValidator,
              );
            }
          },
          error: (error, stackTrace) {
            // Log the error for debugging
            print('Error loading drug names: $error');
            print('Stack trace: $stackTrace');

            // On error, fall back to standard text field
            return TextFormField(
              controller: nameController,
              decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                labelText: 'Medication Name',
              ),
              validator: ValidationService.nameValidator,
            );
          },
          loading: () {
            // While loading, show autocomplete with loading state
            return AutocompleteTextField(
              controller: nameController,
              labelText: 'Medication Name',
              options: const [],
              hintText: 'Loading medications...',
              isLoading: true,
            );
          },
        ),
        SharedWidgets.verticalSpace(),
        // Dosage field
        TextFormField(
          controller: dosageController,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(
            labelText: 'Dosage',
            hintText: 'e.g., 50mg',
          ),
          validator: ValidationService.dosageValidator,
        ),
        SharedWidgets.verticalSpace(),
        // Inventory fields
        Row(
          children: [
            // Current quantity field
            Expanded(
              child: TextFormField(
                initialValue: currentQuantity.toString(),
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                  labelText: 'Quantity',
                ),
                onChanged: (value) {
                  final newValue = int.tryParse(value) ?? currentQuantity;
                  if (newValue >= 0) {
                    onQuantityChanged(newValue);
                  }
                },
              ),
            ),
            SharedWidgets.horizontalSpace(),
            // Refill threshold field
            Expanded(
              child: TextFormField(
                initialValue: refillThreshold.toString(),
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                  labelText: 'Refill At',
                ),
                onChanged: (value) {
                  final newValue = int.tryParse(value) ?? refillThreshold;
                  if (newValue >= 0) {
                    onThresholdChanged(newValue);
                  }
                },
              ),
            ),
          ],
        ),
      ],
    );
  }
}
