import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:em2rp/models/event_type_model.dart';
import 'package:em2rp/views/widgets/event_form/price_ht_ttc_fields.dart';

class EventBasicInfoSection extends StatelessWidget {
  final TextEditingController nameController;
  final TextEditingController basePriceController;
  final List<EventTypeModel> eventTypes;
  final bool isLoadingEventTypes;
  final String? selectedEventTypeId;
  final DateTime? startDateTime;
  final DateTime? endDateTime;
  final List<Map<String, dynamic>> selectedOptions;
  final Function(String?) onEventTypeChanged;
  final Function(DateTime?) onStartDateTimeChanged;
  final Function(DateTime?) onEndDateTimeChanged;
  final VoidCallback onAnyFieldChanged;

  const EventBasicInfoSection({
    super.key,
    required this.nameController,
    required this.basePriceController,
    required this.eventTypes,
    required this.isLoadingEventTypes,
    required this.selectedEventTypeId,
    required this.startDateTime,
    required this.endDateTime,
    required this.selectedOptions,
    required this.onEventTypeChanged,
    required this.onStartDateTimeChanged,
    required this.onEndDateTimeChanged,
    required this.onAnyFieldChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        TextFormField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: 'Nom de l\'événement*',
            border: OutlineInputBorder(),
            prefixIcon: Icon(Icons.event),
          ),
          validator: (v) => v == null || v.isEmpty ? 'Champ requis' : null,
        ),
        const SizedBox(height: 16),
        if (isLoadingEventTypes)
          const Center(child: CircularProgressIndicator())
        else
          DropdownButtonFormField<String>(
            initialValue: selectedEventTypeId,
            items: eventTypes
                .map((type) => DropdownMenuItem<String>(
              value: type.id,
              child: Text(type.name),
            ))
                .toList(),
            onChanged: onEventTypeChanged,
            decoration: const InputDecoration(
              labelText: 'Type d\'événement*',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.category),
            ),
            validator: (v) => v == null ? 'Sélectionnez un type' : null,
          ),
        const SizedBox(height: 16),
        _buildDateTimeRow(context),
        const SizedBox(height: 16),
        PriceHtTtcFields(
          basePriceController: basePriceController,
          onPriceChanged: onAnyFieldChanged,
          selectedOptions: selectedOptions,
        ),
      ],
    );
  }

  Widget _buildDateTimeRow(BuildContext context) {
    final startField = GestureDetector(
      onTap: () => _selectStartDateTime(context),
      child: AbsorbPointer(
        child: TextFormField(
          readOnly: true,
          decoration: const InputDecoration(
            labelText: 'Début*',
            border: OutlineInputBorder(),
            suffixIcon: Icon(Icons.edit_calendar),
          ),
          controller: TextEditingController(
            text: startDateTime == null
                ? ''
                : DateFormat('dd/MM/yyyy HH:mm').format(startDateTime!),
          ),
          validator: (v) => startDateTime == null ? 'Champ requis' : null,
        ),
      ),
    );

    final endField = GestureDetector(
      onTap: startDateTime == null ? null : () => _selectEndDateTime(context),
      child: AbsorbPointer(
        child: TextFormField(
          readOnly: true,
          decoration: const InputDecoration(
            labelText: 'Fin*',
            border: OutlineInputBorder(),
            suffixIcon: Icon(Icons.edit_calendar),
          ),
          controller: TextEditingController(
            text: endDateTime == null
                ? ''
                : DateFormat('dd/MM/yyyy HH:mm').format(endDateTime!),
          ),
          validator: (v) => endDateTime == null
              ? 'Champ requis'
              : (startDateTime != null &&
                      endDateTime != null &&
                      (endDateTime!.isBefore(startDateTime!) ||
                          endDateTime!.isAtSameMomentAs(startDateTime!)))
                  ? 'La date de fin doit être après la date de début'
                  : null,
        ),
      ),
    );

    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth > 500) {
          return Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: startField),
              const SizedBox(width: 16),
              Expanded(child: endField),
            ],
          );
        } else {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              startField,
              const SizedBox(height: 16),
              endField,
            ],
          );
        }
      },
    );
  }

  Future<void> _selectStartDateTime(BuildContext context) async {
    // Utiliser la date actuelle de l'événement ou aujourd'hui
    final initialDate = startDateTime ?? DateTime.now();

    final picked = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: DateTime(2020),
      lastDate: DateTime(2099),
    );
    if (picked != null) {
      // Utiliser l'heure actuelle de l'événement ou l'heure actuelle
      final initialTime = startDateTime != null
          ? TimeOfDay(hour: startDateTime!.hour, minute: startDateTime!.minute)
          : TimeOfDay.now();

      final time = await showTimePicker(
        context: context,
        initialTime: initialTime,
      );
      if (time != null) {
        final newDateTime = DateTime(
          picked.year,
          picked.month,
          picked.day,
          time.hour,
          time.minute,
        );
        onStartDateTimeChanged(newDateTime);
      }
    }
  }

  Future<void> _selectEndDateTime(BuildContext context) async {
    // Utiliser la date actuelle de fin ou date de début + 1h
    final initialDate = endDateTime ?? startDateTime!.add(const Duration(hours: 1));

    final picked = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: startDateTime!,
      lastDate: DateTime(2099),
    );
    if (picked != null) {
      // Utiliser l'heure actuelle de l'événement ou l'heure actuelle
      final initialTime = endDateTime != null
          ? TimeOfDay(hour: endDateTime!.hour, minute: endDateTime!.minute)
          : TimeOfDay.now();

      final time = await showTimePicker(
        context: context,
        initialTime: initialTime,
      );
      if (time != null) {
        final newDateTime = DateTime(
          picked.year,
          picked.month,
          picked.day,
          time.hour,
          time.minute,
        );
        onEndDateTimeChanged(newDateTime);
      }
    }
  }
}
